SemaDeclCXX.cpp 707 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621
  1. //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
  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 C++ declarations.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTConsumer.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ASTLambda.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/ComparisonCategories.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/EvaluatedExprVisitor.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/RecordLayout.h"
  24. #include "clang/AST/RecursiveASTVisitor.h"
  25. #include "clang/AST/StmtVisitor.h"
  26. #include "clang/AST/TypeLoc.h"
  27. #include "clang/AST/TypeOrdering.h"
  28. #include "clang/Basic/AttributeCommonInfo.h"
  29. #include "clang/Basic/PartialDiagnostic.h"
  30. #include "clang/Basic/Specifiers.h"
  31. #include "clang/Basic/TargetInfo.h"
  32. #include "clang/Lex/LiteralSupport.h"
  33. #include "clang/Lex/Preprocessor.h"
  34. #include "clang/Sema/CXXFieldCollector.h"
  35. #include "clang/Sema/DeclSpec.h"
  36. #include "clang/Sema/Initialization.h"
  37. #include "clang/Sema/Lookup.h"
  38. #include "clang/Sema/ParsedTemplate.h"
  39. #include "clang/Sema/Scope.h"
  40. #include "clang/Sema/ScopeInfo.h"
  41. #include "clang/Sema/SemaInternal.h"
  42. #include "clang/Sema/Template.h"
  43. #include "llvm/ADT/ScopeExit.h"
  44. #include "llvm/ADT/SmallString.h"
  45. #include "llvm/ADT/STLExtras.h"
  46. #include "llvm/ADT/StringExtras.h"
  47. #include <map>
  48. #include <optional>
  49. #include <set>
  50. using namespace clang;
  51. //===----------------------------------------------------------------------===//
  52. // CheckDefaultArgumentVisitor
  53. //===----------------------------------------------------------------------===//
  54. namespace {
  55. /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
  56. /// the default argument of a parameter to determine whether it
  57. /// contains any ill-formed subexpressions. For example, this will
  58. /// diagnose the use of local variables or parameters within the
  59. /// default argument expression.
  60. class CheckDefaultArgumentVisitor
  61. : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
  62. Sema &S;
  63. const Expr *DefaultArg;
  64. public:
  65. CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
  66. : S(S), DefaultArg(DefaultArg) {}
  67. bool VisitExpr(const Expr *Node);
  68. bool VisitDeclRefExpr(const DeclRefExpr *DRE);
  69. bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
  70. bool VisitLambdaExpr(const LambdaExpr *Lambda);
  71. bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
  72. };
  73. /// VisitExpr - Visit all of the children of this expression.
  74. bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
  75. bool IsInvalid = false;
  76. for (const Stmt *SubStmt : Node->children())
  77. IsInvalid |= Visit(SubStmt);
  78. return IsInvalid;
  79. }
  80. /// VisitDeclRefExpr - Visit a reference to a declaration, to
  81. /// determine whether this declaration can be used in the default
  82. /// argument expression.
  83. bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
  84. const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
  85. if (!isa<VarDecl, BindingDecl>(Decl))
  86. return false;
  87. if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
  88. // C++ [dcl.fct.default]p9:
  89. // [...] parameters of a function shall not be used in default
  90. // argument expressions, even if they are not evaluated. [...]
  91. //
  92. // C++17 [dcl.fct.default]p9 (by CWG 2082):
  93. // [...] A parameter shall not appear as a potentially-evaluated
  94. // expression in a default argument. [...]
  95. //
  96. if (DRE->isNonOdrUse() != NOUR_Unevaluated)
  97. return S.Diag(DRE->getBeginLoc(),
  98. diag::err_param_default_argument_references_param)
  99. << Param->getDeclName() << DefaultArg->getSourceRange();
  100. } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
  101. // C++ [dcl.fct.default]p7:
  102. // Local variables shall not be used in default argument
  103. // expressions.
  104. //
  105. // C++17 [dcl.fct.default]p7 (by CWG 2082):
  106. // A local variable shall not appear as a potentially-evaluated
  107. // expression in a default argument.
  108. //
  109. // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
  110. // Note: A local variable cannot be odr-used (6.3) in a default
  111. // argument.
  112. //
  113. if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
  114. return S.Diag(DRE->getBeginLoc(),
  115. diag::err_param_default_argument_references_local)
  116. << Decl << DefaultArg->getSourceRange();
  117. }
  118. return false;
  119. }
  120. /// VisitCXXThisExpr - Visit a C++ "this" expression.
  121. bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
  122. // C++ [dcl.fct.default]p8:
  123. // The keyword this shall not be used in a default argument of a
  124. // member function.
  125. return S.Diag(ThisE->getBeginLoc(),
  126. diag::err_param_default_argument_references_this)
  127. << ThisE->getSourceRange();
  128. }
  129. bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
  130. const PseudoObjectExpr *POE) {
  131. bool Invalid = false;
  132. for (const Expr *E : POE->semantics()) {
  133. // Look through bindings.
  134. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  135. E = OVE->getSourceExpr();
  136. assert(E && "pseudo-object binding without source expression?");
  137. }
  138. Invalid |= Visit(E);
  139. }
  140. return Invalid;
  141. }
  142. bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
  143. // [expr.prim.lambda.capture]p9
  144. // a lambda-expression appearing in a default argument cannot implicitly or
  145. // explicitly capture any local entity. Such a lambda-expression can still
  146. // have an init-capture if any full-expression in its initializer satisfies
  147. // the constraints of an expression appearing in a default argument.
  148. bool Invalid = false;
  149. for (const LambdaCapture &LC : Lambda->captures()) {
  150. if (!Lambda->isInitCapture(&LC))
  151. return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
  152. // Init captures are always VarDecl.
  153. auto *D = cast<VarDecl>(LC.getCapturedVar());
  154. Invalid |= Visit(D->getInit());
  155. }
  156. return Invalid;
  157. }
  158. } // namespace
  159. void
  160. Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
  161. const CXXMethodDecl *Method) {
  162. // If we have an MSAny spec already, don't bother.
  163. if (!Method || ComputedEST == EST_MSAny)
  164. return;
  165. const FunctionProtoType *Proto
  166. = Method->getType()->getAs<FunctionProtoType>();
  167. Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
  168. if (!Proto)
  169. return;
  170. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  171. // If we have a throw-all spec at this point, ignore the function.
  172. if (ComputedEST == EST_None)
  173. return;
  174. if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
  175. EST = EST_BasicNoexcept;
  176. switch (EST) {
  177. case EST_Unparsed:
  178. case EST_Uninstantiated:
  179. case EST_Unevaluated:
  180. llvm_unreachable("should not see unresolved exception specs here");
  181. // If this function can throw any exceptions, make a note of that.
  182. case EST_MSAny:
  183. case EST_None:
  184. // FIXME: Whichever we see last of MSAny and None determines our result.
  185. // We should make a consistent, order-independent choice here.
  186. ClearExceptions();
  187. ComputedEST = EST;
  188. return;
  189. case EST_NoexceptFalse:
  190. ClearExceptions();
  191. ComputedEST = EST_None;
  192. return;
  193. // FIXME: If the call to this decl is using any of its default arguments, we
  194. // need to search them for potentially-throwing calls.
  195. // If this function has a basic noexcept, it doesn't affect the outcome.
  196. case EST_BasicNoexcept:
  197. case EST_NoexceptTrue:
  198. case EST_NoThrow:
  199. return;
  200. // If we're still at noexcept(true) and there's a throw() callee,
  201. // change to that specification.
  202. case EST_DynamicNone:
  203. if (ComputedEST == EST_BasicNoexcept)
  204. ComputedEST = EST_DynamicNone;
  205. return;
  206. case EST_DependentNoexcept:
  207. llvm_unreachable(
  208. "should not generate implicit declarations for dependent cases");
  209. case EST_Dynamic:
  210. break;
  211. }
  212. assert(EST == EST_Dynamic && "EST case not considered earlier.");
  213. assert(ComputedEST != EST_None &&
  214. "Shouldn't collect exceptions when throw-all is guaranteed.");
  215. ComputedEST = EST_Dynamic;
  216. // Record the exceptions in this function's exception specification.
  217. for (const auto &E : Proto->exceptions())
  218. if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
  219. Exceptions.push_back(E);
  220. }
  221. void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
  222. if (!S || ComputedEST == EST_MSAny)
  223. return;
  224. // FIXME:
  225. //
  226. // C++0x [except.spec]p14:
  227. // [An] implicit exception-specification specifies the type-id T if and
  228. // only if T is allowed by the exception-specification of a function directly
  229. // invoked by f's implicit definition; f shall allow all exceptions if any
  230. // function it directly invokes allows all exceptions, and f shall allow no
  231. // exceptions if every function it directly invokes allows no exceptions.
  232. //
  233. // Note in particular that if an implicit exception-specification is generated
  234. // for a function containing a throw-expression, that specification can still
  235. // be noexcept(true).
  236. //
  237. // Note also that 'directly invoked' is not defined in the standard, and there
  238. // is no indication that we should only consider potentially-evaluated calls.
  239. //
  240. // Ultimately we should implement the intent of the standard: the exception
  241. // specification should be the set of exceptions which can be thrown by the
  242. // implicit definition. For now, we assume that any non-nothrow expression can
  243. // throw any exception.
  244. if (Self->canThrow(S))
  245. ComputedEST = EST_None;
  246. }
  247. ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
  248. SourceLocation EqualLoc) {
  249. if (RequireCompleteType(Param->getLocation(), Param->getType(),
  250. diag::err_typecheck_decl_incomplete_type))
  251. return true;
  252. // C++ [dcl.fct.default]p5
  253. // A default argument expression is implicitly converted (clause
  254. // 4) to the parameter type. The default argument expression has
  255. // the same semantic constraints as the initializer expression in
  256. // a declaration of a variable of the parameter type, using the
  257. // copy-initialization semantics (8.5).
  258. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  259. Param);
  260. InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
  261. EqualLoc);
  262. InitializationSequence InitSeq(*this, Entity, Kind, Arg);
  263. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
  264. if (Result.isInvalid())
  265. return true;
  266. Arg = Result.getAs<Expr>();
  267. CheckCompletedExpr(Arg, EqualLoc);
  268. Arg = MaybeCreateExprWithCleanups(Arg);
  269. return Arg;
  270. }
  271. void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
  272. SourceLocation EqualLoc) {
  273. // Add the default argument to the parameter
  274. Param->setDefaultArg(Arg);
  275. // We have already instantiated this parameter; provide each of the
  276. // instantiations with the uninstantiated default argument.
  277. UnparsedDefaultArgInstantiationsMap::iterator InstPos
  278. = UnparsedDefaultArgInstantiations.find(Param);
  279. if (InstPos != UnparsedDefaultArgInstantiations.end()) {
  280. for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
  281. InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
  282. // We're done tracking this parameter's instantiations.
  283. UnparsedDefaultArgInstantiations.erase(InstPos);
  284. }
  285. }
  286. /// ActOnParamDefaultArgument - Check whether the default argument
  287. /// provided for a function parameter is well-formed. If so, attach it
  288. /// to the parameter declaration.
  289. void
  290. Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
  291. Expr *DefaultArg) {
  292. if (!param || !DefaultArg)
  293. return;
  294. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  295. UnparsedDefaultArgLocs.erase(Param);
  296. auto Fail = [&] {
  297. Param->setInvalidDecl();
  298. Param->setDefaultArg(new (Context) OpaqueValueExpr(
  299. EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
  300. };
  301. // Default arguments are only permitted in C++
  302. if (!getLangOpts().CPlusPlus) {
  303. Diag(EqualLoc, diag::err_param_default_argument)
  304. << DefaultArg->getSourceRange();
  305. return Fail();
  306. }
  307. // Check for unexpanded parameter packs.
  308. if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
  309. return Fail();
  310. }
  311. // C++11 [dcl.fct.default]p3
  312. // A default argument expression [...] shall not be specified for a
  313. // parameter pack.
  314. if (Param->isParameterPack()) {
  315. Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
  316. << DefaultArg->getSourceRange();
  317. // Recover by discarding the default argument.
  318. Param->setDefaultArg(nullptr);
  319. return;
  320. }
  321. ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
  322. if (Result.isInvalid())
  323. return Fail();
  324. DefaultArg = Result.getAs<Expr>();
  325. // Check that the default argument is well-formed
  326. CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
  327. if (DefaultArgChecker.Visit(DefaultArg))
  328. return Fail();
  329. SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
  330. }
  331. /// ActOnParamUnparsedDefaultArgument - We've seen a default
  332. /// argument for a function parameter, but we can't parse it yet
  333. /// because we're inside a class definition. Note that this default
  334. /// argument will be parsed later.
  335. void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
  336. SourceLocation EqualLoc,
  337. SourceLocation ArgLoc) {
  338. if (!param)
  339. return;
  340. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  341. Param->setUnparsedDefaultArg();
  342. UnparsedDefaultArgLocs[Param] = ArgLoc;
  343. }
  344. /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
  345. /// the default argument for the parameter param failed.
  346. void Sema::ActOnParamDefaultArgumentError(Decl *param,
  347. SourceLocation EqualLoc) {
  348. if (!param)
  349. return;
  350. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  351. Param->setInvalidDecl();
  352. UnparsedDefaultArgLocs.erase(Param);
  353. Param->setDefaultArg(new (Context) OpaqueValueExpr(
  354. EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
  355. }
  356. /// CheckExtraCXXDefaultArguments - Check for any extra default
  357. /// arguments in the declarator, which is not a function declaration
  358. /// or definition and therefore is not permitted to have default
  359. /// arguments. This routine should be invoked for every declarator
  360. /// that is not a function declaration or definition.
  361. void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
  362. // C++ [dcl.fct.default]p3
  363. // A default argument expression shall be specified only in the
  364. // parameter-declaration-clause of a function declaration or in a
  365. // template-parameter (14.1). It shall not be specified for a
  366. // parameter pack. If it is specified in a
  367. // parameter-declaration-clause, it shall not occur within a
  368. // declarator or abstract-declarator of a parameter-declaration.
  369. bool MightBeFunction = D.isFunctionDeclarationContext();
  370. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  371. DeclaratorChunk &chunk = D.getTypeObject(i);
  372. if (chunk.Kind == DeclaratorChunk::Function) {
  373. if (MightBeFunction) {
  374. // This is a function declaration. It can have default arguments, but
  375. // keep looking in case its return type is a function type with default
  376. // arguments.
  377. MightBeFunction = false;
  378. continue;
  379. }
  380. for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
  381. ++argIdx) {
  382. ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
  383. if (Param->hasUnparsedDefaultArg()) {
  384. std::unique_ptr<CachedTokens> Toks =
  385. std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
  386. SourceRange SR;
  387. if (Toks->size() > 1)
  388. SR = SourceRange((*Toks)[1].getLocation(),
  389. Toks->back().getLocation());
  390. else
  391. SR = UnparsedDefaultArgLocs[Param];
  392. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  393. << SR;
  394. } else if (Param->getDefaultArg()) {
  395. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  396. << Param->getDefaultArg()->getSourceRange();
  397. Param->setDefaultArg(nullptr);
  398. }
  399. }
  400. } else if (chunk.Kind != DeclaratorChunk::Paren) {
  401. MightBeFunction = false;
  402. }
  403. }
  404. }
  405. static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
  406. return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
  407. return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
  408. });
  409. }
  410. /// MergeCXXFunctionDecl - Merge two declarations of the same C++
  411. /// function, once we already know that they have the same
  412. /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
  413. /// error, false otherwise.
  414. bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
  415. Scope *S) {
  416. bool Invalid = false;
  417. // The declaration context corresponding to the scope is the semantic
  418. // parent, unless this is a local function declaration, in which case
  419. // it is that surrounding function.
  420. DeclContext *ScopeDC = New->isLocalExternDecl()
  421. ? New->getLexicalDeclContext()
  422. : New->getDeclContext();
  423. // Find the previous declaration for the purpose of default arguments.
  424. FunctionDecl *PrevForDefaultArgs = Old;
  425. for (/**/; PrevForDefaultArgs;
  426. // Don't bother looking back past the latest decl if this is a local
  427. // extern declaration; nothing else could work.
  428. PrevForDefaultArgs = New->isLocalExternDecl()
  429. ? nullptr
  430. : PrevForDefaultArgs->getPreviousDecl()) {
  431. // Ignore hidden declarations.
  432. if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
  433. continue;
  434. if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
  435. !New->isCXXClassMember()) {
  436. // Ignore default arguments of old decl if they are not in
  437. // the same scope and this is not an out-of-line definition of
  438. // a member function.
  439. continue;
  440. }
  441. if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
  442. // If only one of these is a local function declaration, then they are
  443. // declared in different scopes, even though isDeclInScope may think
  444. // they're in the same scope. (If both are local, the scope check is
  445. // sufficient, and if neither is local, then they are in the same scope.)
  446. continue;
  447. }
  448. // We found the right previous declaration.
  449. break;
  450. }
  451. // C++ [dcl.fct.default]p4:
  452. // For non-template functions, default arguments can be added in
  453. // later declarations of a function in the same
  454. // scope. Declarations in different scopes have completely
  455. // distinct sets of default arguments. That is, declarations in
  456. // inner scopes do not acquire default arguments from
  457. // declarations in outer scopes, and vice versa. In a given
  458. // function declaration, all parameters subsequent to a
  459. // parameter with a default argument shall have default
  460. // arguments supplied in this or previous declarations. A
  461. // default argument shall not be redefined by a later
  462. // declaration (not even to the same value).
  463. //
  464. // C++ [dcl.fct.default]p6:
  465. // Except for member functions of class templates, the default arguments
  466. // in a member function definition that appears outside of the class
  467. // definition are added to the set of default arguments provided by the
  468. // member function declaration in the class definition.
  469. for (unsigned p = 0, NumParams = PrevForDefaultArgs
  470. ? PrevForDefaultArgs->getNumParams()
  471. : 0;
  472. p < NumParams; ++p) {
  473. ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
  474. ParmVarDecl *NewParam = New->getParamDecl(p);
  475. bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
  476. bool NewParamHasDfl = NewParam->hasDefaultArg();
  477. if (OldParamHasDfl && NewParamHasDfl) {
  478. unsigned DiagDefaultParamID =
  479. diag::err_param_default_argument_redefinition;
  480. // MSVC accepts that default parameters be redefined for member functions
  481. // of template class. The new default parameter's value is ignored.
  482. Invalid = true;
  483. if (getLangOpts().MicrosoftExt) {
  484. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
  485. if (MD && MD->getParent()->getDescribedClassTemplate()) {
  486. // Merge the old default argument into the new parameter.
  487. NewParam->setHasInheritedDefaultArg();
  488. if (OldParam->hasUninstantiatedDefaultArg())
  489. NewParam->setUninstantiatedDefaultArg(
  490. OldParam->getUninstantiatedDefaultArg());
  491. else
  492. NewParam->setDefaultArg(OldParam->getInit());
  493. DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
  494. Invalid = false;
  495. }
  496. }
  497. // FIXME: If we knew where the '=' was, we could easily provide a fix-it
  498. // hint here. Alternatively, we could walk the type-source information
  499. // for NewParam to find the last source location in the type... but it
  500. // isn't worth the effort right now. This is the kind of test case that
  501. // is hard to get right:
  502. // int f(int);
  503. // void g(int (*fp)(int) = f);
  504. // void g(int (*fp)(int) = &f);
  505. Diag(NewParam->getLocation(), DiagDefaultParamID)
  506. << NewParam->getDefaultArgRange();
  507. // Look for the function declaration where the default argument was
  508. // actually written, which may be a declaration prior to Old.
  509. for (auto Older = PrevForDefaultArgs;
  510. OldParam->hasInheritedDefaultArg(); /**/) {
  511. Older = Older->getPreviousDecl();
  512. OldParam = Older->getParamDecl(p);
  513. }
  514. Diag(OldParam->getLocation(), diag::note_previous_definition)
  515. << OldParam->getDefaultArgRange();
  516. } else if (OldParamHasDfl) {
  517. // Merge the old default argument into the new parameter unless the new
  518. // function is a friend declaration in a template class. In the latter
  519. // case the default arguments will be inherited when the friend
  520. // declaration will be instantiated.
  521. if (New->getFriendObjectKind() == Decl::FOK_None ||
  522. !New->getLexicalDeclContext()->isDependentContext()) {
  523. // It's important to use getInit() here; getDefaultArg()
  524. // strips off any top-level ExprWithCleanups.
  525. NewParam->setHasInheritedDefaultArg();
  526. if (OldParam->hasUnparsedDefaultArg())
  527. NewParam->setUnparsedDefaultArg();
  528. else if (OldParam->hasUninstantiatedDefaultArg())
  529. NewParam->setUninstantiatedDefaultArg(
  530. OldParam->getUninstantiatedDefaultArg());
  531. else
  532. NewParam->setDefaultArg(OldParam->getInit());
  533. }
  534. } else if (NewParamHasDfl) {
  535. if (New->getDescribedFunctionTemplate()) {
  536. // Paragraph 4, quoted above, only applies to non-template functions.
  537. Diag(NewParam->getLocation(),
  538. diag::err_param_default_argument_template_redecl)
  539. << NewParam->getDefaultArgRange();
  540. Diag(PrevForDefaultArgs->getLocation(),
  541. diag::note_template_prev_declaration)
  542. << false;
  543. } else if (New->getTemplateSpecializationKind()
  544. != TSK_ImplicitInstantiation &&
  545. New->getTemplateSpecializationKind() != TSK_Undeclared) {
  546. // C++ [temp.expr.spec]p21:
  547. // Default function arguments shall not be specified in a declaration
  548. // or a definition for one of the following explicit specializations:
  549. // - the explicit specialization of a function template;
  550. // - the explicit specialization of a member function template;
  551. // - the explicit specialization of a member function of a class
  552. // template where the class template specialization to which the
  553. // member function specialization belongs is implicitly
  554. // instantiated.
  555. Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
  556. << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
  557. << New->getDeclName()
  558. << NewParam->getDefaultArgRange();
  559. } else if (New->getDeclContext()->isDependentContext()) {
  560. // C++ [dcl.fct.default]p6 (DR217):
  561. // Default arguments for a member function of a class template shall
  562. // be specified on the initial declaration of the member function
  563. // within the class template.
  564. //
  565. // Reading the tea leaves a bit in DR217 and its reference to DR205
  566. // leads me to the conclusion that one cannot add default function
  567. // arguments for an out-of-line definition of a member function of a
  568. // dependent type.
  569. int WhichKind = 2;
  570. if (CXXRecordDecl *Record
  571. = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
  572. if (Record->getDescribedClassTemplate())
  573. WhichKind = 0;
  574. else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
  575. WhichKind = 1;
  576. else
  577. WhichKind = 2;
  578. }
  579. Diag(NewParam->getLocation(),
  580. diag::err_param_default_argument_member_template_redecl)
  581. << WhichKind
  582. << NewParam->getDefaultArgRange();
  583. }
  584. }
  585. }
  586. // DR1344: If a default argument is added outside a class definition and that
  587. // default argument makes the function a special member function, the program
  588. // is ill-formed. This can only happen for constructors.
  589. if (isa<CXXConstructorDecl>(New) &&
  590. New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
  591. CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
  592. OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
  593. if (NewSM != OldSM) {
  594. ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
  595. assert(NewParam->hasDefaultArg());
  596. Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
  597. << NewParam->getDefaultArgRange() << NewSM;
  598. Diag(Old->getLocation(), diag::note_previous_declaration);
  599. }
  600. }
  601. const FunctionDecl *Def;
  602. // C++11 [dcl.constexpr]p1: If any declaration of a function or function
  603. // template has a constexpr specifier then all its declarations shall
  604. // contain the constexpr specifier.
  605. if (New->getConstexprKind() != Old->getConstexprKind()) {
  606. Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
  607. << New << static_cast<int>(New->getConstexprKind())
  608. << static_cast<int>(Old->getConstexprKind());
  609. Diag(Old->getLocation(), diag::note_previous_declaration);
  610. Invalid = true;
  611. } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
  612. Old->isDefined(Def) &&
  613. // If a friend function is inlined but does not have 'inline'
  614. // specifier, it is a definition. Do not report attribute conflict
  615. // in this case, redefinition will be diagnosed later.
  616. (New->isInlineSpecified() ||
  617. New->getFriendObjectKind() == Decl::FOK_None)) {
  618. // C++11 [dcl.fcn.spec]p4:
  619. // If the definition of a function appears in a translation unit before its
  620. // first declaration as inline, the program is ill-formed.
  621. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  622. Diag(Def->getLocation(), diag::note_previous_definition);
  623. Invalid = true;
  624. }
  625. // C++17 [temp.deduct.guide]p3:
  626. // Two deduction guide declarations in the same translation unit
  627. // for the same class template shall not have equivalent
  628. // parameter-declaration-clauses.
  629. if (isa<CXXDeductionGuideDecl>(New) &&
  630. !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
  631. Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
  632. Diag(Old->getLocation(), diag::note_previous_declaration);
  633. }
  634. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
  635. // argument expression, that declaration shall be a definition and shall be
  636. // the only declaration of the function or function template in the
  637. // translation unit.
  638. if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
  639. functionDeclHasDefaultArgument(Old)) {
  640. Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  641. Diag(Old->getLocation(), diag::note_previous_declaration);
  642. Invalid = true;
  643. }
  644. // C++11 [temp.friend]p4 (DR329):
  645. // When a function is defined in a friend function declaration in a class
  646. // template, the function is instantiated when the function is odr-used.
  647. // The same restrictions on multiple declarations and definitions that
  648. // apply to non-template function declarations and definitions also apply
  649. // to these implicit definitions.
  650. const FunctionDecl *OldDefinition = nullptr;
  651. if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
  652. Old->isDefined(OldDefinition, true))
  653. CheckForFunctionRedefinition(New, OldDefinition);
  654. return Invalid;
  655. }
  656. NamedDecl *
  657. Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
  658. MultiTemplateParamsArg TemplateParamLists) {
  659. assert(D.isDecompositionDeclarator());
  660. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  661. // The syntax only allows a decomposition declarator as a simple-declaration,
  662. // a for-range-declaration, or a condition in Clang, but we parse it in more
  663. // cases than that.
  664. if (!D.mayHaveDecompositionDeclarator()) {
  665. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  666. << Decomp.getSourceRange();
  667. return nullptr;
  668. }
  669. if (!TemplateParamLists.empty()) {
  670. // FIXME: There's no rule against this, but there are also no rules that
  671. // would actually make it usable, so we reject it for now.
  672. Diag(TemplateParamLists.front()->getTemplateLoc(),
  673. diag::err_decomp_decl_template);
  674. return nullptr;
  675. }
  676. Diag(Decomp.getLSquareLoc(),
  677. !getLangOpts().CPlusPlus17
  678. ? diag::ext_decomp_decl
  679. : D.getContext() == DeclaratorContext::Condition
  680. ? diag::ext_decomp_decl_cond
  681. : diag::warn_cxx14_compat_decomp_decl)
  682. << Decomp.getSourceRange();
  683. // The semantic context is always just the current context.
  684. DeclContext *const DC = CurContext;
  685. // C++17 [dcl.dcl]/8:
  686. // The decl-specifier-seq shall contain only the type-specifier auto
  687. // and cv-qualifiers.
  688. // C++20 [dcl.dcl]/8:
  689. // If decl-specifier-seq contains any decl-specifier other than static,
  690. // thread_local, auto, or cv-qualifiers, the program is ill-formed.
  691. // C++2b [dcl.pre]/6:
  692. // Each decl-specifier in the decl-specifier-seq shall be static,
  693. // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
  694. auto &DS = D.getDeclSpec();
  695. {
  696. // Note: While constrained-auto needs to be checked, we do so separately so
  697. // we can emit a better diagnostic.
  698. SmallVector<StringRef, 8> BadSpecifiers;
  699. SmallVector<SourceLocation, 8> BadSpecifierLocs;
  700. SmallVector<StringRef, 8> CPlusPlus20Specifiers;
  701. SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
  702. if (auto SCS = DS.getStorageClassSpec()) {
  703. if (SCS == DeclSpec::SCS_static) {
  704. CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
  705. CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
  706. } else {
  707. BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
  708. BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
  709. }
  710. }
  711. if (auto TSCS = DS.getThreadStorageClassSpec()) {
  712. CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
  713. CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
  714. }
  715. if (DS.hasConstexprSpecifier()) {
  716. BadSpecifiers.push_back(
  717. DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
  718. BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
  719. }
  720. if (DS.isInlineSpecified()) {
  721. BadSpecifiers.push_back("inline");
  722. BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
  723. }
  724. if (!BadSpecifiers.empty()) {
  725. auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
  726. Err << (int)BadSpecifiers.size()
  727. << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
  728. // Don't add FixItHints to remove the specifiers; we do still respect
  729. // them when building the underlying variable.
  730. for (auto Loc : BadSpecifierLocs)
  731. Err << SourceRange(Loc, Loc);
  732. } else if (!CPlusPlus20Specifiers.empty()) {
  733. auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
  734. getLangOpts().CPlusPlus20
  735. ? diag::warn_cxx17_compat_decomp_decl_spec
  736. : diag::ext_decomp_decl_spec);
  737. Warn << (int)CPlusPlus20Specifiers.size()
  738. << llvm::join(CPlusPlus20Specifiers.begin(),
  739. CPlusPlus20Specifiers.end(), " ");
  740. for (auto Loc : CPlusPlus20SpecifierLocs)
  741. Warn << SourceRange(Loc, Loc);
  742. }
  743. // We can't recover from it being declared as a typedef.
  744. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  745. return nullptr;
  746. }
  747. // C++2a [dcl.struct.bind]p1:
  748. // A cv that includes volatile is deprecated
  749. if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
  750. getLangOpts().CPlusPlus20)
  751. Diag(DS.getVolatileSpecLoc(),
  752. diag::warn_deprecated_volatile_structured_binding);
  753. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  754. QualType R = TInfo->getType();
  755. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  756. UPPC_DeclarationType))
  757. D.setInvalidType();
  758. // The syntax only allows a single ref-qualifier prior to the decomposition
  759. // declarator. No other declarator chunks are permitted. Also check the type
  760. // specifier here.
  761. if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
  762. D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
  763. (D.getNumTypeObjects() == 1 &&
  764. D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
  765. Diag(Decomp.getLSquareLoc(),
  766. (D.hasGroupingParens() ||
  767. (D.getNumTypeObjects() &&
  768. D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
  769. ? diag::err_decomp_decl_parens
  770. : diag::err_decomp_decl_type)
  771. << R;
  772. // In most cases, there's no actual problem with an explicitly-specified
  773. // type, but a function type won't work here, and ActOnVariableDeclarator
  774. // shouldn't be called for such a type.
  775. if (R->isFunctionType())
  776. D.setInvalidType();
  777. }
  778. // Constrained auto is prohibited by [decl.pre]p6, so check that here.
  779. if (DS.isConstrainedAuto()) {
  780. TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
  781. assert(TemplRep->Kind == TNK_Concept_template &&
  782. "No other template kind should be possible for a constrained auto");
  783. SourceRange TemplRange{TemplRep->TemplateNameLoc,
  784. TemplRep->RAngleLoc.isValid()
  785. ? TemplRep->RAngleLoc
  786. : TemplRep->TemplateNameLoc};
  787. Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
  788. << TemplRange << FixItHint::CreateRemoval(TemplRange);
  789. }
  790. // Build the BindingDecls.
  791. SmallVector<BindingDecl*, 8> Bindings;
  792. // Build the BindingDecls.
  793. for (auto &B : D.getDecompositionDeclarator().bindings()) {
  794. // Check for name conflicts.
  795. DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
  796. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  797. ForVisibleRedeclaration);
  798. LookupName(Previous, S,
  799. /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
  800. // It's not permitted to shadow a template parameter name.
  801. if (Previous.isSingleResult() &&
  802. Previous.getFoundDecl()->isTemplateParameter()) {
  803. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  804. Previous.getFoundDecl());
  805. Previous.clear();
  806. }
  807. auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
  808. // Find the shadowed declaration before filtering for scope.
  809. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  810. ? getShadowedDeclaration(BD, Previous)
  811. : nullptr;
  812. bool ConsiderLinkage = DC->isFunctionOrMethod() &&
  813. DS.getStorageClassSpec() == DeclSpec::SCS_extern;
  814. FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
  815. /*AllowInlineNamespace*/false);
  816. if (!Previous.empty()) {
  817. auto *Old = Previous.getRepresentativeDecl();
  818. Diag(B.NameLoc, diag::err_redefinition) << B.Name;
  819. Diag(Old->getLocation(), diag::note_previous_definition);
  820. } else if (ShadowedDecl && !D.isRedeclaration()) {
  821. CheckShadow(BD, ShadowedDecl, Previous);
  822. }
  823. PushOnScopeChains(BD, S, true);
  824. Bindings.push_back(BD);
  825. ParsingInitForAutoVars.insert(BD);
  826. }
  827. // There are no prior lookup results for the variable itself, because it
  828. // is unnamed.
  829. DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
  830. Decomp.getLSquareLoc());
  831. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  832. ForVisibleRedeclaration);
  833. // Build the variable that holds the non-decomposed object.
  834. bool AddToScope = true;
  835. NamedDecl *New =
  836. ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
  837. MultiTemplateParamsArg(), AddToScope, Bindings);
  838. if (AddToScope) {
  839. S->AddDecl(New);
  840. CurContext->addHiddenDecl(New);
  841. }
  842. if (isInOpenMPDeclareTargetContext())
  843. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  844. return New;
  845. }
  846. static bool checkSimpleDecomposition(
  847. Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
  848. QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
  849. llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
  850. if ((int64_t)Bindings.size() != NumElems) {
  851. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  852. << DecompType << (unsigned)Bindings.size()
  853. << (unsigned)NumElems.getLimitedValue(UINT_MAX)
  854. << toString(NumElems, 10) << (NumElems < Bindings.size());
  855. return true;
  856. }
  857. unsigned I = 0;
  858. for (auto *B : Bindings) {
  859. SourceLocation Loc = B->getLocation();
  860. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  861. if (E.isInvalid())
  862. return true;
  863. E = GetInit(Loc, E.get(), I++);
  864. if (E.isInvalid())
  865. return true;
  866. B->setBinding(ElemType, E.get());
  867. }
  868. return false;
  869. }
  870. static bool checkArrayLikeDecomposition(Sema &S,
  871. ArrayRef<BindingDecl *> Bindings,
  872. ValueDecl *Src, QualType DecompType,
  873. const llvm::APSInt &NumElems,
  874. QualType ElemType) {
  875. return checkSimpleDecomposition(
  876. S, Bindings, Src, DecompType, NumElems, ElemType,
  877. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  878. ExprResult E = S.ActOnIntegerConstant(Loc, I);
  879. if (E.isInvalid())
  880. return ExprError();
  881. return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
  882. });
  883. }
  884. static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  885. ValueDecl *Src, QualType DecompType,
  886. const ConstantArrayType *CAT) {
  887. return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
  888. llvm::APSInt(CAT->getSize()),
  889. CAT->getElementType());
  890. }
  891. static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  892. ValueDecl *Src, QualType DecompType,
  893. const VectorType *VT) {
  894. return checkArrayLikeDecomposition(
  895. S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
  896. S.Context.getQualifiedType(VT->getElementType(),
  897. DecompType.getQualifiers()));
  898. }
  899. static bool checkComplexDecomposition(Sema &S,
  900. ArrayRef<BindingDecl *> Bindings,
  901. ValueDecl *Src, QualType DecompType,
  902. const ComplexType *CT) {
  903. return checkSimpleDecomposition(
  904. S, Bindings, Src, DecompType, llvm::APSInt::get(2),
  905. S.Context.getQualifiedType(CT->getElementType(),
  906. DecompType.getQualifiers()),
  907. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  908. return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
  909. });
  910. }
  911. static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
  912. TemplateArgumentListInfo &Args,
  913. const TemplateParameterList *Params) {
  914. SmallString<128> SS;
  915. llvm::raw_svector_ostream OS(SS);
  916. bool First = true;
  917. unsigned I = 0;
  918. for (auto &Arg : Args.arguments()) {
  919. if (!First)
  920. OS << ", ";
  921. Arg.getArgument().print(PrintingPolicy, OS,
  922. TemplateParameterList::shouldIncludeTypeForArgument(
  923. PrintingPolicy, Params, I));
  924. First = false;
  925. I++;
  926. }
  927. return std::string(OS.str());
  928. }
  929. static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
  930. SourceLocation Loc, StringRef Trait,
  931. TemplateArgumentListInfo &Args,
  932. unsigned DiagID) {
  933. auto DiagnoseMissing = [&] {
  934. if (DiagID)
  935. S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
  936. Args, /*Params*/ nullptr);
  937. return true;
  938. };
  939. // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
  940. NamespaceDecl *Std = S.getStdNamespace();
  941. if (!Std)
  942. return DiagnoseMissing();
  943. // Look up the trait itself, within namespace std. We can diagnose various
  944. // problems with this lookup even if we've been asked to not diagnose a
  945. // missing specialization, because this can only fail if the user has been
  946. // declaring their own names in namespace std or we don't support the
  947. // standard library implementation in use.
  948. LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
  949. Loc, Sema::LookupOrdinaryName);
  950. if (!S.LookupQualifiedName(Result, Std))
  951. return DiagnoseMissing();
  952. if (Result.isAmbiguous())
  953. return true;
  954. ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
  955. if (!TraitTD) {
  956. Result.suppressDiagnostics();
  957. NamedDecl *Found = *Result.begin();
  958. S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
  959. S.Diag(Found->getLocation(), diag::note_declared_at);
  960. return true;
  961. }
  962. // Build the template-id.
  963. QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
  964. if (TraitTy.isNull())
  965. return true;
  966. if (!S.isCompleteType(Loc, TraitTy)) {
  967. if (DiagID)
  968. S.RequireCompleteType(
  969. Loc, TraitTy, DiagID,
  970. printTemplateArgs(S.Context.getPrintingPolicy(), Args,
  971. TraitTD->getTemplateParameters()));
  972. return true;
  973. }
  974. CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
  975. assert(RD && "specialization of class template is not a class?");
  976. // Look up the member of the trait type.
  977. S.LookupQualifiedName(TraitMemberLookup, RD);
  978. return TraitMemberLookup.isAmbiguous();
  979. }
  980. static TemplateArgumentLoc
  981. getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
  982. uint64_t I) {
  983. TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
  984. return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
  985. }
  986. static TemplateArgumentLoc
  987. getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
  988. return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
  989. }
  990. namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
  991. static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
  992. llvm::APSInt &Size) {
  993. EnterExpressionEvaluationContext ContextRAII(
  994. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  995. DeclarationName Value = S.PP.getIdentifierInfo("value");
  996. LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
  997. // Form template argument list for tuple_size<T>.
  998. TemplateArgumentListInfo Args(Loc, Loc);
  999. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  1000. // If there's no tuple_size specialization or the lookup of 'value' is empty,
  1001. // it's not tuple-like.
  1002. if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
  1003. R.empty())
  1004. return IsTupleLike::NotTupleLike;
  1005. // If we get this far, we've committed to the tuple interpretation, but
  1006. // we can still fail if there actually isn't a usable ::value.
  1007. struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
  1008. LookupResult &R;
  1009. TemplateArgumentListInfo &Args;
  1010. ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
  1011. : R(R), Args(Args) {}
  1012. Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
  1013. SourceLocation Loc) override {
  1014. return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
  1015. << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
  1016. /*Params*/ nullptr);
  1017. }
  1018. } Diagnoser(R, Args);
  1019. ExprResult E =
  1020. S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
  1021. if (E.isInvalid())
  1022. return IsTupleLike::Error;
  1023. E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
  1024. if (E.isInvalid())
  1025. return IsTupleLike::Error;
  1026. return IsTupleLike::TupleLike;
  1027. }
  1028. /// \return std::tuple_element<I, T>::type.
  1029. static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
  1030. unsigned I, QualType T) {
  1031. // Form template argument list for tuple_element<I, T>.
  1032. TemplateArgumentListInfo Args(Loc, Loc);
  1033. Args.addArgument(
  1034. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  1035. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  1036. DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
  1037. LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
  1038. if (lookupStdTypeTraitMember(
  1039. S, R, Loc, "tuple_element", Args,
  1040. diag::err_decomp_decl_std_tuple_element_not_specialized))
  1041. return QualType();
  1042. auto *TD = R.getAsSingle<TypeDecl>();
  1043. if (!TD) {
  1044. R.suppressDiagnostics();
  1045. S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
  1046. << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
  1047. /*Params*/ nullptr);
  1048. if (!R.empty())
  1049. S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
  1050. return QualType();
  1051. }
  1052. return S.Context.getTypeDeclType(TD);
  1053. }
  1054. namespace {
  1055. struct InitializingBinding {
  1056. Sema &S;
  1057. InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
  1058. Sema::CodeSynthesisContext Ctx;
  1059. Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
  1060. Ctx.PointOfInstantiation = BD->getLocation();
  1061. Ctx.Entity = BD;
  1062. S.pushCodeSynthesisContext(Ctx);
  1063. }
  1064. ~InitializingBinding() {
  1065. S.popCodeSynthesisContext();
  1066. }
  1067. };
  1068. }
  1069. static bool checkTupleLikeDecomposition(Sema &S,
  1070. ArrayRef<BindingDecl *> Bindings,
  1071. VarDecl *Src, QualType DecompType,
  1072. const llvm::APSInt &TupleSize) {
  1073. if ((int64_t)Bindings.size() != TupleSize) {
  1074. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  1075. << DecompType << (unsigned)Bindings.size()
  1076. << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
  1077. << toString(TupleSize, 10) << (TupleSize < Bindings.size());
  1078. return true;
  1079. }
  1080. if (Bindings.empty())
  1081. return false;
  1082. DeclarationName GetDN = S.PP.getIdentifierInfo("get");
  1083. // [dcl.decomp]p3:
  1084. // The unqualified-id get is looked up in the scope of E by class member
  1085. // access lookup ...
  1086. LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
  1087. bool UseMemberGet = false;
  1088. if (S.isCompleteType(Src->getLocation(), DecompType)) {
  1089. if (auto *RD = DecompType->getAsCXXRecordDecl())
  1090. S.LookupQualifiedName(MemberGet, RD);
  1091. if (MemberGet.isAmbiguous())
  1092. return true;
  1093. // ... and if that finds at least one declaration that is a function
  1094. // template whose first template parameter is a non-type parameter ...
  1095. for (NamedDecl *D : MemberGet) {
  1096. if (FunctionTemplateDecl *FTD =
  1097. dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
  1098. TemplateParameterList *TPL = FTD->getTemplateParameters();
  1099. if (TPL->size() != 0 &&
  1100. isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
  1101. // ... the initializer is e.get<i>().
  1102. UseMemberGet = true;
  1103. break;
  1104. }
  1105. }
  1106. }
  1107. }
  1108. unsigned I = 0;
  1109. for (auto *B : Bindings) {
  1110. InitializingBinding InitContext(S, B);
  1111. SourceLocation Loc = B->getLocation();
  1112. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1113. if (E.isInvalid())
  1114. return true;
  1115. // e is an lvalue if the type of the entity is an lvalue reference and
  1116. // an xvalue otherwise
  1117. if (!Src->getType()->isLValueReferenceType())
  1118. E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
  1119. E.get(), nullptr, VK_XValue,
  1120. FPOptionsOverride());
  1121. TemplateArgumentListInfo Args(Loc, Loc);
  1122. Args.addArgument(
  1123. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  1124. if (UseMemberGet) {
  1125. // if [lookup of member get] finds at least one declaration, the
  1126. // initializer is e.get<i-1>().
  1127. E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
  1128. CXXScopeSpec(), SourceLocation(), nullptr,
  1129. MemberGet, &Args, nullptr);
  1130. if (E.isInvalid())
  1131. return true;
  1132. E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
  1133. } else {
  1134. // Otherwise, the initializer is get<i-1>(e), where get is looked up
  1135. // in the associated namespaces.
  1136. Expr *Get = UnresolvedLookupExpr::Create(
  1137. S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
  1138. DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
  1139. UnresolvedSetIterator(), UnresolvedSetIterator());
  1140. Expr *Arg = E.get();
  1141. E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
  1142. }
  1143. if (E.isInvalid())
  1144. return true;
  1145. Expr *Init = E.get();
  1146. // Given the type T designated by std::tuple_element<i - 1, E>::type,
  1147. QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
  1148. if (T.isNull())
  1149. return true;
  1150. // each vi is a variable of type "reference to T" initialized with the
  1151. // initializer, where the reference is an lvalue reference if the
  1152. // initializer is an lvalue and an rvalue reference otherwise
  1153. QualType RefType =
  1154. S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
  1155. if (RefType.isNull())
  1156. return true;
  1157. auto *RefVD = VarDecl::Create(
  1158. S.Context, Src->getDeclContext(), Loc, Loc,
  1159. B->getDeclName().getAsIdentifierInfo(), RefType,
  1160. S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
  1161. RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
  1162. RefVD->setTSCSpec(Src->getTSCSpec());
  1163. RefVD->setImplicit();
  1164. if (Src->isInlineSpecified())
  1165. RefVD->setInlineSpecified();
  1166. RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
  1167. InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
  1168. InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
  1169. InitializationSequence Seq(S, Entity, Kind, Init);
  1170. E = Seq.Perform(S, Entity, Kind, Init);
  1171. if (E.isInvalid())
  1172. return true;
  1173. E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
  1174. if (E.isInvalid())
  1175. return true;
  1176. RefVD->setInit(E.get());
  1177. S.CheckCompleteVariableDeclaration(RefVD);
  1178. E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
  1179. DeclarationNameInfo(B->getDeclName(), Loc),
  1180. RefVD);
  1181. if (E.isInvalid())
  1182. return true;
  1183. B->setBinding(T, E.get());
  1184. I++;
  1185. }
  1186. return false;
  1187. }
  1188. /// Find the base class to decompose in a built-in decomposition of a class type.
  1189. /// This base class search is, unfortunately, not quite like any other that we
  1190. /// perform anywhere else in C++.
  1191. static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
  1192. const CXXRecordDecl *RD,
  1193. CXXCastPath &BasePath) {
  1194. auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
  1195. CXXBasePath &Path) {
  1196. return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
  1197. };
  1198. const CXXRecordDecl *ClassWithFields = nullptr;
  1199. AccessSpecifier AS = AS_public;
  1200. if (RD->hasDirectFields())
  1201. // [dcl.decomp]p4:
  1202. // Otherwise, all of E's non-static data members shall be public direct
  1203. // members of E ...
  1204. ClassWithFields = RD;
  1205. else {
  1206. // ... or of ...
  1207. CXXBasePaths Paths;
  1208. Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
  1209. if (!RD->lookupInBases(BaseHasFields, Paths)) {
  1210. // If no classes have fields, just decompose RD itself. (This will work
  1211. // if and only if zero bindings were provided.)
  1212. return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
  1213. }
  1214. CXXBasePath *BestPath = nullptr;
  1215. for (auto &P : Paths) {
  1216. if (!BestPath)
  1217. BestPath = &P;
  1218. else if (!S.Context.hasSameType(P.back().Base->getType(),
  1219. BestPath->back().Base->getType())) {
  1220. // ... the same ...
  1221. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1222. << false << RD << BestPath->back().Base->getType()
  1223. << P.back().Base->getType();
  1224. return DeclAccessPair();
  1225. } else if (P.Access < BestPath->Access) {
  1226. BestPath = &P;
  1227. }
  1228. }
  1229. // ... unambiguous ...
  1230. QualType BaseType = BestPath->back().Base->getType();
  1231. if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
  1232. S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
  1233. << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
  1234. return DeclAccessPair();
  1235. }
  1236. // ... [accessible, implied by other rules] base class of E.
  1237. S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
  1238. *BestPath, diag::err_decomp_decl_inaccessible_base);
  1239. AS = BestPath->Access;
  1240. ClassWithFields = BaseType->getAsCXXRecordDecl();
  1241. S.BuildBasePathArray(Paths, BasePath);
  1242. }
  1243. // The above search did not check whether the selected class itself has base
  1244. // classes with fields, so check that now.
  1245. CXXBasePaths Paths;
  1246. if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
  1247. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1248. << (ClassWithFields == RD) << RD << ClassWithFields
  1249. << Paths.front().back().Base->getType();
  1250. return DeclAccessPair();
  1251. }
  1252. return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
  1253. }
  1254. static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  1255. ValueDecl *Src, QualType DecompType,
  1256. const CXXRecordDecl *OrigRD) {
  1257. if (S.RequireCompleteType(Src->getLocation(), DecompType,
  1258. diag::err_incomplete_type))
  1259. return true;
  1260. CXXCastPath BasePath;
  1261. DeclAccessPair BasePair =
  1262. findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
  1263. const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
  1264. if (!RD)
  1265. return true;
  1266. QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
  1267. DecompType.getQualifiers());
  1268. auto DiagnoseBadNumberOfBindings = [&]() -> bool {
  1269. unsigned NumFields = llvm::count_if(
  1270. RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
  1271. assert(Bindings.size() != NumFields);
  1272. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  1273. << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
  1274. << (NumFields < Bindings.size());
  1275. return true;
  1276. };
  1277. // all of E's non-static data members shall be [...] well-formed
  1278. // when named as e.name in the context of the structured binding,
  1279. // E shall not have an anonymous union member, ...
  1280. unsigned I = 0;
  1281. for (auto *FD : RD->fields()) {
  1282. if (FD->isUnnamedBitfield())
  1283. continue;
  1284. // All the non-static data members are required to be nameable, so they
  1285. // must all have names.
  1286. if (!FD->getDeclName()) {
  1287. if (RD->isLambda()) {
  1288. S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
  1289. S.Diag(RD->getLocation(), diag::note_lambda_decl);
  1290. return true;
  1291. }
  1292. if (FD->isAnonymousStructOrUnion()) {
  1293. S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
  1294. << DecompType << FD->getType()->isUnionType();
  1295. S.Diag(FD->getLocation(), diag::note_declared_at);
  1296. return true;
  1297. }
  1298. // FIXME: Are there any other ways we could have an anonymous member?
  1299. }
  1300. // We have a real field to bind.
  1301. if (I >= Bindings.size())
  1302. return DiagnoseBadNumberOfBindings();
  1303. auto *B = Bindings[I++];
  1304. SourceLocation Loc = B->getLocation();
  1305. // The field must be accessible in the context of the structured binding.
  1306. // We already checked that the base class is accessible.
  1307. // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
  1308. // const_cast here.
  1309. S.CheckStructuredBindingMemberAccess(
  1310. Loc, const_cast<CXXRecordDecl *>(OrigRD),
  1311. DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
  1312. BasePair.getAccess(), FD->getAccess())));
  1313. // Initialize the binding to Src.FD.
  1314. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1315. if (E.isInvalid())
  1316. return true;
  1317. E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
  1318. VK_LValue, &BasePath);
  1319. if (E.isInvalid())
  1320. return true;
  1321. E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
  1322. CXXScopeSpec(), FD,
  1323. DeclAccessPair::make(FD, FD->getAccess()),
  1324. DeclarationNameInfo(FD->getDeclName(), Loc));
  1325. if (E.isInvalid())
  1326. return true;
  1327. // If the type of the member is T, the referenced type is cv T, where cv is
  1328. // the cv-qualification of the decomposition expression.
  1329. //
  1330. // FIXME: We resolve a defect here: if the field is mutable, we do not add
  1331. // 'const' to the type of the field.
  1332. Qualifiers Q = DecompType.getQualifiers();
  1333. if (FD->isMutable())
  1334. Q.removeConst();
  1335. B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
  1336. }
  1337. if (I != Bindings.size())
  1338. return DiagnoseBadNumberOfBindings();
  1339. return false;
  1340. }
  1341. void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
  1342. QualType DecompType = DD->getType();
  1343. // If the type of the decomposition is dependent, then so is the type of
  1344. // each binding.
  1345. if (DecompType->isDependentType()) {
  1346. for (auto *B : DD->bindings())
  1347. B->setType(Context.DependentTy);
  1348. return;
  1349. }
  1350. DecompType = DecompType.getNonReferenceType();
  1351. ArrayRef<BindingDecl*> Bindings = DD->bindings();
  1352. // C++1z [dcl.decomp]/2:
  1353. // If E is an array type [...]
  1354. // As an extension, we also support decomposition of built-in complex and
  1355. // vector types.
  1356. if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
  1357. if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
  1358. DD->setInvalidDecl();
  1359. return;
  1360. }
  1361. if (auto *VT = DecompType->getAs<VectorType>()) {
  1362. if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
  1363. DD->setInvalidDecl();
  1364. return;
  1365. }
  1366. if (auto *CT = DecompType->getAs<ComplexType>()) {
  1367. if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
  1368. DD->setInvalidDecl();
  1369. return;
  1370. }
  1371. // C++1z [dcl.decomp]/3:
  1372. // if the expression std::tuple_size<E>::value is a well-formed integral
  1373. // constant expression, [...]
  1374. llvm::APSInt TupleSize(32);
  1375. switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
  1376. case IsTupleLike::Error:
  1377. DD->setInvalidDecl();
  1378. return;
  1379. case IsTupleLike::TupleLike:
  1380. if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
  1381. DD->setInvalidDecl();
  1382. return;
  1383. case IsTupleLike::NotTupleLike:
  1384. break;
  1385. }
  1386. // C++1z [dcl.dcl]/8:
  1387. // [E shall be of array or non-union class type]
  1388. CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
  1389. if (!RD || RD->isUnion()) {
  1390. Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
  1391. << DD << !RD << DecompType;
  1392. DD->setInvalidDecl();
  1393. return;
  1394. }
  1395. // C++1z [dcl.decomp]/4:
  1396. // all of E's non-static data members shall be [...] direct members of
  1397. // E or of the same unambiguous public base class of E, ...
  1398. if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
  1399. DD->setInvalidDecl();
  1400. }
  1401. /// Merge the exception specifications of two variable declarations.
  1402. ///
  1403. /// This is called when there's a redeclaration of a VarDecl. The function
  1404. /// checks if the redeclaration might have an exception specification and
  1405. /// validates compatibility and merges the specs if necessary.
  1406. void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
  1407. // Shortcut if exceptions are disabled.
  1408. if (!getLangOpts().CXXExceptions)
  1409. return;
  1410. assert(Context.hasSameType(New->getType(), Old->getType()) &&
  1411. "Should only be called if types are otherwise the same.");
  1412. QualType NewType = New->getType();
  1413. QualType OldType = Old->getType();
  1414. // We're only interested in pointers and references to functions, as well
  1415. // as pointers to member functions.
  1416. if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
  1417. NewType = R->getPointeeType();
  1418. OldType = OldType->castAs<ReferenceType>()->getPointeeType();
  1419. } else if (const PointerType *P = NewType->getAs<PointerType>()) {
  1420. NewType = P->getPointeeType();
  1421. OldType = OldType->castAs<PointerType>()->getPointeeType();
  1422. } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
  1423. NewType = M->getPointeeType();
  1424. OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
  1425. }
  1426. if (!NewType->isFunctionProtoType())
  1427. return;
  1428. // There's lots of special cases for functions. For function pointers, system
  1429. // libraries are hopefully not as broken so that we don't need these
  1430. // workarounds.
  1431. if (CheckEquivalentExceptionSpec(
  1432. OldType->getAs<FunctionProtoType>(), Old->getLocation(),
  1433. NewType->getAs<FunctionProtoType>(), New->getLocation())) {
  1434. New->setInvalidDecl();
  1435. }
  1436. }
  1437. /// CheckCXXDefaultArguments - Verify that the default arguments for a
  1438. /// function declaration are well-formed according to C++
  1439. /// [dcl.fct.default].
  1440. void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
  1441. unsigned NumParams = FD->getNumParams();
  1442. unsigned ParamIdx = 0;
  1443. // This checking doesn't make sense for explicit specializations; their
  1444. // default arguments are determined by the declaration we're specializing,
  1445. // not by FD.
  1446. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  1447. return;
  1448. if (auto *FTD = FD->getDescribedFunctionTemplate())
  1449. if (FTD->isMemberSpecialization())
  1450. return;
  1451. // Find first parameter with a default argument
  1452. for (; ParamIdx < NumParams; ++ParamIdx) {
  1453. ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
  1454. if (Param->hasDefaultArg())
  1455. break;
  1456. }
  1457. // C++20 [dcl.fct.default]p4:
  1458. // In a given function declaration, each parameter subsequent to a parameter
  1459. // with a default argument shall have a default argument supplied in this or
  1460. // a previous declaration, unless the parameter was expanded from a
  1461. // parameter pack, or shall be a function parameter pack.
  1462. for (; ParamIdx < NumParams; ++ParamIdx) {
  1463. ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
  1464. if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
  1465. !(CurrentInstantiationScope &&
  1466. CurrentInstantiationScope->isLocalPackExpansion(Param))) {
  1467. if (Param->isInvalidDecl())
  1468. /* We already complained about this parameter. */;
  1469. else if (Param->getIdentifier())
  1470. Diag(Param->getLocation(),
  1471. diag::err_param_default_argument_missing_name)
  1472. << Param->getIdentifier();
  1473. else
  1474. Diag(Param->getLocation(),
  1475. diag::err_param_default_argument_missing);
  1476. }
  1477. }
  1478. }
  1479. /// Check that the given type is a literal type. Issue a diagnostic if not,
  1480. /// if Kind is Diagnose.
  1481. /// \return \c true if a problem has been found (and optionally diagnosed).
  1482. template <typename... Ts>
  1483. static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
  1484. SourceLocation Loc, QualType T, unsigned DiagID,
  1485. Ts &&...DiagArgs) {
  1486. if (T->isDependentType())
  1487. return false;
  1488. switch (Kind) {
  1489. case Sema::CheckConstexprKind::Diagnose:
  1490. return SemaRef.RequireLiteralType(Loc, T, DiagID,
  1491. std::forward<Ts>(DiagArgs)...);
  1492. case Sema::CheckConstexprKind::CheckValid:
  1493. return !T->isLiteralType(SemaRef.Context);
  1494. }
  1495. llvm_unreachable("unknown CheckConstexprKind");
  1496. }
  1497. /// Determine whether a destructor cannot be constexpr due to
  1498. static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
  1499. const CXXDestructorDecl *DD,
  1500. Sema::CheckConstexprKind Kind) {
  1501. auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
  1502. const CXXRecordDecl *RD =
  1503. T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1504. if (!RD || RD->hasConstexprDestructor())
  1505. return true;
  1506. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1507. SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
  1508. << static_cast<int>(DD->getConstexprKind()) << !FD
  1509. << (FD ? FD->getDeclName() : DeclarationName()) << T;
  1510. SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
  1511. << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
  1512. }
  1513. return false;
  1514. };
  1515. const CXXRecordDecl *RD = DD->getParent();
  1516. for (const CXXBaseSpecifier &B : RD->bases())
  1517. if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
  1518. return false;
  1519. for (const FieldDecl *FD : RD->fields())
  1520. if (!Check(FD->getLocation(), FD->getType(), FD))
  1521. return false;
  1522. return true;
  1523. }
  1524. /// Check whether a function's parameter types are all literal types. If so,
  1525. /// return true. If not, produce a suitable diagnostic and return false.
  1526. static bool CheckConstexprParameterTypes(Sema &SemaRef,
  1527. const FunctionDecl *FD,
  1528. Sema::CheckConstexprKind Kind) {
  1529. unsigned ArgIndex = 0;
  1530. const auto *FT = FD->getType()->castAs<FunctionProtoType>();
  1531. for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
  1532. e = FT->param_type_end();
  1533. i != e; ++i, ++ArgIndex) {
  1534. const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
  1535. SourceLocation ParamLoc = PD->getLocation();
  1536. if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
  1537. diag::err_constexpr_non_literal_param, ArgIndex + 1,
  1538. PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
  1539. FD->isConsteval()))
  1540. return false;
  1541. }
  1542. return true;
  1543. }
  1544. /// Check whether a function's return type is a literal type. If so, return
  1545. /// true. If not, produce a suitable diagnostic and return false.
  1546. static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
  1547. Sema::CheckConstexprKind Kind) {
  1548. if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
  1549. diag::err_constexpr_non_literal_return,
  1550. FD->isConsteval()))
  1551. return false;
  1552. return true;
  1553. }
  1554. /// Get diagnostic %select index for tag kind for
  1555. /// record diagnostic message.
  1556. /// WARNING: Indexes apply to particular diagnostics only!
  1557. ///
  1558. /// \returns diagnostic %select index.
  1559. static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
  1560. switch (Tag) {
  1561. case TTK_Struct: return 0;
  1562. case TTK_Interface: return 1;
  1563. case TTK_Class: return 2;
  1564. default: llvm_unreachable("Invalid tag kind for record diagnostic!");
  1565. }
  1566. }
  1567. static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
  1568. Stmt *Body,
  1569. Sema::CheckConstexprKind Kind);
  1570. // Check whether a function declaration satisfies the requirements of a
  1571. // constexpr function definition or a constexpr constructor definition. If so,
  1572. // return true. If not, produce appropriate diagnostics (unless asked not to by
  1573. // Kind) and return false.
  1574. //
  1575. // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
  1576. bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
  1577. CheckConstexprKind Kind) {
  1578. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  1579. if (MD && MD->isInstance()) {
  1580. // C++11 [dcl.constexpr]p4:
  1581. // The definition of a constexpr constructor shall satisfy the following
  1582. // constraints:
  1583. // - the class shall not have any virtual base classes;
  1584. //
  1585. // FIXME: This only applies to constructors and destructors, not arbitrary
  1586. // member functions.
  1587. const CXXRecordDecl *RD = MD->getParent();
  1588. if (RD->getNumVBases()) {
  1589. if (Kind == CheckConstexprKind::CheckValid)
  1590. return false;
  1591. Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
  1592. << isa<CXXConstructorDecl>(NewFD)
  1593. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  1594. for (const auto &I : RD->vbases())
  1595. Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
  1596. << I.getSourceRange();
  1597. return false;
  1598. }
  1599. }
  1600. if (!isa<CXXConstructorDecl>(NewFD)) {
  1601. // C++11 [dcl.constexpr]p3:
  1602. // The definition of a constexpr function shall satisfy the following
  1603. // constraints:
  1604. // - it shall not be virtual; (removed in C++20)
  1605. const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
  1606. if (Method && Method->isVirtual()) {
  1607. if (getLangOpts().CPlusPlus20) {
  1608. if (Kind == CheckConstexprKind::Diagnose)
  1609. Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
  1610. } else {
  1611. if (Kind == CheckConstexprKind::CheckValid)
  1612. return false;
  1613. Method = Method->getCanonicalDecl();
  1614. Diag(Method->getLocation(), diag::err_constexpr_virtual);
  1615. // If it's not obvious why this function is virtual, find an overridden
  1616. // function which uses the 'virtual' keyword.
  1617. const CXXMethodDecl *WrittenVirtual = Method;
  1618. while (!WrittenVirtual->isVirtualAsWritten())
  1619. WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
  1620. if (WrittenVirtual != Method)
  1621. Diag(WrittenVirtual->getLocation(),
  1622. diag::note_overridden_virtual_function);
  1623. return false;
  1624. }
  1625. }
  1626. // - its return type shall be a literal type;
  1627. if (!CheckConstexprReturnType(*this, NewFD, Kind))
  1628. return false;
  1629. }
  1630. if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
  1631. // A destructor can be constexpr only if the defaulted destructor could be;
  1632. // we don't need to check the members and bases if we already know they all
  1633. // have constexpr destructors.
  1634. if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
  1635. if (Kind == CheckConstexprKind::CheckValid)
  1636. return false;
  1637. if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
  1638. return false;
  1639. }
  1640. }
  1641. // - each of its parameter types shall be a literal type;
  1642. if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
  1643. return false;
  1644. Stmt *Body = NewFD->getBody();
  1645. assert(Body &&
  1646. "CheckConstexprFunctionDefinition called on function with no body");
  1647. return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
  1648. }
  1649. /// Check the given declaration statement is legal within a constexpr function
  1650. /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
  1651. ///
  1652. /// \return true if the body is OK (maybe only as an extension), false if we
  1653. /// have diagnosed a problem.
  1654. static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
  1655. DeclStmt *DS, SourceLocation &Cxx1yLoc,
  1656. Sema::CheckConstexprKind Kind) {
  1657. // C++11 [dcl.constexpr]p3 and p4:
  1658. // The definition of a constexpr function(p3) or constructor(p4) [...] shall
  1659. // contain only
  1660. for (const auto *DclIt : DS->decls()) {
  1661. switch (DclIt->getKind()) {
  1662. case Decl::StaticAssert:
  1663. case Decl::Using:
  1664. case Decl::UsingShadow:
  1665. case Decl::UsingDirective:
  1666. case Decl::UnresolvedUsingTypename:
  1667. case Decl::UnresolvedUsingValue:
  1668. case Decl::UsingEnum:
  1669. // - static_assert-declarations
  1670. // - using-declarations,
  1671. // - using-directives,
  1672. // - using-enum-declaration
  1673. continue;
  1674. case Decl::Typedef:
  1675. case Decl::TypeAlias: {
  1676. // - typedef declarations and alias-declarations that do not define
  1677. // classes or enumerations,
  1678. const auto *TN = cast<TypedefNameDecl>(DclIt);
  1679. if (TN->getUnderlyingType()->isVariablyModifiedType()) {
  1680. // Don't allow variably-modified types in constexpr functions.
  1681. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1682. TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
  1683. SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
  1684. << TL.getSourceRange() << TL.getType()
  1685. << isa<CXXConstructorDecl>(Dcl);
  1686. }
  1687. return false;
  1688. }
  1689. continue;
  1690. }
  1691. case Decl::Enum:
  1692. case Decl::CXXRecord:
  1693. // C++1y allows types to be defined, not just declared.
  1694. if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
  1695. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1696. SemaRef.Diag(DS->getBeginLoc(),
  1697. SemaRef.getLangOpts().CPlusPlus14
  1698. ? diag::warn_cxx11_compat_constexpr_type_definition
  1699. : diag::ext_constexpr_type_definition)
  1700. << isa<CXXConstructorDecl>(Dcl);
  1701. } else if (!SemaRef.getLangOpts().CPlusPlus14) {
  1702. return false;
  1703. }
  1704. }
  1705. continue;
  1706. case Decl::EnumConstant:
  1707. case Decl::IndirectField:
  1708. case Decl::ParmVar:
  1709. // These can only appear with other declarations which are banned in
  1710. // C++11 and permitted in C++1y, so ignore them.
  1711. continue;
  1712. case Decl::Var:
  1713. case Decl::Decomposition: {
  1714. // C++1y [dcl.constexpr]p3 allows anything except:
  1715. // a definition of a variable of non-literal type or of static or
  1716. // thread storage duration or [before C++2a] for which no
  1717. // initialization is performed.
  1718. const auto *VD = cast<VarDecl>(DclIt);
  1719. if (VD->isThisDeclarationADefinition()) {
  1720. if (VD->isStaticLocal()) {
  1721. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1722. SemaRef.Diag(VD->getLocation(),
  1723. SemaRef.getLangOpts().CPlusPlus2b
  1724. ? diag::warn_cxx20_compat_constexpr_var
  1725. : diag::ext_constexpr_static_var)
  1726. << isa<CXXConstructorDecl>(Dcl)
  1727. << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
  1728. } else if (!SemaRef.getLangOpts().CPlusPlus2b) {
  1729. return false;
  1730. }
  1731. }
  1732. if (SemaRef.LangOpts.CPlusPlus2b) {
  1733. CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
  1734. diag::warn_cxx20_compat_constexpr_var,
  1735. isa<CXXConstructorDecl>(Dcl),
  1736. /*variable of non-literal type*/ 2);
  1737. } else if (CheckLiteralType(
  1738. SemaRef, Kind, VD->getLocation(), VD->getType(),
  1739. diag::err_constexpr_local_var_non_literal_type,
  1740. isa<CXXConstructorDecl>(Dcl))) {
  1741. return false;
  1742. }
  1743. if (!VD->getType()->isDependentType() &&
  1744. !VD->hasInit() && !VD->isCXXForRangeDecl()) {
  1745. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1746. SemaRef.Diag(
  1747. VD->getLocation(),
  1748. SemaRef.getLangOpts().CPlusPlus20
  1749. ? diag::warn_cxx17_compat_constexpr_local_var_no_init
  1750. : diag::ext_constexpr_local_var_no_init)
  1751. << isa<CXXConstructorDecl>(Dcl);
  1752. } else if (!SemaRef.getLangOpts().CPlusPlus20) {
  1753. return false;
  1754. }
  1755. continue;
  1756. }
  1757. }
  1758. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1759. SemaRef.Diag(VD->getLocation(),
  1760. SemaRef.getLangOpts().CPlusPlus14
  1761. ? diag::warn_cxx11_compat_constexpr_local_var
  1762. : diag::ext_constexpr_local_var)
  1763. << isa<CXXConstructorDecl>(Dcl);
  1764. } else if (!SemaRef.getLangOpts().CPlusPlus14) {
  1765. return false;
  1766. }
  1767. continue;
  1768. }
  1769. case Decl::NamespaceAlias:
  1770. case Decl::Function:
  1771. // These are disallowed in C++11 and permitted in C++1y. Allow them
  1772. // everywhere as an extension.
  1773. if (!Cxx1yLoc.isValid())
  1774. Cxx1yLoc = DS->getBeginLoc();
  1775. continue;
  1776. default:
  1777. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1778. SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1779. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  1780. }
  1781. return false;
  1782. }
  1783. }
  1784. return true;
  1785. }
  1786. /// Check that the given field is initialized within a constexpr constructor.
  1787. ///
  1788. /// \param Dcl The constexpr constructor being checked.
  1789. /// \param Field The field being checked. This may be a member of an anonymous
  1790. /// struct or union nested within the class being checked.
  1791. /// \param Inits All declarations, including anonymous struct/union members and
  1792. /// indirect members, for which any initialization was provided.
  1793. /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
  1794. /// multiple notes for different members to the same error.
  1795. /// \param Kind Whether we're diagnosing a constructor as written or determining
  1796. /// whether the formal requirements are satisfied.
  1797. /// \return \c false if we're checking for validity and the constructor does
  1798. /// not satisfy the requirements on a constexpr constructor.
  1799. static bool CheckConstexprCtorInitializer(Sema &SemaRef,
  1800. const FunctionDecl *Dcl,
  1801. FieldDecl *Field,
  1802. llvm::SmallSet<Decl*, 16> &Inits,
  1803. bool &Diagnosed,
  1804. Sema::CheckConstexprKind Kind) {
  1805. // In C++20 onwards, there's nothing to check for validity.
  1806. if (Kind == Sema::CheckConstexprKind::CheckValid &&
  1807. SemaRef.getLangOpts().CPlusPlus20)
  1808. return true;
  1809. if (Field->isInvalidDecl())
  1810. return true;
  1811. if (Field->isUnnamedBitfield())
  1812. return true;
  1813. // Anonymous unions with no variant members and empty anonymous structs do not
  1814. // need to be explicitly initialized. FIXME: Anonymous structs that contain no
  1815. // indirect fields don't need initializing.
  1816. if (Field->isAnonymousStructOrUnion() &&
  1817. (Field->getType()->isUnionType()
  1818. ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
  1819. : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
  1820. return true;
  1821. if (!Inits.count(Field)) {
  1822. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1823. if (!Diagnosed) {
  1824. SemaRef.Diag(Dcl->getLocation(),
  1825. SemaRef.getLangOpts().CPlusPlus20
  1826. ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
  1827. : diag::ext_constexpr_ctor_missing_init);
  1828. Diagnosed = true;
  1829. }
  1830. SemaRef.Diag(Field->getLocation(),
  1831. diag::note_constexpr_ctor_missing_init);
  1832. } else if (!SemaRef.getLangOpts().CPlusPlus20) {
  1833. return false;
  1834. }
  1835. } else if (Field->isAnonymousStructOrUnion()) {
  1836. const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
  1837. for (auto *I : RD->fields())
  1838. // If an anonymous union contains an anonymous struct of which any member
  1839. // is initialized, all members must be initialized.
  1840. if (!RD->isUnion() || Inits.count(I))
  1841. if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
  1842. Kind))
  1843. return false;
  1844. }
  1845. return true;
  1846. }
  1847. /// Check the provided statement is allowed in a constexpr function
  1848. /// definition.
  1849. static bool
  1850. CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
  1851. SmallVectorImpl<SourceLocation> &ReturnStmts,
  1852. SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
  1853. SourceLocation &Cxx2bLoc,
  1854. Sema::CheckConstexprKind Kind) {
  1855. // - its function-body shall be [...] a compound-statement that contains only
  1856. switch (S->getStmtClass()) {
  1857. case Stmt::NullStmtClass:
  1858. // - null statements,
  1859. return true;
  1860. case Stmt::DeclStmtClass:
  1861. // - static_assert-declarations
  1862. // - using-declarations,
  1863. // - using-directives,
  1864. // - typedef declarations and alias-declarations that do not define
  1865. // classes or enumerations,
  1866. if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
  1867. return false;
  1868. return true;
  1869. case Stmt::ReturnStmtClass:
  1870. // - and exactly one return statement;
  1871. if (isa<CXXConstructorDecl>(Dcl)) {
  1872. // C++1y allows return statements in constexpr constructors.
  1873. if (!Cxx1yLoc.isValid())
  1874. Cxx1yLoc = S->getBeginLoc();
  1875. return true;
  1876. }
  1877. ReturnStmts.push_back(S->getBeginLoc());
  1878. return true;
  1879. case Stmt::AttributedStmtClass:
  1880. // Attributes on a statement don't affect its formal kind and hence don't
  1881. // affect its validity in a constexpr function.
  1882. return CheckConstexprFunctionStmt(
  1883. SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
  1884. Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
  1885. case Stmt::CompoundStmtClass: {
  1886. // C++1y allows compound-statements.
  1887. if (!Cxx1yLoc.isValid())
  1888. Cxx1yLoc = S->getBeginLoc();
  1889. CompoundStmt *CompStmt = cast<CompoundStmt>(S);
  1890. for (auto *BodyIt : CompStmt->body()) {
  1891. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
  1892. Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
  1893. return false;
  1894. }
  1895. return true;
  1896. }
  1897. case Stmt::IfStmtClass: {
  1898. // C++1y allows if-statements.
  1899. if (!Cxx1yLoc.isValid())
  1900. Cxx1yLoc = S->getBeginLoc();
  1901. IfStmt *If = cast<IfStmt>(S);
  1902. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
  1903. Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
  1904. return false;
  1905. if (If->getElse() &&
  1906. !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
  1907. Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
  1908. return false;
  1909. return true;
  1910. }
  1911. case Stmt::WhileStmtClass:
  1912. case Stmt::DoStmtClass:
  1913. case Stmt::ForStmtClass:
  1914. case Stmt::CXXForRangeStmtClass:
  1915. case Stmt::ContinueStmtClass:
  1916. // C++1y allows all of these. We don't allow them as extensions in C++11,
  1917. // because they don't make sense without variable mutation.
  1918. if (!SemaRef.getLangOpts().CPlusPlus14)
  1919. break;
  1920. if (!Cxx1yLoc.isValid())
  1921. Cxx1yLoc = S->getBeginLoc();
  1922. for (Stmt *SubStmt : S->children()) {
  1923. if (SubStmt &&
  1924. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1925. Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
  1926. return false;
  1927. }
  1928. return true;
  1929. case Stmt::SwitchStmtClass:
  1930. case Stmt::CaseStmtClass:
  1931. case Stmt::DefaultStmtClass:
  1932. case Stmt::BreakStmtClass:
  1933. // C++1y allows switch-statements, and since they don't need variable
  1934. // mutation, we can reasonably allow them in C++11 as an extension.
  1935. if (!Cxx1yLoc.isValid())
  1936. Cxx1yLoc = S->getBeginLoc();
  1937. for (Stmt *SubStmt : S->children()) {
  1938. if (SubStmt &&
  1939. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1940. Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
  1941. return false;
  1942. }
  1943. return true;
  1944. case Stmt::LabelStmtClass:
  1945. case Stmt::GotoStmtClass:
  1946. if (Cxx2bLoc.isInvalid())
  1947. Cxx2bLoc = S->getBeginLoc();
  1948. for (Stmt *SubStmt : S->children()) {
  1949. if (SubStmt &&
  1950. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1951. Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
  1952. return false;
  1953. }
  1954. return true;
  1955. case Stmt::GCCAsmStmtClass:
  1956. case Stmt::MSAsmStmtClass:
  1957. // C++2a allows inline assembly statements.
  1958. case Stmt::CXXTryStmtClass:
  1959. if (Cxx2aLoc.isInvalid())
  1960. Cxx2aLoc = S->getBeginLoc();
  1961. for (Stmt *SubStmt : S->children()) {
  1962. if (SubStmt &&
  1963. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1964. Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
  1965. return false;
  1966. }
  1967. return true;
  1968. case Stmt::CXXCatchStmtClass:
  1969. // Do not bother checking the language mode (already covered by the
  1970. // try block check).
  1971. if (!CheckConstexprFunctionStmt(
  1972. SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
  1973. Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
  1974. return false;
  1975. return true;
  1976. default:
  1977. if (!isa<Expr>(S))
  1978. break;
  1979. // C++1y allows expression-statements.
  1980. if (!Cxx1yLoc.isValid())
  1981. Cxx1yLoc = S->getBeginLoc();
  1982. return true;
  1983. }
  1984. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1985. SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1986. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  1987. }
  1988. return false;
  1989. }
  1990. /// Check the body for the given constexpr function declaration only contains
  1991. /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
  1992. ///
  1993. /// \return true if the body is OK, false if we have found or diagnosed a
  1994. /// problem.
  1995. static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
  1996. Stmt *Body,
  1997. Sema::CheckConstexprKind Kind) {
  1998. SmallVector<SourceLocation, 4> ReturnStmts;
  1999. if (isa<CXXTryStmt>(Body)) {
  2000. // C++11 [dcl.constexpr]p3:
  2001. // The definition of a constexpr function shall satisfy the following
  2002. // constraints: [...]
  2003. // - its function-body shall be = delete, = default, or a
  2004. // compound-statement
  2005. //
  2006. // C++11 [dcl.constexpr]p4:
  2007. // In the definition of a constexpr constructor, [...]
  2008. // - its function-body shall not be a function-try-block;
  2009. //
  2010. // This restriction is lifted in C++2a, as long as inner statements also
  2011. // apply the general constexpr rules.
  2012. switch (Kind) {
  2013. case Sema::CheckConstexprKind::CheckValid:
  2014. if (!SemaRef.getLangOpts().CPlusPlus20)
  2015. return false;
  2016. break;
  2017. case Sema::CheckConstexprKind::Diagnose:
  2018. SemaRef.Diag(Body->getBeginLoc(),
  2019. !SemaRef.getLangOpts().CPlusPlus20
  2020. ? diag::ext_constexpr_function_try_block_cxx20
  2021. : diag::warn_cxx17_compat_constexpr_function_try_block)
  2022. << isa<CXXConstructorDecl>(Dcl);
  2023. break;
  2024. }
  2025. }
  2026. // - its function-body shall be [...] a compound-statement that contains only
  2027. // [... list of cases ...]
  2028. //
  2029. // Note that walking the children here is enough to properly check for
  2030. // CompoundStmt and CXXTryStmt body.
  2031. SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
  2032. for (Stmt *SubStmt : Body->children()) {
  2033. if (SubStmt &&
  2034. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  2035. Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
  2036. return false;
  2037. }
  2038. if (Kind == Sema::CheckConstexprKind::CheckValid) {
  2039. // If this is only valid as an extension, report that we don't satisfy the
  2040. // constraints of the current language.
  2041. if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) ||
  2042. (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
  2043. (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
  2044. return false;
  2045. } else if (Cxx2bLoc.isValid()) {
  2046. SemaRef.Diag(Cxx2bLoc,
  2047. SemaRef.getLangOpts().CPlusPlus2b
  2048. ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
  2049. : diag::ext_constexpr_body_invalid_stmt_cxx2b)
  2050. << isa<CXXConstructorDecl>(Dcl);
  2051. } else if (Cxx2aLoc.isValid()) {
  2052. SemaRef.Diag(Cxx2aLoc,
  2053. SemaRef.getLangOpts().CPlusPlus20
  2054. ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
  2055. : diag::ext_constexpr_body_invalid_stmt_cxx20)
  2056. << isa<CXXConstructorDecl>(Dcl);
  2057. } else if (Cxx1yLoc.isValid()) {
  2058. SemaRef.Diag(Cxx1yLoc,
  2059. SemaRef.getLangOpts().CPlusPlus14
  2060. ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
  2061. : diag::ext_constexpr_body_invalid_stmt)
  2062. << isa<CXXConstructorDecl>(Dcl);
  2063. }
  2064. if (const CXXConstructorDecl *Constructor
  2065. = dyn_cast<CXXConstructorDecl>(Dcl)) {
  2066. const CXXRecordDecl *RD = Constructor->getParent();
  2067. // DR1359:
  2068. // - every non-variant non-static data member and base class sub-object
  2069. // shall be initialized;
  2070. // DR1460:
  2071. // - if the class is a union having variant members, exactly one of them
  2072. // shall be initialized;
  2073. if (RD->isUnion()) {
  2074. if (Constructor->getNumCtorInitializers() == 0 &&
  2075. RD->hasVariantMembers()) {
  2076. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  2077. SemaRef.Diag(
  2078. Dcl->getLocation(),
  2079. SemaRef.getLangOpts().CPlusPlus20
  2080. ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
  2081. : diag::ext_constexpr_union_ctor_no_init);
  2082. } else if (!SemaRef.getLangOpts().CPlusPlus20) {
  2083. return false;
  2084. }
  2085. }
  2086. } else if (!Constructor->isDependentContext() &&
  2087. !Constructor->isDelegatingConstructor()) {
  2088. assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
  2089. // Skip detailed checking if we have enough initializers, and we would
  2090. // allow at most one initializer per member.
  2091. bool AnyAnonStructUnionMembers = false;
  2092. unsigned Fields = 0;
  2093. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  2094. E = RD->field_end(); I != E; ++I, ++Fields) {
  2095. if (I->isAnonymousStructOrUnion()) {
  2096. AnyAnonStructUnionMembers = true;
  2097. break;
  2098. }
  2099. }
  2100. // DR1460:
  2101. // - if the class is a union-like class, but is not a union, for each of
  2102. // its anonymous union members having variant members, exactly one of
  2103. // them shall be initialized;
  2104. if (AnyAnonStructUnionMembers ||
  2105. Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
  2106. // Check initialization of non-static data members. Base classes are
  2107. // always initialized so do not need to be checked. Dependent bases
  2108. // might not have initializers in the member initializer list.
  2109. llvm::SmallSet<Decl*, 16> Inits;
  2110. for (const auto *I: Constructor->inits()) {
  2111. if (FieldDecl *FD = I->getMember())
  2112. Inits.insert(FD);
  2113. else if (IndirectFieldDecl *ID = I->getIndirectMember())
  2114. Inits.insert(ID->chain_begin(), ID->chain_end());
  2115. }
  2116. bool Diagnosed = false;
  2117. for (auto *I : RD->fields())
  2118. if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
  2119. Kind))
  2120. return false;
  2121. }
  2122. }
  2123. } else {
  2124. if (ReturnStmts.empty()) {
  2125. // C++1y doesn't require constexpr functions to contain a 'return'
  2126. // statement. We still do, unless the return type might be void, because
  2127. // otherwise if there's no return statement, the function cannot
  2128. // be used in a core constant expression.
  2129. bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
  2130. (Dcl->getReturnType()->isVoidType() ||
  2131. Dcl->getReturnType()->isDependentType());
  2132. switch (Kind) {
  2133. case Sema::CheckConstexprKind::Diagnose:
  2134. SemaRef.Diag(Dcl->getLocation(),
  2135. OK ? diag::warn_cxx11_compat_constexpr_body_no_return
  2136. : diag::err_constexpr_body_no_return)
  2137. << Dcl->isConsteval();
  2138. if (!OK)
  2139. return false;
  2140. break;
  2141. case Sema::CheckConstexprKind::CheckValid:
  2142. // The formal requirements don't include this rule in C++14, even
  2143. // though the "must be able to produce a constant expression" rules
  2144. // still imply it in some cases.
  2145. if (!SemaRef.getLangOpts().CPlusPlus14)
  2146. return false;
  2147. break;
  2148. }
  2149. } else if (ReturnStmts.size() > 1) {
  2150. switch (Kind) {
  2151. case Sema::CheckConstexprKind::Diagnose:
  2152. SemaRef.Diag(
  2153. ReturnStmts.back(),
  2154. SemaRef.getLangOpts().CPlusPlus14
  2155. ? diag::warn_cxx11_compat_constexpr_body_multiple_return
  2156. : diag::ext_constexpr_body_multiple_return);
  2157. for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
  2158. SemaRef.Diag(ReturnStmts[I],
  2159. diag::note_constexpr_body_previous_return);
  2160. break;
  2161. case Sema::CheckConstexprKind::CheckValid:
  2162. if (!SemaRef.getLangOpts().CPlusPlus14)
  2163. return false;
  2164. break;
  2165. }
  2166. }
  2167. }
  2168. // C++11 [dcl.constexpr]p5:
  2169. // if no function argument values exist such that the function invocation
  2170. // substitution would produce a constant expression, the program is
  2171. // ill-formed; no diagnostic required.
  2172. // C++11 [dcl.constexpr]p3:
  2173. // - every constructor call and implicit conversion used in initializing the
  2174. // return value shall be one of those allowed in a constant expression.
  2175. // C++11 [dcl.constexpr]p4:
  2176. // - every constructor involved in initializing non-static data members and
  2177. // base class sub-objects shall be a constexpr constructor.
  2178. //
  2179. // Note that this rule is distinct from the "requirements for a constexpr
  2180. // function", so is not checked in CheckValid mode.
  2181. SmallVector<PartialDiagnosticAt, 8> Diags;
  2182. if (Kind == Sema::CheckConstexprKind::Diagnose &&
  2183. !Expr::isPotentialConstantExpr(Dcl, Diags)) {
  2184. SemaRef.Diag(Dcl->getLocation(),
  2185. diag::ext_constexpr_function_never_constant_expr)
  2186. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  2187. for (size_t I = 0, N = Diags.size(); I != N; ++I)
  2188. SemaRef.Diag(Diags[I].first, Diags[I].second);
  2189. // Don't return false here: we allow this for compatibility in
  2190. // system headers.
  2191. }
  2192. return true;
  2193. }
  2194. /// Get the class that is directly named by the current context. This is the
  2195. /// class for which an unqualified-id in this scope could name a constructor
  2196. /// or destructor.
  2197. ///
  2198. /// If the scope specifier denotes a class, this will be that class.
  2199. /// If the scope specifier is empty, this will be the class whose
  2200. /// member-specification we are currently within. Otherwise, there
  2201. /// is no such class.
  2202. CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
  2203. assert(getLangOpts().CPlusPlus && "No class names in C!");
  2204. if (SS && SS->isInvalid())
  2205. return nullptr;
  2206. if (SS && SS->isNotEmpty()) {
  2207. DeclContext *DC = computeDeclContext(*SS, true);
  2208. return dyn_cast_or_null<CXXRecordDecl>(DC);
  2209. }
  2210. return dyn_cast_or_null<CXXRecordDecl>(CurContext);
  2211. }
  2212. /// isCurrentClassName - Determine whether the identifier II is the
  2213. /// name of the class type currently being defined. In the case of
  2214. /// nested classes, this will only return true if II is the name of
  2215. /// the innermost class.
  2216. bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
  2217. const CXXScopeSpec *SS) {
  2218. CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
  2219. return CurDecl && &II == CurDecl->getIdentifier();
  2220. }
  2221. /// Determine whether the identifier II is a typo for the name of
  2222. /// the class type currently being defined. If so, update it to the identifier
  2223. /// that should have been used.
  2224. bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
  2225. assert(getLangOpts().CPlusPlus && "No class names in C!");
  2226. if (!getLangOpts().SpellChecking)
  2227. return false;
  2228. CXXRecordDecl *CurDecl;
  2229. if (SS && SS->isSet() && !SS->isInvalid()) {
  2230. DeclContext *DC = computeDeclContext(*SS, true);
  2231. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  2232. } else
  2233. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  2234. if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
  2235. 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
  2236. < II->getLength()) {
  2237. II = CurDecl->getIdentifier();
  2238. return true;
  2239. }
  2240. return false;
  2241. }
  2242. /// Determine whether the given class is a base class of the given
  2243. /// class, including looking at dependent bases.
  2244. static bool findCircularInheritance(const CXXRecordDecl *Class,
  2245. const CXXRecordDecl *Current) {
  2246. SmallVector<const CXXRecordDecl*, 8> Queue;
  2247. Class = Class->getCanonicalDecl();
  2248. while (true) {
  2249. for (const auto &I : Current->bases()) {
  2250. CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  2251. if (!Base)
  2252. continue;
  2253. Base = Base->getDefinition();
  2254. if (!Base)
  2255. continue;
  2256. if (Base->getCanonicalDecl() == Class)
  2257. return true;
  2258. Queue.push_back(Base);
  2259. }
  2260. if (Queue.empty())
  2261. return false;
  2262. Current = Queue.pop_back_val();
  2263. }
  2264. return false;
  2265. }
  2266. /// Check the validity of a C++ base class specifier.
  2267. ///
  2268. /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
  2269. /// and returns NULL otherwise.
  2270. CXXBaseSpecifier *
  2271. Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
  2272. SourceRange SpecifierRange,
  2273. bool Virtual, AccessSpecifier Access,
  2274. TypeSourceInfo *TInfo,
  2275. SourceLocation EllipsisLoc) {
  2276. // In HLSL, unspecified class access is public rather than private.
  2277. if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class &&
  2278. Access == AS_none)
  2279. Access = AS_public;
  2280. QualType BaseType = TInfo->getType();
  2281. if (BaseType->containsErrors()) {
  2282. // Already emitted a diagnostic when parsing the error type.
  2283. return nullptr;
  2284. }
  2285. // C++ [class.union]p1:
  2286. // A union shall not have base classes.
  2287. if (Class->isUnion()) {
  2288. Diag(Class->getLocation(), diag::err_base_clause_on_union)
  2289. << SpecifierRange;
  2290. return nullptr;
  2291. }
  2292. if (EllipsisLoc.isValid() &&
  2293. !TInfo->getType()->containsUnexpandedParameterPack()) {
  2294. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  2295. << TInfo->getTypeLoc().getSourceRange();
  2296. EllipsisLoc = SourceLocation();
  2297. }
  2298. SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
  2299. if (BaseType->isDependentType()) {
  2300. // Make sure that we don't have circular inheritance among our dependent
  2301. // bases. For non-dependent bases, the check for completeness below handles
  2302. // this.
  2303. if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
  2304. if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
  2305. ((BaseDecl = BaseDecl->getDefinition()) &&
  2306. findCircularInheritance(Class, BaseDecl))) {
  2307. Diag(BaseLoc, diag::err_circular_inheritance)
  2308. << BaseType << Context.getTypeDeclType(Class);
  2309. if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
  2310. Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  2311. << BaseType;
  2312. return nullptr;
  2313. }
  2314. }
  2315. // Make sure that we don't make an ill-formed AST where the type of the
  2316. // Class is non-dependent and its attached base class specifier is an
  2317. // dependent type, which violates invariants in many clang code paths (e.g.
  2318. // constexpr evaluator). If this case happens (in errory-recovery mode), we
  2319. // explicitly mark the Class decl invalid. The diagnostic was already
  2320. // emitted.
  2321. if (!Class->getTypeForDecl()->isDependentType())
  2322. Class->setInvalidDecl();
  2323. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2324. Class->getTagKind() == TTK_Class,
  2325. Access, TInfo, EllipsisLoc);
  2326. }
  2327. // Base specifiers must be record types.
  2328. if (!BaseType->isRecordType()) {
  2329. Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
  2330. return nullptr;
  2331. }
  2332. // C++ [class.union]p1:
  2333. // A union shall not be used as a base class.
  2334. if (BaseType->isUnionType()) {
  2335. Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
  2336. return nullptr;
  2337. }
  2338. // For the MS ABI, propagate DLL attributes to base class templates.
  2339. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2340. if (Attr *ClassAttr = getDLLAttr(Class)) {
  2341. if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  2342. BaseType->getAsCXXRecordDecl())) {
  2343. propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
  2344. BaseLoc);
  2345. }
  2346. }
  2347. }
  2348. // C++ [class.derived]p2:
  2349. // The class-name in a base-specifier shall not be an incompletely
  2350. // defined class.
  2351. if (RequireCompleteType(BaseLoc, BaseType,
  2352. diag::err_incomplete_base_class, SpecifierRange)) {
  2353. Class->setInvalidDecl();
  2354. return nullptr;
  2355. }
  2356. // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
  2357. RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
  2358. assert(BaseDecl && "Record type has no declaration");
  2359. BaseDecl = BaseDecl->getDefinition();
  2360. assert(BaseDecl && "Base type is not incomplete, but has no definition");
  2361. CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
  2362. assert(CXXBaseDecl && "Base type is not a C++ type");
  2363. // Microsoft docs say:
  2364. // "If a base-class has a code_seg attribute, derived classes must have the
  2365. // same attribute."
  2366. const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
  2367. const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
  2368. if ((DerivedCSA || BaseCSA) &&
  2369. (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
  2370. Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
  2371. Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
  2372. << CXXBaseDecl;
  2373. return nullptr;
  2374. }
  2375. // A class which contains a flexible array member is not suitable for use as a
  2376. // base class:
  2377. // - If the layout determines that a base comes before another base,
  2378. // the flexible array member would index into the subsequent base.
  2379. // - If the layout determines that base comes before the derived class,
  2380. // the flexible array member would index into the derived class.
  2381. if (CXXBaseDecl->hasFlexibleArrayMember()) {
  2382. Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
  2383. << CXXBaseDecl->getDeclName();
  2384. return nullptr;
  2385. }
  2386. // C++ [class]p3:
  2387. // If a class is marked final and it appears as a base-type-specifier in
  2388. // base-clause, the program is ill-formed.
  2389. if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
  2390. Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
  2391. << CXXBaseDecl->getDeclName()
  2392. << FA->isSpelledAsSealed();
  2393. Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
  2394. << CXXBaseDecl->getDeclName() << FA->getRange();
  2395. return nullptr;
  2396. }
  2397. if (BaseDecl->isInvalidDecl())
  2398. Class->setInvalidDecl();
  2399. // Create the base specifier.
  2400. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2401. Class->getTagKind() == TTK_Class,
  2402. Access, TInfo, EllipsisLoc);
  2403. }
  2404. /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
  2405. /// one entry in the base class list of a class specifier, for
  2406. /// example:
  2407. /// class foo : public bar, virtual private baz {
  2408. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  2409. BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
  2410. const ParsedAttributesView &Attributes,
  2411. bool Virtual, AccessSpecifier Access,
  2412. ParsedType basetype, SourceLocation BaseLoc,
  2413. SourceLocation EllipsisLoc) {
  2414. if (!classdecl)
  2415. return true;
  2416. AdjustDeclIfTemplate(classdecl);
  2417. CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
  2418. if (!Class)
  2419. return true;
  2420. // We haven't yet attached the base specifiers.
  2421. Class->setIsParsingBaseSpecifiers();
  2422. // We do not support any C++11 attributes on base-specifiers yet.
  2423. // Diagnose any attributes we see.
  2424. for (const ParsedAttr &AL : Attributes) {
  2425. if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
  2426. continue;
  2427. Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
  2428. ? (unsigned)diag::warn_unknown_attribute_ignored
  2429. : (unsigned)diag::err_base_specifier_attribute)
  2430. << AL << AL.getRange();
  2431. }
  2432. TypeSourceInfo *TInfo = nullptr;
  2433. GetTypeFromParser(basetype, &TInfo);
  2434. if (EllipsisLoc.isInvalid() &&
  2435. DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
  2436. UPPC_BaseType))
  2437. return true;
  2438. if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
  2439. Virtual, Access, TInfo,
  2440. EllipsisLoc))
  2441. return BaseSpec;
  2442. else
  2443. Class->setInvalidDecl();
  2444. return true;
  2445. }
  2446. /// Use small set to collect indirect bases. As this is only used
  2447. /// locally, there's no need to abstract the small size parameter.
  2448. typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
  2449. /// Recursively add the bases of Type. Don't add Type itself.
  2450. static void
  2451. NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
  2452. const QualType &Type)
  2453. {
  2454. // Even though the incoming type is a base, it might not be
  2455. // a class -- it could be a template parm, for instance.
  2456. if (auto Rec = Type->getAs<RecordType>()) {
  2457. auto Decl = Rec->getAsCXXRecordDecl();
  2458. // Iterate over its bases.
  2459. for (const auto &BaseSpec : Decl->bases()) {
  2460. QualType Base = Context.getCanonicalType(BaseSpec.getType())
  2461. .getUnqualifiedType();
  2462. if (Set.insert(Base).second)
  2463. // If we've not already seen it, recurse.
  2464. NoteIndirectBases(Context, Set, Base);
  2465. }
  2466. }
  2467. }
  2468. /// Performs the actual work of attaching the given base class
  2469. /// specifiers to a C++ class.
  2470. bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
  2471. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2472. if (Bases.empty())
  2473. return false;
  2474. // Used to keep track of which base types we have already seen, so
  2475. // that we can properly diagnose redundant direct base types. Note
  2476. // that the key is always the unqualified canonical type of the base
  2477. // class.
  2478. std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
  2479. // Used to track indirect bases so we can see if a direct base is
  2480. // ambiguous.
  2481. IndirectBaseSet IndirectBaseTypes;
  2482. // Copy non-redundant base specifiers into permanent storage.
  2483. unsigned NumGoodBases = 0;
  2484. bool Invalid = false;
  2485. for (unsigned idx = 0; idx < Bases.size(); ++idx) {
  2486. QualType NewBaseType
  2487. = Context.getCanonicalType(Bases[idx]->getType());
  2488. NewBaseType = NewBaseType.getLocalUnqualifiedType();
  2489. CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
  2490. if (KnownBase) {
  2491. // C++ [class.mi]p3:
  2492. // A class shall not be specified as a direct base class of a
  2493. // derived class more than once.
  2494. Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
  2495. << KnownBase->getType() << Bases[idx]->getSourceRange();
  2496. // Delete the duplicate base class specifier; we're going to
  2497. // overwrite its pointer later.
  2498. Context.Deallocate(Bases[idx]);
  2499. Invalid = true;
  2500. } else {
  2501. // Okay, add this new base class.
  2502. KnownBase = Bases[idx];
  2503. Bases[NumGoodBases++] = Bases[idx];
  2504. if (NewBaseType->isDependentType())
  2505. continue;
  2506. // Note this base's direct & indirect bases, if there could be ambiguity.
  2507. if (Bases.size() > 1)
  2508. NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
  2509. if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
  2510. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  2511. if (Class->isInterface() &&
  2512. (!RD->isInterfaceLike() ||
  2513. KnownBase->getAccessSpecifier() != AS_public)) {
  2514. // The Microsoft extension __interface does not permit bases that
  2515. // are not themselves public interfaces.
  2516. Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
  2517. << getRecordDiagFromTagKind(RD->getTagKind()) << RD
  2518. << RD->getSourceRange();
  2519. Invalid = true;
  2520. }
  2521. if (RD->hasAttr<WeakAttr>())
  2522. Class->addAttr(WeakAttr::CreateImplicit(Context));
  2523. }
  2524. }
  2525. }
  2526. // Attach the remaining base class specifiers to the derived class.
  2527. Class->setBases(Bases.data(), NumGoodBases);
  2528. // Check that the only base classes that are duplicate are virtual.
  2529. for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
  2530. // Check whether this direct base is inaccessible due to ambiguity.
  2531. QualType BaseType = Bases[idx]->getType();
  2532. // Skip all dependent types in templates being used as base specifiers.
  2533. // Checks below assume that the base specifier is a CXXRecord.
  2534. if (BaseType->isDependentType())
  2535. continue;
  2536. CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
  2537. .getUnqualifiedType();
  2538. if (IndirectBaseTypes.count(CanonicalBase)) {
  2539. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2540. /*DetectVirtual=*/true);
  2541. bool found
  2542. = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
  2543. assert(found);
  2544. (void)found;
  2545. if (Paths.isAmbiguous(CanonicalBase))
  2546. Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
  2547. << BaseType << getAmbiguousPathsDisplayString(Paths)
  2548. << Bases[idx]->getSourceRange();
  2549. else
  2550. assert(Bases[idx]->isVirtual());
  2551. }
  2552. // Delete the base class specifier, since its data has been copied
  2553. // into the CXXRecordDecl.
  2554. Context.Deallocate(Bases[idx]);
  2555. }
  2556. return Invalid;
  2557. }
  2558. /// ActOnBaseSpecifiers - Attach the given base specifiers to the
  2559. /// class, after checking whether there are any duplicate base
  2560. /// classes.
  2561. void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
  2562. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2563. if (!ClassDecl || Bases.empty())
  2564. return;
  2565. AdjustDeclIfTemplate(ClassDecl);
  2566. AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
  2567. }
  2568. /// Determine whether the type \p Derived is a C++ class that is
  2569. /// derived from the type \p Base.
  2570. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
  2571. if (!getLangOpts().CPlusPlus)
  2572. return false;
  2573. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2574. if (!DerivedRD)
  2575. return false;
  2576. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2577. if (!BaseRD)
  2578. return false;
  2579. // If either the base or the derived type is invalid, don't try to
  2580. // check whether one is derived from the other.
  2581. if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
  2582. return false;
  2583. // FIXME: In a modules build, do we need the entire path to be visible for us
  2584. // to be able to use the inheritance relationship?
  2585. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2586. return false;
  2587. return DerivedRD->isDerivedFrom(BaseRD);
  2588. }
  2589. /// Determine whether the type \p Derived is a C++ class that is
  2590. /// derived from the type \p Base.
  2591. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
  2592. CXXBasePaths &Paths) {
  2593. if (!getLangOpts().CPlusPlus)
  2594. return false;
  2595. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2596. if (!DerivedRD)
  2597. return false;
  2598. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2599. if (!BaseRD)
  2600. return false;
  2601. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2602. return false;
  2603. return DerivedRD->isDerivedFrom(BaseRD, Paths);
  2604. }
  2605. static void BuildBasePathArray(const CXXBasePath &Path,
  2606. CXXCastPath &BasePathArray) {
  2607. // We first go backward and check if we have a virtual base.
  2608. // FIXME: It would be better if CXXBasePath had the base specifier for
  2609. // the nearest virtual base.
  2610. unsigned Start = 0;
  2611. for (unsigned I = Path.size(); I != 0; --I) {
  2612. if (Path[I - 1].Base->isVirtual()) {
  2613. Start = I - 1;
  2614. break;
  2615. }
  2616. }
  2617. // Now add all bases.
  2618. for (unsigned I = Start, E = Path.size(); I != E; ++I)
  2619. BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
  2620. }
  2621. void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
  2622. CXXCastPath &BasePathArray) {
  2623. assert(BasePathArray.empty() && "Base path array must be empty!");
  2624. assert(Paths.isRecordingPaths() && "Must record paths!");
  2625. return ::BuildBasePathArray(Paths.front(), BasePathArray);
  2626. }
  2627. /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
  2628. /// conversion (where Derived and Base are class types) is
  2629. /// well-formed, meaning that the conversion is unambiguous (and
  2630. /// that all of the base classes are accessible). Returns true
  2631. /// and emits a diagnostic if the code is ill-formed, returns false
  2632. /// otherwise. Loc is the location where this routine should point to
  2633. /// if there is an error, and Range is the source range to highlight
  2634. /// if there is an error.
  2635. ///
  2636. /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
  2637. /// diagnostic for the respective type of error will be suppressed, but the
  2638. /// check for ill-formed code will still be performed.
  2639. bool
  2640. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2641. unsigned InaccessibleBaseID,
  2642. unsigned AmbiguousBaseConvID,
  2643. SourceLocation Loc, SourceRange Range,
  2644. DeclarationName Name,
  2645. CXXCastPath *BasePath,
  2646. bool IgnoreAccess) {
  2647. // First, determine whether the path from Derived to Base is
  2648. // ambiguous. This is slightly more expensive than checking whether
  2649. // the Derived to Base conversion exists, because here we need to
  2650. // explore multiple paths to determine if there is an ambiguity.
  2651. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2652. /*DetectVirtual=*/false);
  2653. bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2654. if (!DerivationOkay)
  2655. return true;
  2656. const CXXBasePath *Path = nullptr;
  2657. if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
  2658. Path = &Paths.front();
  2659. // For MSVC compatibility, check if Derived directly inherits from Base. Clang
  2660. // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
  2661. // user to access such bases.
  2662. if (!Path && getLangOpts().MSVCCompat) {
  2663. for (const CXXBasePath &PossiblePath : Paths) {
  2664. if (PossiblePath.size() == 1) {
  2665. Path = &PossiblePath;
  2666. if (AmbiguousBaseConvID)
  2667. Diag(Loc, diag::ext_ms_ambiguous_direct_base)
  2668. << Base << Derived << Range;
  2669. break;
  2670. }
  2671. }
  2672. }
  2673. if (Path) {
  2674. if (!IgnoreAccess) {
  2675. // Check that the base class can be accessed.
  2676. switch (
  2677. CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
  2678. case AR_inaccessible:
  2679. return true;
  2680. case AR_accessible:
  2681. case AR_dependent:
  2682. case AR_delayed:
  2683. break;
  2684. }
  2685. }
  2686. // Build a base path if necessary.
  2687. if (BasePath)
  2688. ::BuildBasePathArray(*Path, *BasePath);
  2689. return false;
  2690. }
  2691. if (AmbiguousBaseConvID) {
  2692. // We know that the derived-to-base conversion is ambiguous, and
  2693. // we're going to produce a diagnostic. Perform the derived-to-base
  2694. // search just one more time to compute all of the possible paths so
  2695. // that we can print them out. This is more expensive than any of
  2696. // the previous derived-to-base checks we've done, but at this point
  2697. // performance isn't as much of an issue.
  2698. Paths.clear();
  2699. Paths.setRecordingPaths(true);
  2700. bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2701. assert(StillOkay && "Can only be used with a derived-to-base conversion");
  2702. (void)StillOkay;
  2703. // Build up a textual representation of the ambiguous paths, e.g.,
  2704. // D -> B -> A, that will be used to illustrate the ambiguous
  2705. // conversions in the diagnostic. We only print one of the paths
  2706. // to each base class subobject.
  2707. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2708. Diag(Loc, AmbiguousBaseConvID)
  2709. << Derived << Base << PathDisplayStr << Range << Name;
  2710. }
  2711. return true;
  2712. }
  2713. bool
  2714. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2715. SourceLocation Loc, SourceRange Range,
  2716. CXXCastPath *BasePath,
  2717. bool IgnoreAccess) {
  2718. return CheckDerivedToBaseConversion(
  2719. Derived, Base, diag::err_upcast_to_inaccessible_base,
  2720. diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
  2721. BasePath, IgnoreAccess);
  2722. }
  2723. /// Builds a string representing ambiguous paths from a
  2724. /// specific derived class to different subobjects of the same base
  2725. /// class.
  2726. ///
  2727. /// This function builds a string that can be used in error messages
  2728. /// to show the different paths that one can take through the
  2729. /// inheritance hierarchy to go from the derived class to different
  2730. /// subobjects of a base class. The result looks something like this:
  2731. /// @code
  2732. /// struct D -> struct B -> struct A
  2733. /// struct D -> struct C -> struct A
  2734. /// @endcode
  2735. std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
  2736. std::string PathDisplayStr;
  2737. std::set<unsigned> DisplayedPaths;
  2738. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  2739. Path != Paths.end(); ++Path) {
  2740. if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
  2741. // We haven't displayed a path to this particular base
  2742. // class subobject yet.
  2743. PathDisplayStr += "\n ";
  2744. PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
  2745. for (CXXBasePath::const_iterator Element = Path->begin();
  2746. Element != Path->end(); ++Element)
  2747. PathDisplayStr += " -> " + Element->Base->getType().getAsString();
  2748. }
  2749. }
  2750. return PathDisplayStr;
  2751. }
  2752. //===----------------------------------------------------------------------===//
  2753. // C++ class member Handling
  2754. //===----------------------------------------------------------------------===//
  2755. /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
  2756. bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
  2757. SourceLocation ColonLoc,
  2758. const ParsedAttributesView &Attrs) {
  2759. assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
  2760. AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
  2761. ASLoc, ColonLoc);
  2762. CurContext->addHiddenDecl(ASDecl);
  2763. return ProcessAccessDeclAttributeList(ASDecl, Attrs);
  2764. }
  2765. /// CheckOverrideControl - Check C++11 override control semantics.
  2766. void Sema::CheckOverrideControl(NamedDecl *D) {
  2767. if (D->isInvalidDecl())
  2768. return;
  2769. // We only care about "override" and "final" declarations.
  2770. if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
  2771. return;
  2772. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2773. // We can't check dependent instance methods.
  2774. if (MD && MD->isInstance() &&
  2775. (MD->getParent()->hasAnyDependentBases() ||
  2776. MD->getType()->isDependentType()))
  2777. return;
  2778. if (MD && !MD->isVirtual()) {
  2779. // If we have a non-virtual method, check if it hides a virtual method.
  2780. // (In that case, it's most likely the method has the wrong type.)
  2781. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  2782. FindHiddenVirtualMethods(MD, OverloadedMethods);
  2783. if (!OverloadedMethods.empty()) {
  2784. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2785. Diag(OA->getLocation(),
  2786. diag::override_keyword_hides_virtual_member_function)
  2787. << "override" << (OverloadedMethods.size() > 1);
  2788. } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2789. Diag(FA->getLocation(),
  2790. diag::override_keyword_hides_virtual_member_function)
  2791. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2792. << (OverloadedMethods.size() > 1);
  2793. }
  2794. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  2795. MD->setInvalidDecl();
  2796. return;
  2797. }
  2798. // Fall through into the general case diagnostic.
  2799. // FIXME: We might want to attempt typo correction here.
  2800. }
  2801. if (!MD || !MD->isVirtual()) {
  2802. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2803. Diag(OA->getLocation(),
  2804. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2805. << "override" << FixItHint::CreateRemoval(OA->getLocation());
  2806. D->dropAttr<OverrideAttr>();
  2807. }
  2808. if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2809. Diag(FA->getLocation(),
  2810. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2811. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2812. << FixItHint::CreateRemoval(FA->getLocation());
  2813. D->dropAttr<FinalAttr>();
  2814. }
  2815. return;
  2816. }
  2817. // C++11 [class.virtual]p5:
  2818. // If a function is marked with the virt-specifier override and
  2819. // does not override a member function of a base class, the program is
  2820. // ill-formed.
  2821. bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
  2822. if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
  2823. Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
  2824. << MD->getDeclName();
  2825. }
  2826. void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
  2827. if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
  2828. return;
  2829. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2830. if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
  2831. return;
  2832. SourceLocation Loc = MD->getLocation();
  2833. SourceLocation SpellingLoc = Loc;
  2834. if (getSourceManager().isMacroArgExpansion(Loc))
  2835. SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
  2836. SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
  2837. if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
  2838. return;
  2839. if (MD->size_overridden_methods() > 0) {
  2840. auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
  2841. unsigned DiagID =
  2842. Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
  2843. ? DiagInconsistent
  2844. : DiagSuggest;
  2845. Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  2846. const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
  2847. Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
  2848. };
  2849. if (isa<CXXDestructorDecl>(MD))
  2850. EmitDiag(
  2851. diag::warn_inconsistent_destructor_marked_not_override_overriding,
  2852. diag::warn_suggest_destructor_marked_not_override_overriding);
  2853. else
  2854. EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
  2855. diag::warn_suggest_function_marked_not_override_overriding);
  2856. }
  2857. }
  2858. /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
  2859. /// function overrides a virtual member function marked 'final', according to
  2860. /// C++11 [class.virtual]p4.
  2861. bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
  2862. const CXXMethodDecl *Old) {
  2863. FinalAttr *FA = Old->getAttr<FinalAttr>();
  2864. if (!FA)
  2865. return false;
  2866. Diag(New->getLocation(), diag::err_final_function_overridden)
  2867. << New->getDeclName()
  2868. << FA->isSpelledAsSealed();
  2869. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  2870. return true;
  2871. }
  2872. static bool InitializationHasSideEffects(const FieldDecl &FD) {
  2873. const Type *T = FD.getType()->getBaseElementTypeUnsafe();
  2874. // FIXME: Destruction of ObjC lifetime types has side-effects.
  2875. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  2876. return !RD->isCompleteDefinition() ||
  2877. !RD->hasTrivialDefaultConstructor() ||
  2878. !RD->hasTrivialDestructor();
  2879. return false;
  2880. }
  2881. static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
  2882. ParsedAttributesView::const_iterator Itr =
  2883. llvm::find_if(list, [](const ParsedAttr &AL) {
  2884. return AL.isDeclspecPropertyAttribute();
  2885. });
  2886. if (Itr != list.end())
  2887. return &*Itr;
  2888. return nullptr;
  2889. }
  2890. // Check if there is a field shadowing.
  2891. void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
  2892. DeclarationName FieldName,
  2893. const CXXRecordDecl *RD,
  2894. bool DeclIsField) {
  2895. if (Diags.isIgnored(diag::warn_shadow_field, Loc))
  2896. return;
  2897. // To record a shadowed field in a base
  2898. std::map<CXXRecordDecl*, NamedDecl*> Bases;
  2899. auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
  2900. CXXBasePath &Path) {
  2901. const auto Base = Specifier->getType()->getAsCXXRecordDecl();
  2902. // Record an ambiguous path directly
  2903. if (Bases.find(Base) != Bases.end())
  2904. return true;
  2905. for (const auto Field : Base->lookup(FieldName)) {
  2906. if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
  2907. Field->getAccess() != AS_private) {
  2908. assert(Field->getAccess() != AS_none);
  2909. assert(Bases.find(Base) == Bases.end());
  2910. Bases[Base] = Field;
  2911. return true;
  2912. }
  2913. }
  2914. return false;
  2915. };
  2916. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2917. /*DetectVirtual=*/true);
  2918. if (!RD->lookupInBases(FieldShadowed, Paths))
  2919. return;
  2920. for (const auto &P : Paths) {
  2921. auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
  2922. auto It = Bases.find(Base);
  2923. // Skip duplicated bases
  2924. if (It == Bases.end())
  2925. continue;
  2926. auto BaseField = It->second;
  2927. assert(BaseField->getAccess() != AS_private);
  2928. if (AS_none !=
  2929. CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
  2930. Diag(Loc, diag::warn_shadow_field)
  2931. << FieldName << RD << Base << DeclIsField;
  2932. Diag(BaseField->getLocation(), diag::note_shadow_field);
  2933. Bases.erase(It);
  2934. }
  2935. }
  2936. }
  2937. /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
  2938. /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
  2939. /// bitfield width if there is one, 'InitExpr' specifies the initializer if
  2940. /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
  2941. /// present (but parsing it has been deferred).
  2942. NamedDecl *
  2943. Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
  2944. MultiTemplateParamsArg TemplateParameterLists,
  2945. Expr *BW, const VirtSpecifiers &VS,
  2946. InClassInitStyle InitStyle) {
  2947. const DeclSpec &DS = D.getDeclSpec();
  2948. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  2949. DeclarationName Name = NameInfo.getName();
  2950. SourceLocation Loc = NameInfo.getLoc();
  2951. // For anonymous bitfields, the location should point to the type.
  2952. if (Loc.isInvalid())
  2953. Loc = D.getBeginLoc();
  2954. Expr *BitWidth = static_cast<Expr*>(BW);
  2955. assert(isa<CXXRecordDecl>(CurContext));
  2956. assert(!DS.isFriendSpecified());
  2957. bool isFunc = D.isDeclarationOfFunction();
  2958. const ParsedAttr *MSPropertyAttr =
  2959. getMSPropertyAttr(D.getDeclSpec().getAttributes());
  2960. if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
  2961. // The Microsoft extension __interface only permits public member functions
  2962. // and prohibits constructors, destructors, operators, non-public member
  2963. // functions, static methods and data members.
  2964. unsigned InvalidDecl;
  2965. bool ShowDeclName = true;
  2966. if (!isFunc &&
  2967. (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
  2968. InvalidDecl = 0;
  2969. else if (!isFunc)
  2970. InvalidDecl = 1;
  2971. else if (AS != AS_public)
  2972. InvalidDecl = 2;
  2973. else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
  2974. InvalidDecl = 3;
  2975. else switch (Name.getNameKind()) {
  2976. case DeclarationName::CXXConstructorName:
  2977. InvalidDecl = 4;
  2978. ShowDeclName = false;
  2979. break;
  2980. case DeclarationName::CXXDestructorName:
  2981. InvalidDecl = 5;
  2982. ShowDeclName = false;
  2983. break;
  2984. case DeclarationName::CXXOperatorName:
  2985. case DeclarationName::CXXConversionFunctionName:
  2986. InvalidDecl = 6;
  2987. break;
  2988. default:
  2989. InvalidDecl = 0;
  2990. break;
  2991. }
  2992. if (InvalidDecl) {
  2993. if (ShowDeclName)
  2994. Diag(Loc, diag::err_invalid_member_in_interface)
  2995. << (InvalidDecl-1) << Name;
  2996. else
  2997. Diag(Loc, diag::err_invalid_member_in_interface)
  2998. << (InvalidDecl-1) << "";
  2999. return nullptr;
  3000. }
  3001. }
  3002. // C++ 9.2p6: A member shall not be declared to have automatic storage
  3003. // duration (auto, register) or with the extern storage-class-specifier.
  3004. // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
  3005. // data members and cannot be applied to names declared const or static,
  3006. // and cannot be applied to reference members.
  3007. switch (DS.getStorageClassSpec()) {
  3008. case DeclSpec::SCS_unspecified:
  3009. case DeclSpec::SCS_typedef:
  3010. case DeclSpec::SCS_static:
  3011. break;
  3012. case DeclSpec::SCS_mutable:
  3013. if (isFunc) {
  3014. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
  3015. // FIXME: It would be nicer if the keyword was ignored only for this
  3016. // declarator. Otherwise we could get follow-up errors.
  3017. D.getMutableDeclSpec().ClearStorageClassSpecs();
  3018. }
  3019. break;
  3020. default:
  3021. Diag(DS.getStorageClassSpecLoc(),
  3022. diag::err_storageclass_invalid_for_member);
  3023. D.getMutableDeclSpec().ClearStorageClassSpecs();
  3024. break;
  3025. }
  3026. bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
  3027. DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
  3028. !isFunc);
  3029. if (DS.hasConstexprSpecifier() && isInstField) {
  3030. SemaDiagnosticBuilder B =
  3031. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
  3032. SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
  3033. if (InitStyle == ICIS_NoInit) {
  3034. B << 0 << 0;
  3035. if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
  3036. B << FixItHint::CreateRemoval(ConstexprLoc);
  3037. else {
  3038. B << FixItHint::CreateReplacement(ConstexprLoc, "const");
  3039. D.getMutableDeclSpec().ClearConstexprSpec();
  3040. const char *PrevSpec;
  3041. unsigned DiagID;
  3042. bool Failed = D.getMutableDeclSpec().SetTypeQual(
  3043. DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
  3044. (void)Failed;
  3045. assert(!Failed && "Making a constexpr member const shouldn't fail");
  3046. }
  3047. } else {
  3048. B << 1;
  3049. const char *PrevSpec;
  3050. unsigned DiagID;
  3051. if (D.getMutableDeclSpec().SetStorageClassSpec(
  3052. *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
  3053. Context.getPrintingPolicy())) {
  3054. assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
  3055. "This is the only DeclSpec that should fail to be applied");
  3056. B << 1;
  3057. } else {
  3058. B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
  3059. isInstField = false;
  3060. }
  3061. }
  3062. }
  3063. NamedDecl *Member;
  3064. if (isInstField) {
  3065. CXXScopeSpec &SS = D.getCXXScopeSpec();
  3066. // Data members must have identifiers for names.
  3067. if (!Name.isIdentifier()) {
  3068. Diag(Loc, diag::err_bad_variable_name)
  3069. << Name;
  3070. return nullptr;
  3071. }
  3072. IdentifierInfo *II = Name.getAsIdentifierInfo();
  3073. // Member field could not be with "template" keyword.
  3074. // So TemplateParameterLists should be empty in this case.
  3075. if (TemplateParameterLists.size()) {
  3076. TemplateParameterList* TemplateParams = TemplateParameterLists[0];
  3077. if (TemplateParams->size()) {
  3078. // There is no such thing as a member field template.
  3079. Diag(D.getIdentifierLoc(), diag::err_template_member)
  3080. << II
  3081. << SourceRange(TemplateParams->getTemplateLoc(),
  3082. TemplateParams->getRAngleLoc());
  3083. } else {
  3084. // There is an extraneous 'template<>' for this member.
  3085. Diag(TemplateParams->getTemplateLoc(),
  3086. diag::err_template_member_noparams)
  3087. << II
  3088. << SourceRange(TemplateParams->getTemplateLoc(),
  3089. TemplateParams->getRAngleLoc());
  3090. }
  3091. return nullptr;
  3092. }
  3093. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  3094. Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
  3095. << II
  3096. << SourceRange(D.getName().TemplateId->LAngleLoc,
  3097. D.getName().TemplateId->RAngleLoc)
  3098. << D.getName().TemplateId->LAngleLoc;
  3099. D.SetIdentifier(II, Loc);
  3100. }
  3101. if (SS.isSet() && !SS.isInvalid()) {
  3102. // The user provided a superfluous scope specifier inside a class
  3103. // definition:
  3104. //
  3105. // class X {
  3106. // int X::member;
  3107. // };
  3108. if (DeclContext *DC = computeDeclContext(SS, false))
  3109. diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
  3110. D.getName().getKind() ==
  3111. UnqualifiedIdKind::IK_TemplateId);
  3112. else
  3113. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  3114. << Name << SS.getRange();
  3115. SS.clear();
  3116. }
  3117. if (MSPropertyAttr) {
  3118. Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  3119. BitWidth, InitStyle, AS, *MSPropertyAttr);
  3120. if (!Member)
  3121. return nullptr;
  3122. isInstField = false;
  3123. } else {
  3124. Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  3125. BitWidth, InitStyle, AS);
  3126. if (!Member)
  3127. return nullptr;
  3128. }
  3129. CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
  3130. } else {
  3131. Member = HandleDeclarator(S, D, TemplateParameterLists);
  3132. if (!Member)
  3133. return nullptr;
  3134. // Non-instance-fields can't have a bitfield.
  3135. if (BitWidth) {
  3136. if (Member->isInvalidDecl()) {
  3137. // don't emit another diagnostic.
  3138. } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
  3139. // C++ 9.6p3: A bit-field shall not be a static member.
  3140. // "static member 'A' cannot be a bit-field"
  3141. Diag(Loc, diag::err_static_not_bitfield)
  3142. << Name << BitWidth->getSourceRange();
  3143. } else if (isa<TypedefDecl>(Member)) {
  3144. // "typedef member 'x' cannot be a bit-field"
  3145. Diag(Loc, diag::err_typedef_not_bitfield)
  3146. << Name << BitWidth->getSourceRange();
  3147. } else {
  3148. // A function typedef ("typedef int f(); f a;").
  3149. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  3150. Diag(Loc, diag::err_not_integral_type_bitfield)
  3151. << Name << cast<ValueDecl>(Member)->getType()
  3152. << BitWidth->getSourceRange();
  3153. }
  3154. BitWidth = nullptr;
  3155. Member->setInvalidDecl();
  3156. }
  3157. NamedDecl *NonTemplateMember = Member;
  3158. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
  3159. NonTemplateMember = FunTmpl->getTemplatedDecl();
  3160. else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
  3161. NonTemplateMember = VarTmpl->getTemplatedDecl();
  3162. Member->setAccess(AS);
  3163. // If we have declared a member function template or static data member
  3164. // template, set the access of the templated declaration as well.
  3165. if (NonTemplateMember != Member)
  3166. NonTemplateMember->setAccess(AS);
  3167. // C++ [temp.deduct.guide]p3:
  3168. // A deduction guide [...] for a member class template [shall be
  3169. // declared] with the same access [as the template].
  3170. if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
  3171. auto *TD = DG->getDeducedTemplate();
  3172. // Access specifiers are only meaningful if both the template and the
  3173. // deduction guide are from the same scope.
  3174. if (AS != TD->getAccess() &&
  3175. TD->getDeclContext()->getRedeclContext()->Equals(
  3176. DG->getDeclContext()->getRedeclContext())) {
  3177. Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
  3178. Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
  3179. << TD->getAccess();
  3180. const AccessSpecDecl *LastAccessSpec = nullptr;
  3181. for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
  3182. if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
  3183. LastAccessSpec = AccessSpec;
  3184. }
  3185. assert(LastAccessSpec && "differing access with no access specifier");
  3186. Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
  3187. << AS;
  3188. }
  3189. }
  3190. }
  3191. if (VS.isOverrideSpecified())
  3192. Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
  3193. AttributeCommonInfo::AS_Keyword));
  3194. if (VS.isFinalSpecified())
  3195. Member->addAttr(FinalAttr::Create(
  3196. Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
  3197. static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
  3198. if (VS.getLastLocation().isValid()) {
  3199. // Update the end location of a method that has a virt-specifiers.
  3200. if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
  3201. MD->setRangeEnd(VS.getLastLocation());
  3202. }
  3203. CheckOverrideControl(Member);
  3204. assert((Name || isInstField) && "No identifier for non-field ?");
  3205. if (isInstField) {
  3206. FieldDecl *FD = cast<FieldDecl>(Member);
  3207. FieldCollector->Add(FD);
  3208. if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
  3209. // Remember all explicit private FieldDecls that have a name, no side
  3210. // effects and are not part of a dependent type declaration.
  3211. if (!FD->isImplicit() && FD->getDeclName() &&
  3212. FD->getAccess() == AS_private &&
  3213. !FD->hasAttr<UnusedAttr>() &&
  3214. !FD->getParent()->isDependentContext() &&
  3215. !InitializationHasSideEffects(*FD))
  3216. UnusedPrivateFields.insert(FD);
  3217. }
  3218. }
  3219. return Member;
  3220. }
  3221. namespace {
  3222. class UninitializedFieldVisitor
  3223. : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
  3224. Sema &S;
  3225. // List of Decls to generate a warning on. Also remove Decls that become
  3226. // initialized.
  3227. llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
  3228. // List of base classes of the record. Classes are removed after their
  3229. // initializers.
  3230. llvm::SmallPtrSetImpl<QualType> &BaseClasses;
  3231. // Vector of decls to be removed from the Decl set prior to visiting the
  3232. // nodes. These Decls may have been initialized in the prior initializer.
  3233. llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
  3234. // If non-null, add a note to the warning pointing back to the constructor.
  3235. const CXXConstructorDecl *Constructor;
  3236. // Variables to hold state when processing an initializer list. When
  3237. // InitList is true, special case initialization of FieldDecls matching
  3238. // InitListFieldDecl.
  3239. bool InitList;
  3240. FieldDecl *InitListFieldDecl;
  3241. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  3242. public:
  3243. typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
  3244. UninitializedFieldVisitor(Sema &S,
  3245. llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
  3246. llvm::SmallPtrSetImpl<QualType> &BaseClasses)
  3247. : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
  3248. Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
  3249. // Returns true if the use of ME is not an uninitialized use.
  3250. bool IsInitListMemberExprInitialized(MemberExpr *ME,
  3251. bool CheckReferenceOnly) {
  3252. llvm::SmallVector<FieldDecl*, 4> Fields;
  3253. bool ReferenceField = false;
  3254. while (ME) {
  3255. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  3256. if (!FD)
  3257. return false;
  3258. Fields.push_back(FD);
  3259. if (FD->getType()->isReferenceType())
  3260. ReferenceField = true;
  3261. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
  3262. }
  3263. // Binding a reference to an uninitialized field is not an
  3264. // uninitialized use.
  3265. if (CheckReferenceOnly && !ReferenceField)
  3266. return true;
  3267. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  3268. // Discard the first field since it is the field decl that is being
  3269. // initialized.
  3270. for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
  3271. UsedFieldIndex.push_back(FD->getFieldIndex());
  3272. for (auto UsedIter = UsedFieldIndex.begin(),
  3273. UsedEnd = UsedFieldIndex.end(),
  3274. OrigIter = InitFieldIndex.begin(),
  3275. OrigEnd = InitFieldIndex.end();
  3276. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  3277. if (*UsedIter < *OrigIter)
  3278. return true;
  3279. if (*UsedIter > *OrigIter)
  3280. break;
  3281. }
  3282. return false;
  3283. }
  3284. void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
  3285. bool AddressOf) {
  3286. if (isa<EnumConstantDecl>(ME->getMemberDecl()))
  3287. return;
  3288. // FieldME is the inner-most MemberExpr that is not an anonymous struct
  3289. // or union.
  3290. MemberExpr *FieldME = ME;
  3291. bool AllPODFields = FieldME->getType().isPODType(S.Context);
  3292. Expr *Base = ME;
  3293. while (MemberExpr *SubME =
  3294. dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
  3295. if (isa<VarDecl>(SubME->getMemberDecl()))
  3296. return;
  3297. if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
  3298. if (!FD->isAnonymousStructOrUnion())
  3299. FieldME = SubME;
  3300. if (!FieldME->getType().isPODType(S.Context))
  3301. AllPODFields = false;
  3302. Base = SubME->getBase();
  3303. }
  3304. if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
  3305. Visit(Base);
  3306. return;
  3307. }
  3308. if (AddressOf && AllPODFields)
  3309. return;
  3310. ValueDecl* FoundVD = FieldME->getMemberDecl();
  3311. if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
  3312. while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
  3313. BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
  3314. }
  3315. if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
  3316. QualType T = BaseCast->getType();
  3317. if (T->isPointerType() &&
  3318. BaseClasses.count(T->getPointeeType())) {
  3319. S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
  3320. << T->getPointeeType() << FoundVD;
  3321. }
  3322. }
  3323. }
  3324. if (!Decls.count(FoundVD))
  3325. return;
  3326. const bool IsReference = FoundVD->getType()->isReferenceType();
  3327. if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
  3328. // Special checking for initializer lists.
  3329. if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
  3330. return;
  3331. }
  3332. } else {
  3333. // Prevent double warnings on use of unbounded references.
  3334. if (CheckReferenceOnly && !IsReference)
  3335. return;
  3336. }
  3337. unsigned diag = IsReference
  3338. ? diag::warn_reference_field_is_uninit
  3339. : diag::warn_field_is_uninit;
  3340. S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
  3341. if (Constructor)
  3342. S.Diag(Constructor->getLocation(),
  3343. diag::note_uninit_in_this_constructor)
  3344. << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
  3345. }
  3346. void HandleValue(Expr *E, bool AddressOf) {
  3347. E = E->IgnoreParens();
  3348. if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3349. HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
  3350. AddressOf /*AddressOf*/);
  3351. return;
  3352. }
  3353. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  3354. Visit(CO->getCond());
  3355. HandleValue(CO->getTrueExpr(), AddressOf);
  3356. HandleValue(CO->getFalseExpr(), AddressOf);
  3357. return;
  3358. }
  3359. if (BinaryConditionalOperator *BCO =
  3360. dyn_cast<BinaryConditionalOperator>(E)) {
  3361. Visit(BCO->getCond());
  3362. HandleValue(BCO->getFalseExpr(), AddressOf);
  3363. return;
  3364. }
  3365. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  3366. HandleValue(OVE->getSourceExpr(), AddressOf);
  3367. return;
  3368. }
  3369. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  3370. switch (BO->getOpcode()) {
  3371. default:
  3372. break;
  3373. case(BO_PtrMemD):
  3374. case(BO_PtrMemI):
  3375. HandleValue(BO->getLHS(), AddressOf);
  3376. Visit(BO->getRHS());
  3377. return;
  3378. case(BO_Comma):
  3379. Visit(BO->getLHS());
  3380. HandleValue(BO->getRHS(), AddressOf);
  3381. return;
  3382. }
  3383. }
  3384. Visit(E);
  3385. }
  3386. void CheckInitListExpr(InitListExpr *ILE) {
  3387. InitFieldIndex.push_back(0);
  3388. for (auto *Child : ILE->children()) {
  3389. if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
  3390. CheckInitListExpr(SubList);
  3391. } else {
  3392. Visit(Child);
  3393. }
  3394. ++InitFieldIndex.back();
  3395. }
  3396. InitFieldIndex.pop_back();
  3397. }
  3398. void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
  3399. FieldDecl *Field, const Type *BaseClass) {
  3400. // Remove Decls that may have been initialized in the previous
  3401. // initializer.
  3402. for (ValueDecl* VD : DeclsToRemove)
  3403. Decls.erase(VD);
  3404. DeclsToRemove.clear();
  3405. Constructor = FieldConstructor;
  3406. InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  3407. if (ILE && Field) {
  3408. InitList = true;
  3409. InitListFieldDecl = Field;
  3410. InitFieldIndex.clear();
  3411. CheckInitListExpr(ILE);
  3412. } else {
  3413. InitList = false;
  3414. Visit(E);
  3415. }
  3416. if (Field)
  3417. Decls.erase(Field);
  3418. if (BaseClass)
  3419. BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
  3420. }
  3421. void VisitMemberExpr(MemberExpr *ME) {
  3422. // All uses of unbounded reference fields will warn.
  3423. HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
  3424. }
  3425. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  3426. if (E->getCastKind() == CK_LValueToRValue) {
  3427. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3428. return;
  3429. }
  3430. Inherited::VisitImplicitCastExpr(E);
  3431. }
  3432. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  3433. if (E->getConstructor()->isCopyConstructor()) {
  3434. Expr *ArgExpr = E->getArg(0);
  3435. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  3436. if (ILE->getNumInits() == 1)
  3437. ArgExpr = ILE->getInit(0);
  3438. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  3439. if (ICE->getCastKind() == CK_NoOp)
  3440. ArgExpr = ICE->getSubExpr();
  3441. HandleValue(ArgExpr, false /*AddressOf*/);
  3442. return;
  3443. }
  3444. Inherited::VisitCXXConstructExpr(E);
  3445. }
  3446. void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  3447. Expr *Callee = E->getCallee();
  3448. if (isa<MemberExpr>(Callee)) {
  3449. HandleValue(Callee, false /*AddressOf*/);
  3450. for (auto *Arg : E->arguments())
  3451. Visit(Arg);
  3452. return;
  3453. }
  3454. Inherited::VisitCXXMemberCallExpr(E);
  3455. }
  3456. void VisitCallExpr(CallExpr *E) {
  3457. // Treat std::move as a use.
  3458. if (E->isCallToStdMove()) {
  3459. HandleValue(E->getArg(0), /*AddressOf=*/false);
  3460. return;
  3461. }
  3462. Inherited::VisitCallExpr(E);
  3463. }
  3464. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  3465. Expr *Callee = E->getCallee();
  3466. if (isa<UnresolvedLookupExpr>(Callee))
  3467. return Inherited::VisitCXXOperatorCallExpr(E);
  3468. Visit(Callee);
  3469. for (auto *Arg : E->arguments())
  3470. HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
  3471. }
  3472. void VisitBinaryOperator(BinaryOperator *E) {
  3473. // If a field assignment is detected, remove the field from the
  3474. // uninitiailized field set.
  3475. if (E->getOpcode() == BO_Assign)
  3476. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
  3477. if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  3478. if (!FD->getType()->isReferenceType())
  3479. DeclsToRemove.push_back(FD);
  3480. if (E->isCompoundAssignmentOp()) {
  3481. HandleValue(E->getLHS(), false /*AddressOf*/);
  3482. Visit(E->getRHS());
  3483. return;
  3484. }
  3485. Inherited::VisitBinaryOperator(E);
  3486. }
  3487. void VisitUnaryOperator(UnaryOperator *E) {
  3488. if (E->isIncrementDecrementOp()) {
  3489. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3490. return;
  3491. }
  3492. if (E->getOpcode() == UO_AddrOf) {
  3493. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
  3494. HandleValue(ME->getBase(), true /*AddressOf*/);
  3495. return;
  3496. }
  3497. }
  3498. Inherited::VisitUnaryOperator(E);
  3499. }
  3500. };
  3501. // Diagnose value-uses of fields to initialize themselves, e.g.
  3502. // foo(foo)
  3503. // where foo is not also a parameter to the constructor.
  3504. // Also diagnose across field uninitialized use such as
  3505. // x(y), y(x)
  3506. // TODO: implement -Wuninitialized and fold this into that framework.
  3507. static void DiagnoseUninitializedFields(
  3508. Sema &SemaRef, const CXXConstructorDecl *Constructor) {
  3509. if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
  3510. Constructor->getLocation())) {
  3511. return;
  3512. }
  3513. if (Constructor->isInvalidDecl())
  3514. return;
  3515. const CXXRecordDecl *RD = Constructor->getParent();
  3516. if (RD->isDependentContext())
  3517. return;
  3518. // Holds fields that are uninitialized.
  3519. llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
  3520. // At the beginning, all fields are uninitialized.
  3521. for (auto *I : RD->decls()) {
  3522. if (auto *FD = dyn_cast<FieldDecl>(I)) {
  3523. UninitializedFields.insert(FD);
  3524. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
  3525. UninitializedFields.insert(IFD->getAnonField());
  3526. }
  3527. }
  3528. llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
  3529. for (auto I : RD->bases())
  3530. UninitializedBaseClasses.insert(I.getType().getCanonicalType());
  3531. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3532. return;
  3533. UninitializedFieldVisitor UninitializedChecker(SemaRef,
  3534. UninitializedFields,
  3535. UninitializedBaseClasses);
  3536. for (const auto *FieldInit : Constructor->inits()) {
  3537. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3538. break;
  3539. Expr *InitExpr = FieldInit->getInit();
  3540. if (!InitExpr)
  3541. continue;
  3542. if (CXXDefaultInitExpr *Default =
  3543. dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
  3544. InitExpr = Default->getExpr();
  3545. if (!InitExpr)
  3546. continue;
  3547. // In class initializers will point to the constructor.
  3548. UninitializedChecker.CheckInitializer(InitExpr, Constructor,
  3549. FieldInit->getAnyMember(),
  3550. FieldInit->getBaseClass());
  3551. } else {
  3552. UninitializedChecker.CheckInitializer(InitExpr, nullptr,
  3553. FieldInit->getAnyMember(),
  3554. FieldInit->getBaseClass());
  3555. }
  3556. }
  3557. }
  3558. } // namespace
  3559. /// Enter a new C++ default initializer scope. After calling this, the
  3560. /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
  3561. /// parsing or instantiating the initializer failed.
  3562. void Sema::ActOnStartCXXInClassMemberInitializer() {
  3563. // Create a synthetic function scope to represent the call to the constructor
  3564. // that notionally surrounds a use of this initializer.
  3565. PushFunctionScope();
  3566. }
  3567. void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
  3568. if (!D.isFunctionDeclarator())
  3569. return;
  3570. auto &FTI = D.getFunctionTypeInfo();
  3571. if (!FTI.Params)
  3572. return;
  3573. for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
  3574. FTI.NumParams)) {
  3575. auto *ParamDecl = cast<NamedDecl>(Param.Param);
  3576. if (ParamDecl->getDeclName())
  3577. PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
  3578. }
  3579. }
  3580. ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
  3581. return ActOnRequiresClause(ConstraintExpr);
  3582. }
  3583. ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
  3584. if (ConstraintExpr.isInvalid())
  3585. return ExprError();
  3586. ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
  3587. if (ConstraintExpr.isInvalid())
  3588. return ExprError();
  3589. if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
  3590. UPPC_RequiresClause))
  3591. return ExprError();
  3592. return ConstraintExpr;
  3593. }
  3594. ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
  3595. Expr *InitExpr,
  3596. SourceLocation InitLoc) {
  3597. InitializedEntity Entity =
  3598. InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
  3599. InitializationKind Kind =
  3600. FD->getInClassInitStyle() == ICIS_ListInit
  3601. ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
  3602. InitExpr->getBeginLoc(),
  3603. InitExpr->getEndLoc())
  3604. : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
  3605. InitializationSequence Seq(*this, Entity, Kind, InitExpr);
  3606. return Seq.Perform(*this, Entity, Kind, InitExpr);
  3607. }
  3608. /// This is invoked after parsing an in-class initializer for a
  3609. /// non-static C++ class member, and after instantiating an in-class initializer
  3610. /// in a class template. Such actions are deferred until the class is complete.
  3611. void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
  3612. SourceLocation InitLoc,
  3613. Expr *InitExpr) {
  3614. // Pop the notional constructor scope we created earlier.
  3615. PopFunctionScopeInfo(nullptr, D);
  3616. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  3617. assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
  3618. "must set init style when field is created");
  3619. if (!InitExpr) {
  3620. D->setInvalidDecl();
  3621. if (FD)
  3622. FD->removeInClassInitializer();
  3623. return;
  3624. }
  3625. if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
  3626. FD->setInvalidDecl();
  3627. FD->removeInClassInitializer();
  3628. return;
  3629. }
  3630. ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
  3631. /*RecoverUncorrectedTypos=*/true);
  3632. assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
  3633. if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
  3634. Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
  3635. // C++11 [class.base.init]p7:
  3636. // The initialization of each base and member constitutes a
  3637. // full-expression.
  3638. if (!Init.isInvalid())
  3639. Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
  3640. if (Init.isInvalid()) {
  3641. FD->setInvalidDecl();
  3642. return;
  3643. }
  3644. }
  3645. FD->setInClassInitializer(Init.get());
  3646. }
  3647. /// Find the direct and/or virtual base specifiers that
  3648. /// correspond to the given base type, for use in base initialization
  3649. /// within a constructor.
  3650. static bool FindBaseInitializer(Sema &SemaRef,
  3651. CXXRecordDecl *ClassDecl,
  3652. QualType BaseType,
  3653. const CXXBaseSpecifier *&DirectBaseSpec,
  3654. const CXXBaseSpecifier *&VirtualBaseSpec) {
  3655. // First, check for a direct base class.
  3656. DirectBaseSpec = nullptr;
  3657. for (const auto &Base : ClassDecl->bases()) {
  3658. if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
  3659. // We found a direct base of this type. That's what we're
  3660. // initializing.
  3661. DirectBaseSpec = &Base;
  3662. break;
  3663. }
  3664. }
  3665. // Check for a virtual base class.
  3666. // FIXME: We might be able to short-circuit this if we know in advance that
  3667. // there are no virtual bases.
  3668. VirtualBaseSpec = nullptr;
  3669. if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
  3670. // We haven't found a base yet; search the class hierarchy for a
  3671. // virtual base class.
  3672. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  3673. /*DetectVirtual=*/false);
  3674. if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
  3675. SemaRef.Context.getTypeDeclType(ClassDecl),
  3676. BaseType, Paths)) {
  3677. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  3678. Path != Paths.end(); ++Path) {
  3679. if (Path->back().Base->isVirtual()) {
  3680. VirtualBaseSpec = Path->back().Base;
  3681. break;
  3682. }
  3683. }
  3684. }
  3685. }
  3686. return DirectBaseSpec || VirtualBaseSpec;
  3687. }
  3688. /// Handle a C++ member initializer using braced-init-list syntax.
  3689. MemInitResult
  3690. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3691. Scope *S,
  3692. CXXScopeSpec &SS,
  3693. IdentifierInfo *MemberOrBase,
  3694. ParsedType TemplateTypeTy,
  3695. const DeclSpec &DS,
  3696. SourceLocation IdLoc,
  3697. Expr *InitList,
  3698. SourceLocation EllipsisLoc) {
  3699. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3700. DS, IdLoc, InitList,
  3701. EllipsisLoc);
  3702. }
  3703. /// Handle a C++ member initializer using parentheses syntax.
  3704. MemInitResult
  3705. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3706. Scope *S,
  3707. CXXScopeSpec &SS,
  3708. IdentifierInfo *MemberOrBase,
  3709. ParsedType TemplateTypeTy,
  3710. const DeclSpec &DS,
  3711. SourceLocation IdLoc,
  3712. SourceLocation LParenLoc,
  3713. ArrayRef<Expr *> Args,
  3714. SourceLocation RParenLoc,
  3715. SourceLocation EllipsisLoc) {
  3716. Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
  3717. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3718. DS, IdLoc, List, EllipsisLoc);
  3719. }
  3720. namespace {
  3721. // Callback to only accept typo corrections that can be a valid C++ member
  3722. // initializer: either a non-static field member or a base class.
  3723. class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
  3724. public:
  3725. explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
  3726. : ClassDecl(ClassDecl) {}
  3727. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3728. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  3729. if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
  3730. return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
  3731. return isa<TypeDecl>(ND);
  3732. }
  3733. return false;
  3734. }
  3735. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  3736. return std::make_unique<MemInitializerValidatorCCC>(*this);
  3737. }
  3738. private:
  3739. CXXRecordDecl *ClassDecl;
  3740. };
  3741. }
  3742. ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
  3743. CXXScopeSpec &SS,
  3744. ParsedType TemplateTypeTy,
  3745. IdentifierInfo *MemberOrBase) {
  3746. if (SS.getScopeRep() || TemplateTypeTy)
  3747. return nullptr;
  3748. for (auto *D : ClassDecl->lookup(MemberOrBase))
  3749. if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
  3750. return cast<ValueDecl>(D);
  3751. return nullptr;
  3752. }
  3753. /// Handle a C++ member initializer.
  3754. MemInitResult
  3755. Sema::BuildMemInitializer(Decl *ConstructorD,
  3756. Scope *S,
  3757. CXXScopeSpec &SS,
  3758. IdentifierInfo *MemberOrBase,
  3759. ParsedType TemplateTypeTy,
  3760. const DeclSpec &DS,
  3761. SourceLocation IdLoc,
  3762. Expr *Init,
  3763. SourceLocation EllipsisLoc) {
  3764. ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
  3765. /*RecoverUncorrectedTypos=*/true);
  3766. if (!Res.isUsable())
  3767. return true;
  3768. Init = Res.get();
  3769. if (!ConstructorD)
  3770. return true;
  3771. AdjustDeclIfTemplate(ConstructorD);
  3772. CXXConstructorDecl *Constructor
  3773. = dyn_cast<CXXConstructorDecl>(ConstructorD);
  3774. if (!Constructor) {
  3775. // The user wrote a constructor initializer on a function that is
  3776. // not a C++ constructor. Ignore the error for now, because we may
  3777. // have more member initializers coming; we'll diagnose it just
  3778. // once in ActOnMemInitializers.
  3779. return true;
  3780. }
  3781. CXXRecordDecl *ClassDecl = Constructor->getParent();
  3782. // C++ [class.base.init]p2:
  3783. // Names in a mem-initializer-id are looked up in the scope of the
  3784. // constructor's class and, if not found in that scope, are looked
  3785. // up in the scope containing the constructor's definition.
  3786. // [Note: if the constructor's class contains a member with the
  3787. // same name as a direct or virtual base class of the class, a
  3788. // mem-initializer-id naming the member or base class and composed
  3789. // of a single identifier refers to the class member. A
  3790. // mem-initializer-id for the hidden base class may be specified
  3791. // using a qualified name. ]
  3792. // Look for a member, first.
  3793. if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
  3794. ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
  3795. if (EllipsisLoc.isValid())
  3796. Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
  3797. << MemberOrBase
  3798. << SourceRange(IdLoc, Init->getSourceRange().getEnd());
  3799. return BuildMemberInitializer(Member, Init, IdLoc);
  3800. }
  3801. // It didn't name a member, so see if it names a class.
  3802. QualType BaseType;
  3803. TypeSourceInfo *TInfo = nullptr;
  3804. if (TemplateTypeTy) {
  3805. BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
  3806. if (BaseType.isNull())
  3807. return true;
  3808. } else if (DS.getTypeSpecType() == TST_decltype) {
  3809. BaseType = BuildDecltypeType(DS.getRepAsExpr());
  3810. } else if (DS.getTypeSpecType() == TST_decltype_auto) {
  3811. Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
  3812. return true;
  3813. } else {
  3814. LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
  3815. LookupParsedName(R, S, &SS);
  3816. TypeDecl *TyD = R.getAsSingle<TypeDecl>();
  3817. if (!TyD) {
  3818. if (R.isAmbiguous()) return true;
  3819. // We don't want access-control diagnostics here.
  3820. R.suppressDiagnostics();
  3821. if (SS.isSet() && isDependentScopeSpecifier(SS)) {
  3822. bool NotUnknownSpecialization = false;
  3823. DeclContext *DC = computeDeclContext(SS, false);
  3824. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
  3825. NotUnknownSpecialization = !Record->hasAnyDependentBases();
  3826. if (!NotUnknownSpecialization) {
  3827. // When the scope specifier can refer to a member of an unknown
  3828. // specialization, we take it as a type name.
  3829. BaseType = CheckTypenameType(ETK_None, SourceLocation(),
  3830. SS.getWithLocInContext(Context),
  3831. *MemberOrBase, IdLoc);
  3832. if (BaseType.isNull())
  3833. return true;
  3834. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3835. DependentNameTypeLoc TL =
  3836. TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
  3837. if (!TL.isNull()) {
  3838. TL.setNameLoc(IdLoc);
  3839. TL.setElaboratedKeywordLoc(SourceLocation());
  3840. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3841. }
  3842. R.clear();
  3843. R.setLookupName(MemberOrBase);
  3844. }
  3845. }
  3846. if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
  3847. if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
  3848. auto *TempSpec = cast<TemplateSpecializationType>(
  3849. UnqualifiedBase->getInjectedClassNameSpecialization());
  3850. TemplateName TN = TempSpec->getTemplateName();
  3851. for (auto const &Base : ClassDecl->bases()) {
  3852. auto BaseTemplate =
  3853. Base.getType()->getAs<TemplateSpecializationType>();
  3854. if (BaseTemplate && Context.hasSameTemplateName(
  3855. BaseTemplate->getTemplateName(), TN)) {
  3856. Diag(IdLoc, diag::ext_unqualified_base_class)
  3857. << SourceRange(IdLoc, Init->getSourceRange().getEnd());
  3858. BaseType = Base.getType();
  3859. break;
  3860. }
  3861. }
  3862. }
  3863. }
  3864. // If no results were found, try to correct typos.
  3865. TypoCorrection Corr;
  3866. MemInitializerValidatorCCC CCC(ClassDecl);
  3867. if (R.empty() && BaseType.isNull() &&
  3868. (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  3869. CCC, CTK_ErrorRecovery, ClassDecl))) {
  3870. if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
  3871. // We have found a non-static data member with a similar
  3872. // name to what was typed; complain and initialize that
  3873. // member.
  3874. diagnoseTypo(Corr,
  3875. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3876. << MemberOrBase << true);
  3877. return BuildMemberInitializer(Member, Init, IdLoc);
  3878. } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
  3879. const CXXBaseSpecifier *DirectBaseSpec;
  3880. const CXXBaseSpecifier *VirtualBaseSpec;
  3881. if (FindBaseInitializer(*this, ClassDecl,
  3882. Context.getTypeDeclType(Type),
  3883. DirectBaseSpec, VirtualBaseSpec)) {
  3884. // We have found a direct or virtual base class with a
  3885. // similar name to what was typed; complain and initialize
  3886. // that base class.
  3887. diagnoseTypo(Corr,
  3888. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3889. << MemberOrBase << false,
  3890. PDiag() /*Suppress note, we provide our own.*/);
  3891. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
  3892. : VirtualBaseSpec;
  3893. Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
  3894. << BaseSpec->getType() << BaseSpec->getSourceRange();
  3895. TyD = Type;
  3896. }
  3897. }
  3898. }
  3899. if (!TyD && BaseType.isNull()) {
  3900. Diag(IdLoc, diag::err_mem_init_not_member_or_class)
  3901. << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
  3902. return true;
  3903. }
  3904. }
  3905. if (BaseType.isNull()) {
  3906. BaseType = getElaboratedType(ETK_None, SS, Context.getTypeDeclType(TyD));
  3907. MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
  3908. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3909. ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
  3910. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
  3911. TL.setElaboratedKeywordLoc(SourceLocation());
  3912. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3913. }
  3914. }
  3915. if (!TInfo)
  3916. TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
  3917. return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
  3918. }
  3919. MemInitResult
  3920. Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
  3921. SourceLocation IdLoc) {
  3922. FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
  3923. IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
  3924. assert((DirectMember || IndirectMember) &&
  3925. "Member must be a FieldDecl or IndirectFieldDecl");
  3926. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3927. return true;
  3928. if (Member->isInvalidDecl())
  3929. return true;
  3930. MultiExprArg Args;
  3931. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3932. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3933. } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  3934. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  3935. } else {
  3936. // Template instantiation doesn't reconstruct ParenListExprs for us.
  3937. Args = Init;
  3938. }
  3939. SourceRange InitRange = Init->getSourceRange();
  3940. if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
  3941. // Can't check initialization for a member of dependent type or when
  3942. // any of the arguments are type-dependent expressions.
  3943. DiscardCleanupsInEvaluationContext();
  3944. } else {
  3945. bool InitList = false;
  3946. if (isa<InitListExpr>(Init)) {
  3947. InitList = true;
  3948. Args = Init;
  3949. }
  3950. // Initialize the member.
  3951. InitializedEntity MemberEntity =
  3952. DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
  3953. : InitializedEntity::InitializeMember(IndirectMember,
  3954. nullptr);
  3955. InitializationKind Kind =
  3956. InitList ? InitializationKind::CreateDirectList(
  3957. IdLoc, Init->getBeginLoc(), Init->getEndLoc())
  3958. : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
  3959. InitRange.getEnd());
  3960. InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
  3961. ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
  3962. nullptr);
  3963. if (!MemberInit.isInvalid()) {
  3964. // C++11 [class.base.init]p7:
  3965. // The initialization of each base and member constitutes a
  3966. // full-expression.
  3967. MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
  3968. /*DiscardedValue*/ false);
  3969. }
  3970. if (MemberInit.isInvalid()) {
  3971. // Args were sensible expressions but we couldn't initialize the member
  3972. // from them. Preserve them in a RecoveryExpr instead.
  3973. Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
  3974. Member->getType())
  3975. .get();
  3976. if (!Init)
  3977. return true;
  3978. } else {
  3979. Init = MemberInit.get();
  3980. }
  3981. }
  3982. if (DirectMember) {
  3983. return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
  3984. InitRange.getBegin(), Init,
  3985. InitRange.getEnd());
  3986. } else {
  3987. return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
  3988. InitRange.getBegin(), Init,
  3989. InitRange.getEnd());
  3990. }
  3991. }
  3992. MemInitResult
  3993. Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
  3994. CXXRecordDecl *ClassDecl) {
  3995. SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
  3996. if (!LangOpts.CPlusPlus11)
  3997. return Diag(NameLoc, diag::err_delegating_ctor)
  3998. << TInfo->getTypeLoc().getSourceRange();
  3999. Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
  4000. bool InitList = true;
  4001. MultiExprArg Args = Init;
  4002. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  4003. InitList = false;
  4004. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  4005. }
  4006. SourceRange InitRange = Init->getSourceRange();
  4007. // Initialize the object.
  4008. InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
  4009. QualType(ClassDecl->getTypeForDecl(), 0));
  4010. InitializationKind Kind =
  4011. InitList ? InitializationKind::CreateDirectList(
  4012. NameLoc, Init->getBeginLoc(), Init->getEndLoc())
  4013. : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
  4014. InitRange.getEnd());
  4015. InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
  4016. ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
  4017. Args, nullptr);
  4018. if (!DelegationInit.isInvalid()) {
  4019. assert((DelegationInit.get()->containsErrors() ||
  4020. cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
  4021. "Delegating constructor with no target?");
  4022. // C++11 [class.base.init]p7:
  4023. // The initialization of each base and member constitutes a
  4024. // full-expression.
  4025. DelegationInit = ActOnFinishFullExpr(
  4026. DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
  4027. }
  4028. if (DelegationInit.isInvalid()) {
  4029. DelegationInit =
  4030. CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
  4031. QualType(ClassDecl->getTypeForDecl(), 0));
  4032. if (DelegationInit.isInvalid())
  4033. return true;
  4034. } else {
  4035. // If we are in a dependent context, template instantiation will
  4036. // perform this type-checking again. Just save the arguments that we
  4037. // received in a ParenListExpr.
  4038. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  4039. // of the information that we have about the base
  4040. // initializer. However, deconstructing the ASTs is a dicey process,
  4041. // and this approach is far more likely to get the corner cases right.
  4042. if (CurContext->isDependentContext())
  4043. DelegationInit = Init;
  4044. }
  4045. return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
  4046. DelegationInit.getAs<Expr>(),
  4047. InitRange.getEnd());
  4048. }
  4049. MemInitResult
  4050. Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
  4051. Expr *Init, CXXRecordDecl *ClassDecl,
  4052. SourceLocation EllipsisLoc) {
  4053. SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
  4054. if (!BaseType->isDependentType() && !BaseType->isRecordType())
  4055. return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
  4056. << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
  4057. // C++ [class.base.init]p2:
  4058. // [...] Unless the mem-initializer-id names a nonstatic data
  4059. // member of the constructor's class or a direct or virtual base
  4060. // of that class, the mem-initializer is ill-formed. A
  4061. // mem-initializer-list can initialize a base class using any
  4062. // name that denotes that base class type.
  4063. // We can store the initializers in "as-written" form and delay analysis until
  4064. // instantiation if the constructor is dependent. But not for dependent
  4065. // (broken) code in a non-template! SetCtorInitializers does not expect this.
  4066. bool Dependent = CurContext->isDependentContext() &&
  4067. (BaseType->isDependentType() || Init->isTypeDependent());
  4068. SourceRange InitRange = Init->getSourceRange();
  4069. if (EllipsisLoc.isValid()) {
  4070. // This is a pack expansion.
  4071. if (!BaseType->containsUnexpandedParameterPack()) {
  4072. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  4073. << SourceRange(BaseLoc, InitRange.getEnd());
  4074. EllipsisLoc = SourceLocation();
  4075. }
  4076. } else {
  4077. // Check for any unexpanded parameter packs.
  4078. if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
  4079. return true;
  4080. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  4081. return true;
  4082. }
  4083. // Check for direct and virtual base classes.
  4084. const CXXBaseSpecifier *DirectBaseSpec = nullptr;
  4085. const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
  4086. if (!Dependent) {
  4087. if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
  4088. BaseType))
  4089. return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
  4090. FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
  4091. VirtualBaseSpec);
  4092. // C++ [base.class.init]p2:
  4093. // Unless the mem-initializer-id names a nonstatic data member of the
  4094. // constructor's class or a direct or virtual base of that class, the
  4095. // mem-initializer is ill-formed.
  4096. if (!DirectBaseSpec && !VirtualBaseSpec) {
  4097. // If the class has any dependent bases, then it's possible that
  4098. // one of those types will resolve to the same type as
  4099. // BaseType. Therefore, just treat this as a dependent base
  4100. // class initialization. FIXME: Should we try to check the
  4101. // initialization anyway? It seems odd.
  4102. if (ClassDecl->hasAnyDependentBases())
  4103. Dependent = true;
  4104. else
  4105. return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
  4106. << BaseType << Context.getTypeDeclType(ClassDecl)
  4107. << BaseTInfo->getTypeLoc().getSourceRange();
  4108. }
  4109. }
  4110. if (Dependent) {
  4111. DiscardCleanupsInEvaluationContext();
  4112. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  4113. /*IsVirtual=*/false,
  4114. InitRange.getBegin(), Init,
  4115. InitRange.getEnd(), EllipsisLoc);
  4116. }
  4117. // C++ [base.class.init]p2:
  4118. // If a mem-initializer-id is ambiguous because it designates both
  4119. // a direct non-virtual base class and an inherited virtual base
  4120. // class, the mem-initializer is ill-formed.
  4121. if (DirectBaseSpec && VirtualBaseSpec)
  4122. return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
  4123. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  4124. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
  4125. if (!BaseSpec)
  4126. BaseSpec = VirtualBaseSpec;
  4127. // Initialize the base.
  4128. bool InitList = true;
  4129. MultiExprArg Args = Init;
  4130. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  4131. InitList = false;
  4132. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  4133. }
  4134. InitializedEntity BaseEntity =
  4135. InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
  4136. InitializationKind Kind =
  4137. InitList ? InitializationKind::CreateDirectList(BaseLoc)
  4138. : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
  4139. InitRange.getEnd());
  4140. InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
  4141. ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
  4142. if (!BaseInit.isInvalid()) {
  4143. // C++11 [class.base.init]p7:
  4144. // The initialization of each base and member constitutes a
  4145. // full-expression.
  4146. BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
  4147. /*DiscardedValue*/ false);
  4148. }
  4149. if (BaseInit.isInvalid()) {
  4150. BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
  4151. Args, BaseType);
  4152. if (BaseInit.isInvalid())
  4153. return true;
  4154. } else {
  4155. // If we are in a dependent context, template instantiation will
  4156. // perform this type-checking again. Just save the arguments that we
  4157. // received in a ParenListExpr.
  4158. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  4159. // of the information that we have about the base
  4160. // initializer. However, deconstructing the ASTs is a dicey process,
  4161. // and this approach is far more likely to get the corner cases right.
  4162. if (CurContext->isDependentContext())
  4163. BaseInit = Init;
  4164. }
  4165. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  4166. BaseSpec->isVirtual(),
  4167. InitRange.getBegin(),
  4168. BaseInit.getAs<Expr>(),
  4169. InitRange.getEnd(), EllipsisLoc);
  4170. }
  4171. // Create a static_cast\<T&&>(expr).
  4172. static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
  4173. QualType TargetType =
  4174. SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
  4175. SourceLocation(), DeclarationName());
  4176. SourceLocation ExprLoc = E->getBeginLoc();
  4177. TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
  4178. TargetType, ExprLoc);
  4179. return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  4180. SourceRange(ExprLoc, ExprLoc),
  4181. E->getSourceRange()).get();
  4182. }
  4183. /// ImplicitInitializerKind - How an implicit base or member initializer should
  4184. /// initialize its base or member.
  4185. enum ImplicitInitializerKind {
  4186. IIK_Default,
  4187. IIK_Copy,
  4188. IIK_Move,
  4189. IIK_Inherit
  4190. };
  4191. static bool
  4192. BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  4193. ImplicitInitializerKind ImplicitInitKind,
  4194. CXXBaseSpecifier *BaseSpec,
  4195. bool IsInheritedVirtualBase,
  4196. CXXCtorInitializer *&CXXBaseInit) {
  4197. InitializedEntity InitEntity
  4198. = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
  4199. IsInheritedVirtualBase);
  4200. ExprResult BaseInit;
  4201. switch (ImplicitInitKind) {
  4202. case IIK_Inherit:
  4203. case IIK_Default: {
  4204. InitializationKind InitKind
  4205. = InitializationKind::CreateDefault(Constructor->getLocation());
  4206. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
  4207. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
  4208. break;
  4209. }
  4210. case IIK_Move:
  4211. case IIK_Copy: {
  4212. bool Moving = ImplicitInitKind == IIK_Move;
  4213. ParmVarDecl *Param = Constructor->getParamDecl(0);
  4214. QualType ParamType = Param->getType().getNonReferenceType();
  4215. Expr *CopyCtorArg =
  4216. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  4217. SourceLocation(), Param, false,
  4218. Constructor->getLocation(), ParamType,
  4219. VK_LValue, nullptr);
  4220. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
  4221. // Cast to the base class to avoid ambiguities.
  4222. QualType ArgTy =
  4223. SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
  4224. ParamType.getQualifiers());
  4225. if (Moving) {
  4226. CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
  4227. }
  4228. CXXCastPath BasePath;
  4229. BasePath.push_back(BaseSpec);
  4230. CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
  4231. CK_UncheckedDerivedToBase,
  4232. Moving ? VK_XValue : VK_LValue,
  4233. &BasePath).get();
  4234. InitializationKind InitKind
  4235. = InitializationKind::CreateDirect(Constructor->getLocation(),
  4236. SourceLocation(), SourceLocation());
  4237. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
  4238. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
  4239. break;
  4240. }
  4241. }
  4242. BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
  4243. if (BaseInit.isInvalid())
  4244. return true;
  4245. CXXBaseInit =
  4246. new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4247. SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
  4248. SourceLocation()),
  4249. BaseSpec->isVirtual(),
  4250. SourceLocation(),
  4251. BaseInit.getAs<Expr>(),
  4252. SourceLocation(),
  4253. SourceLocation());
  4254. return false;
  4255. }
  4256. static bool RefersToRValueRef(Expr *MemRef) {
  4257. ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
  4258. return Referenced->getType()->isRValueReferenceType();
  4259. }
  4260. static bool
  4261. BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  4262. ImplicitInitializerKind ImplicitInitKind,
  4263. FieldDecl *Field, IndirectFieldDecl *Indirect,
  4264. CXXCtorInitializer *&CXXMemberInit) {
  4265. if (Field->isInvalidDecl())
  4266. return true;
  4267. SourceLocation Loc = Constructor->getLocation();
  4268. if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
  4269. bool Moving = ImplicitInitKind == IIK_Move;
  4270. ParmVarDecl *Param = Constructor->getParamDecl(0);
  4271. QualType ParamType = Param->getType().getNonReferenceType();
  4272. // Suppress copying zero-width bitfields.
  4273. if (Field->isZeroLengthBitField(SemaRef.Context))
  4274. return false;
  4275. Expr *MemberExprBase =
  4276. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  4277. SourceLocation(), Param, false,
  4278. Loc, ParamType, VK_LValue, nullptr);
  4279. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
  4280. if (Moving) {
  4281. MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
  4282. }
  4283. // Build a reference to this field within the parameter.
  4284. CXXScopeSpec SS;
  4285. LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
  4286. Sema::LookupMemberName);
  4287. MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
  4288. : cast<ValueDecl>(Field), AS_public);
  4289. MemberLookup.resolveKind();
  4290. ExprResult CtorArg
  4291. = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
  4292. ParamType, Loc,
  4293. /*IsArrow=*/false,
  4294. SS,
  4295. /*TemplateKWLoc=*/SourceLocation(),
  4296. /*FirstQualifierInScope=*/nullptr,
  4297. MemberLookup,
  4298. /*TemplateArgs=*/nullptr,
  4299. /*S*/nullptr);
  4300. if (CtorArg.isInvalid())
  4301. return true;
  4302. // C++11 [class.copy]p15:
  4303. // - if a member m has rvalue reference type T&&, it is direct-initialized
  4304. // with static_cast<T&&>(x.m);
  4305. if (RefersToRValueRef(CtorArg.get())) {
  4306. CtorArg = CastForMoving(SemaRef, CtorArg.get());
  4307. }
  4308. InitializedEntity Entity =
  4309. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  4310. /*Implicit*/ true)
  4311. : InitializedEntity::InitializeMember(Field, nullptr,
  4312. /*Implicit*/ true);
  4313. // Direct-initialize to use the copy constructor.
  4314. InitializationKind InitKind =
  4315. InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
  4316. Expr *CtorArgE = CtorArg.getAs<Expr>();
  4317. InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
  4318. ExprResult MemberInit =
  4319. InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
  4320. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  4321. if (MemberInit.isInvalid())
  4322. return true;
  4323. if (Indirect)
  4324. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  4325. SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  4326. else
  4327. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  4328. SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  4329. return false;
  4330. }
  4331. assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
  4332. "Unhandled implicit init kind!");
  4333. QualType FieldBaseElementType =
  4334. SemaRef.Context.getBaseElementType(Field->getType());
  4335. if (FieldBaseElementType->isRecordType()) {
  4336. InitializedEntity InitEntity =
  4337. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  4338. /*Implicit*/ true)
  4339. : InitializedEntity::InitializeMember(Field, nullptr,
  4340. /*Implicit*/ true);
  4341. InitializationKind InitKind =
  4342. InitializationKind::CreateDefault(Loc);
  4343. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
  4344. ExprResult MemberInit =
  4345. InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
  4346. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  4347. if (MemberInit.isInvalid())
  4348. return true;
  4349. if (Indirect)
  4350. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4351. Indirect, Loc,
  4352. Loc,
  4353. MemberInit.get(),
  4354. Loc);
  4355. else
  4356. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4357. Field, Loc, Loc,
  4358. MemberInit.get(),
  4359. Loc);
  4360. return false;
  4361. }
  4362. if (!Field->getParent()->isUnion()) {
  4363. if (FieldBaseElementType->isReferenceType()) {
  4364. SemaRef.Diag(Constructor->getLocation(),
  4365. diag::err_uninitialized_member_in_ctor)
  4366. << (int)Constructor->isImplicit()
  4367. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  4368. << 0 << Field->getDeclName();
  4369. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  4370. return true;
  4371. }
  4372. if (FieldBaseElementType.isConstQualified()) {
  4373. SemaRef.Diag(Constructor->getLocation(),
  4374. diag::err_uninitialized_member_in_ctor)
  4375. << (int)Constructor->isImplicit()
  4376. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  4377. << 1 << Field->getDeclName();
  4378. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  4379. return true;
  4380. }
  4381. }
  4382. if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
  4383. // ARC and Weak:
  4384. // Default-initialize Objective-C pointers to NULL.
  4385. CXXMemberInit
  4386. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
  4387. Loc, Loc,
  4388. new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
  4389. Loc);
  4390. return false;
  4391. }
  4392. // Nothing to initialize.
  4393. CXXMemberInit = nullptr;
  4394. return false;
  4395. }
  4396. namespace {
  4397. struct BaseAndFieldInfo {
  4398. Sema &S;
  4399. CXXConstructorDecl *Ctor;
  4400. bool AnyErrorsInInits;
  4401. ImplicitInitializerKind IIK;
  4402. llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
  4403. SmallVector<CXXCtorInitializer*, 8> AllToInit;
  4404. llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
  4405. BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
  4406. : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
  4407. bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
  4408. if (Ctor->getInheritedConstructor())
  4409. IIK = IIK_Inherit;
  4410. else if (Generated && Ctor->isCopyConstructor())
  4411. IIK = IIK_Copy;
  4412. else if (Generated && Ctor->isMoveConstructor())
  4413. IIK = IIK_Move;
  4414. else
  4415. IIK = IIK_Default;
  4416. }
  4417. bool isImplicitCopyOrMove() const {
  4418. switch (IIK) {
  4419. case IIK_Copy:
  4420. case IIK_Move:
  4421. return true;
  4422. case IIK_Default:
  4423. case IIK_Inherit:
  4424. return false;
  4425. }
  4426. llvm_unreachable("Invalid ImplicitInitializerKind!");
  4427. }
  4428. bool addFieldInitializer(CXXCtorInitializer *Init) {
  4429. AllToInit.push_back(Init);
  4430. // Check whether this initializer makes the field "used".
  4431. if (Init->getInit()->HasSideEffects(S.Context))
  4432. S.UnusedPrivateFields.remove(Init->getAnyMember());
  4433. return false;
  4434. }
  4435. bool isInactiveUnionMember(FieldDecl *Field) {
  4436. RecordDecl *Record = Field->getParent();
  4437. if (!Record->isUnion())
  4438. return false;
  4439. if (FieldDecl *Active =
  4440. ActiveUnionMember.lookup(Record->getCanonicalDecl()))
  4441. return Active != Field->getCanonicalDecl();
  4442. // In an implicit copy or move constructor, ignore any in-class initializer.
  4443. if (isImplicitCopyOrMove())
  4444. return true;
  4445. // If there's no explicit initialization, the field is active only if it
  4446. // has an in-class initializer...
  4447. if (Field->hasInClassInitializer())
  4448. return false;
  4449. // ... or it's an anonymous struct or union whose class has an in-class
  4450. // initializer.
  4451. if (!Field->isAnonymousStructOrUnion())
  4452. return true;
  4453. CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
  4454. return !FieldRD->hasInClassInitializer();
  4455. }
  4456. /// Determine whether the given field is, or is within, a union member
  4457. /// that is inactive (because there was an initializer given for a different
  4458. /// member of the union, or because the union was not initialized at all).
  4459. bool isWithinInactiveUnionMember(FieldDecl *Field,
  4460. IndirectFieldDecl *Indirect) {
  4461. if (!Indirect)
  4462. return isInactiveUnionMember(Field);
  4463. for (auto *C : Indirect->chain()) {
  4464. FieldDecl *Field = dyn_cast<FieldDecl>(C);
  4465. if (Field && isInactiveUnionMember(Field))
  4466. return true;
  4467. }
  4468. return false;
  4469. }
  4470. };
  4471. }
  4472. /// Determine whether the given type is an incomplete or zero-lenfgth
  4473. /// array type.
  4474. static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
  4475. if (T->isIncompleteArrayType())
  4476. return true;
  4477. while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
  4478. if (!ArrayT->getSize())
  4479. return true;
  4480. T = ArrayT->getElementType();
  4481. }
  4482. return false;
  4483. }
  4484. static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
  4485. FieldDecl *Field,
  4486. IndirectFieldDecl *Indirect = nullptr) {
  4487. if (Field->isInvalidDecl())
  4488. return false;
  4489. // Overwhelmingly common case: we have a direct initializer for this field.
  4490. if (CXXCtorInitializer *Init =
  4491. Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
  4492. return Info.addFieldInitializer(Init);
  4493. // C++11 [class.base.init]p8:
  4494. // if the entity is a non-static data member that has a
  4495. // brace-or-equal-initializer and either
  4496. // -- the constructor's class is a union and no other variant member of that
  4497. // union is designated by a mem-initializer-id or
  4498. // -- the constructor's class is not a union, and, if the entity is a member
  4499. // of an anonymous union, no other member of that union is designated by
  4500. // a mem-initializer-id,
  4501. // the entity is initialized as specified in [dcl.init].
  4502. //
  4503. // We also apply the same rules to handle anonymous structs within anonymous
  4504. // unions.
  4505. if (Info.isWithinInactiveUnionMember(Field, Indirect))
  4506. return false;
  4507. if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
  4508. ExprResult DIE =
  4509. SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
  4510. if (DIE.isInvalid())
  4511. return true;
  4512. auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
  4513. SemaRef.checkInitializerLifetime(Entity, DIE.get());
  4514. CXXCtorInitializer *Init;
  4515. if (Indirect)
  4516. Init = new (SemaRef.Context)
  4517. CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
  4518. SourceLocation(), DIE.get(), SourceLocation());
  4519. else
  4520. Init = new (SemaRef.Context)
  4521. CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
  4522. SourceLocation(), DIE.get(), SourceLocation());
  4523. return Info.addFieldInitializer(Init);
  4524. }
  4525. // Don't initialize incomplete or zero-length arrays.
  4526. if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
  4527. return false;
  4528. // Don't try to build an implicit initializer if there were semantic
  4529. // errors in any of the initializers (and therefore we might be
  4530. // missing some that the user actually wrote).
  4531. if (Info.AnyErrorsInInits)
  4532. return false;
  4533. CXXCtorInitializer *Init = nullptr;
  4534. if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
  4535. Indirect, Init))
  4536. return true;
  4537. if (!Init)
  4538. return false;
  4539. return Info.addFieldInitializer(Init);
  4540. }
  4541. bool
  4542. Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
  4543. CXXCtorInitializer *Initializer) {
  4544. assert(Initializer->isDelegatingInitializer());
  4545. Constructor->setNumCtorInitializers(1);
  4546. CXXCtorInitializer **initializer =
  4547. new (Context) CXXCtorInitializer*[1];
  4548. memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
  4549. Constructor->setCtorInitializers(initializer);
  4550. if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
  4551. MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
  4552. DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
  4553. }
  4554. DelegatingCtorDecls.push_back(Constructor);
  4555. DiagnoseUninitializedFields(*this, Constructor);
  4556. return false;
  4557. }
  4558. bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
  4559. ArrayRef<CXXCtorInitializer *> Initializers) {
  4560. if (Constructor->isDependentContext()) {
  4561. // Just store the initializers as written, they will be checked during
  4562. // instantiation.
  4563. if (!Initializers.empty()) {
  4564. Constructor->setNumCtorInitializers(Initializers.size());
  4565. CXXCtorInitializer **baseOrMemberInitializers =
  4566. new (Context) CXXCtorInitializer*[Initializers.size()];
  4567. memcpy(baseOrMemberInitializers, Initializers.data(),
  4568. Initializers.size() * sizeof(CXXCtorInitializer*));
  4569. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4570. }
  4571. // Let template instantiation know whether we had errors.
  4572. if (AnyErrors)
  4573. Constructor->setInvalidDecl();
  4574. return false;
  4575. }
  4576. BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
  4577. // We need to build the initializer AST according to order of construction
  4578. // and not what user specified in the Initializers list.
  4579. CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
  4580. if (!ClassDecl)
  4581. return true;
  4582. bool HadError = false;
  4583. for (unsigned i = 0; i < Initializers.size(); i++) {
  4584. CXXCtorInitializer *Member = Initializers[i];
  4585. if (Member->isBaseInitializer())
  4586. Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
  4587. else {
  4588. Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
  4589. if (IndirectFieldDecl *F = Member->getIndirectMember()) {
  4590. for (auto *C : F->chain()) {
  4591. FieldDecl *FD = dyn_cast<FieldDecl>(C);
  4592. if (FD && FD->getParent()->isUnion())
  4593. Info.ActiveUnionMember.insert(std::make_pair(
  4594. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4595. }
  4596. } else if (FieldDecl *FD = Member->getMember()) {
  4597. if (FD->getParent()->isUnion())
  4598. Info.ActiveUnionMember.insert(std::make_pair(
  4599. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4600. }
  4601. }
  4602. }
  4603. // Keep track of the direct virtual bases.
  4604. llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
  4605. for (auto &I : ClassDecl->bases()) {
  4606. if (I.isVirtual())
  4607. DirectVBases.insert(&I);
  4608. }
  4609. // Push virtual bases before others.
  4610. for (auto &VBase : ClassDecl->vbases()) {
  4611. if (CXXCtorInitializer *Value
  4612. = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
  4613. // [class.base.init]p7, per DR257:
  4614. // A mem-initializer where the mem-initializer-id names a virtual base
  4615. // class is ignored during execution of a constructor of any class that
  4616. // is not the most derived class.
  4617. if (ClassDecl->isAbstract()) {
  4618. // FIXME: Provide a fixit to remove the base specifier. This requires
  4619. // tracking the location of the associated comma for a base specifier.
  4620. Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
  4621. << VBase.getType() << ClassDecl;
  4622. DiagnoseAbstractType(ClassDecl);
  4623. }
  4624. Info.AllToInit.push_back(Value);
  4625. } else if (!AnyErrors && !ClassDecl->isAbstract()) {
  4626. // [class.base.init]p8, per DR257:
  4627. // If a given [...] base class is not named by a mem-initializer-id
  4628. // [...] and the entity is not a virtual base class of an abstract
  4629. // class, then [...] the entity is default-initialized.
  4630. bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
  4631. CXXCtorInitializer *CXXBaseInit;
  4632. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4633. &VBase, IsInheritedVirtualBase,
  4634. CXXBaseInit)) {
  4635. HadError = true;
  4636. continue;
  4637. }
  4638. Info.AllToInit.push_back(CXXBaseInit);
  4639. }
  4640. }
  4641. // Non-virtual bases.
  4642. for (auto &Base : ClassDecl->bases()) {
  4643. // Virtuals are in the virtual base list and already constructed.
  4644. if (Base.isVirtual())
  4645. continue;
  4646. if (CXXCtorInitializer *Value
  4647. = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
  4648. Info.AllToInit.push_back(Value);
  4649. } else if (!AnyErrors) {
  4650. CXXCtorInitializer *CXXBaseInit;
  4651. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4652. &Base, /*IsInheritedVirtualBase=*/false,
  4653. CXXBaseInit)) {
  4654. HadError = true;
  4655. continue;
  4656. }
  4657. Info.AllToInit.push_back(CXXBaseInit);
  4658. }
  4659. }
  4660. // Fields.
  4661. for (auto *Mem : ClassDecl->decls()) {
  4662. if (auto *F = dyn_cast<FieldDecl>(Mem)) {
  4663. // C++ [class.bit]p2:
  4664. // A declaration for a bit-field that omits the identifier declares an
  4665. // unnamed bit-field. Unnamed bit-fields are not members and cannot be
  4666. // initialized.
  4667. if (F->isUnnamedBitfield())
  4668. continue;
  4669. // If we're not generating the implicit copy/move constructor, then we'll
  4670. // handle anonymous struct/union fields based on their individual
  4671. // indirect fields.
  4672. if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
  4673. continue;
  4674. if (CollectFieldInitializer(*this, Info, F))
  4675. HadError = true;
  4676. continue;
  4677. }
  4678. // Beyond this point, we only consider default initialization.
  4679. if (Info.isImplicitCopyOrMove())
  4680. continue;
  4681. if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
  4682. if (F->getType()->isIncompleteArrayType()) {
  4683. assert(ClassDecl->hasFlexibleArrayMember() &&
  4684. "Incomplete array type is not valid");
  4685. continue;
  4686. }
  4687. // Initialize each field of an anonymous struct individually.
  4688. if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
  4689. HadError = true;
  4690. continue;
  4691. }
  4692. }
  4693. unsigned NumInitializers = Info.AllToInit.size();
  4694. if (NumInitializers > 0) {
  4695. Constructor->setNumCtorInitializers(NumInitializers);
  4696. CXXCtorInitializer **baseOrMemberInitializers =
  4697. new (Context) CXXCtorInitializer*[NumInitializers];
  4698. memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
  4699. NumInitializers * sizeof(CXXCtorInitializer*));
  4700. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4701. // Constructors implicitly reference the base and member
  4702. // destructors.
  4703. MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
  4704. Constructor->getParent());
  4705. }
  4706. return HadError;
  4707. }
  4708. static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
  4709. if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
  4710. const RecordDecl *RD = RT->getDecl();
  4711. if (RD->isAnonymousStructOrUnion()) {
  4712. for (auto *Field : RD->fields())
  4713. PopulateKeysForFields(Field, IdealInits);
  4714. return;
  4715. }
  4716. }
  4717. IdealInits.push_back(Field->getCanonicalDecl());
  4718. }
  4719. static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
  4720. return Context.getCanonicalType(BaseType).getTypePtr();
  4721. }
  4722. static const void *GetKeyForMember(ASTContext &Context,
  4723. CXXCtorInitializer *Member) {
  4724. if (!Member->isAnyMemberInitializer())
  4725. return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
  4726. return Member->getAnyMember()->getCanonicalDecl();
  4727. }
  4728. static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
  4729. const CXXCtorInitializer *Previous,
  4730. const CXXCtorInitializer *Current) {
  4731. if (Previous->isAnyMemberInitializer())
  4732. Diag << 0 << Previous->getAnyMember();
  4733. else
  4734. Diag << 1 << Previous->getTypeSourceInfo()->getType();
  4735. if (Current->isAnyMemberInitializer())
  4736. Diag << 0 << Current->getAnyMember();
  4737. else
  4738. Diag << 1 << Current->getTypeSourceInfo()->getType();
  4739. }
  4740. static void DiagnoseBaseOrMemInitializerOrder(
  4741. Sema &SemaRef, const CXXConstructorDecl *Constructor,
  4742. ArrayRef<CXXCtorInitializer *> Inits) {
  4743. if (Constructor->getDeclContext()->isDependentContext())
  4744. return;
  4745. // Don't check initializers order unless the warning is enabled at the
  4746. // location of at least one initializer.
  4747. bool ShouldCheckOrder = false;
  4748. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4749. CXXCtorInitializer *Init = Inits[InitIndex];
  4750. if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
  4751. Init->getSourceLocation())) {
  4752. ShouldCheckOrder = true;
  4753. break;
  4754. }
  4755. }
  4756. if (!ShouldCheckOrder)
  4757. return;
  4758. // Build the list of bases and members in the order that they'll
  4759. // actually be initialized. The explicit initializers should be in
  4760. // this same order but may be missing things.
  4761. SmallVector<const void*, 32> IdealInitKeys;
  4762. const CXXRecordDecl *ClassDecl = Constructor->getParent();
  4763. // 1. Virtual bases.
  4764. for (const auto &VBase : ClassDecl->vbases())
  4765. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
  4766. // 2. Non-virtual bases.
  4767. for (const auto &Base : ClassDecl->bases()) {
  4768. if (Base.isVirtual())
  4769. continue;
  4770. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
  4771. }
  4772. // 3. Direct fields.
  4773. for (auto *Field : ClassDecl->fields()) {
  4774. if (Field->isUnnamedBitfield())
  4775. continue;
  4776. PopulateKeysForFields(Field, IdealInitKeys);
  4777. }
  4778. unsigned NumIdealInits = IdealInitKeys.size();
  4779. unsigned IdealIndex = 0;
  4780. // Track initializers that are in an incorrect order for either a warning or
  4781. // note if multiple ones occur.
  4782. SmallVector<unsigned> WarnIndexes;
  4783. // Correlates the index of an initializer in the init-list to the index of
  4784. // the field/base in the class.
  4785. SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
  4786. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4787. const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
  4788. // Scan forward to try to find this initializer in the idealized
  4789. // initializers list.
  4790. for (; IdealIndex != NumIdealInits; ++IdealIndex)
  4791. if (InitKey == IdealInitKeys[IdealIndex])
  4792. break;
  4793. // If we didn't find this initializer, it must be because we
  4794. // scanned past it on a previous iteration. That can only
  4795. // happen if we're out of order; emit a warning.
  4796. if (IdealIndex == NumIdealInits && InitIndex) {
  4797. WarnIndexes.push_back(InitIndex);
  4798. // Move back to the initializer's location in the ideal list.
  4799. for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
  4800. if (InitKey == IdealInitKeys[IdealIndex])
  4801. break;
  4802. assert(IdealIndex < NumIdealInits &&
  4803. "initializer not found in initializer list");
  4804. }
  4805. CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
  4806. }
  4807. if (WarnIndexes.empty())
  4808. return;
  4809. // Sort based on the ideal order, first in the pair.
  4810. llvm::sort(CorrelatedInitOrder, llvm::less_first());
  4811. // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
  4812. // emit the diagnostic before we can try adding notes.
  4813. {
  4814. Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
  4815. Inits[WarnIndexes.front() - 1]->getSourceLocation(),
  4816. WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
  4817. : diag::warn_some_initializers_out_of_order);
  4818. for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
  4819. if (CorrelatedInitOrder[I].second == I)
  4820. continue;
  4821. // Ideally we would be using InsertFromRange here, but clang doesn't
  4822. // appear to handle InsertFromRange correctly when the source range is
  4823. // modified by another fix-it.
  4824. D << FixItHint::CreateReplacement(
  4825. Inits[I]->getSourceRange(),
  4826. Lexer::getSourceText(
  4827. CharSourceRange::getTokenRange(
  4828. Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
  4829. SemaRef.getSourceManager(), SemaRef.getLangOpts()));
  4830. }
  4831. // If there is only 1 item out of order, the warning expects the name and
  4832. // type of each being added to it.
  4833. if (WarnIndexes.size() == 1) {
  4834. AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
  4835. Inits[WarnIndexes.front()]);
  4836. return;
  4837. }
  4838. }
  4839. // More than 1 item to warn, create notes letting the user know which ones
  4840. // are bad.
  4841. for (unsigned WarnIndex : WarnIndexes) {
  4842. const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
  4843. auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
  4844. diag::note_initializer_out_of_order);
  4845. AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
  4846. D << PrevInit->getSourceRange();
  4847. }
  4848. }
  4849. namespace {
  4850. bool CheckRedundantInit(Sema &S,
  4851. CXXCtorInitializer *Init,
  4852. CXXCtorInitializer *&PrevInit) {
  4853. if (!PrevInit) {
  4854. PrevInit = Init;
  4855. return false;
  4856. }
  4857. if (FieldDecl *Field = Init->getAnyMember())
  4858. S.Diag(Init->getSourceLocation(),
  4859. diag::err_multiple_mem_initialization)
  4860. << Field->getDeclName()
  4861. << Init->getSourceRange();
  4862. else {
  4863. const Type *BaseClass = Init->getBaseClass();
  4864. assert(BaseClass && "neither field nor base");
  4865. S.Diag(Init->getSourceLocation(),
  4866. diag::err_multiple_base_initialization)
  4867. << QualType(BaseClass, 0)
  4868. << Init->getSourceRange();
  4869. }
  4870. S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
  4871. << 0 << PrevInit->getSourceRange();
  4872. return true;
  4873. }
  4874. typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
  4875. typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
  4876. bool CheckRedundantUnionInit(Sema &S,
  4877. CXXCtorInitializer *Init,
  4878. RedundantUnionMap &Unions) {
  4879. FieldDecl *Field = Init->getAnyMember();
  4880. RecordDecl *Parent = Field->getParent();
  4881. NamedDecl *Child = Field;
  4882. while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
  4883. if (Parent->isUnion()) {
  4884. UnionEntry &En = Unions[Parent];
  4885. if (En.first && En.first != Child) {
  4886. S.Diag(Init->getSourceLocation(),
  4887. diag::err_multiple_mem_union_initialization)
  4888. << Field->getDeclName()
  4889. << Init->getSourceRange();
  4890. S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
  4891. << 0 << En.second->getSourceRange();
  4892. return true;
  4893. }
  4894. if (!En.first) {
  4895. En.first = Child;
  4896. En.second = Init;
  4897. }
  4898. if (!Parent->isAnonymousStructOrUnion())
  4899. return false;
  4900. }
  4901. Child = Parent;
  4902. Parent = cast<RecordDecl>(Parent->getDeclContext());
  4903. }
  4904. return false;
  4905. }
  4906. } // namespace
  4907. /// ActOnMemInitializers - Handle the member initializers for a constructor.
  4908. void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
  4909. SourceLocation ColonLoc,
  4910. ArrayRef<CXXCtorInitializer*> MemInits,
  4911. bool AnyErrors) {
  4912. if (!ConstructorDecl)
  4913. return;
  4914. AdjustDeclIfTemplate(ConstructorDecl);
  4915. CXXConstructorDecl *Constructor
  4916. = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
  4917. if (!Constructor) {
  4918. Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
  4919. return;
  4920. }
  4921. // Mapping for the duplicate initializers check.
  4922. // For member initializers, this is keyed with a FieldDecl*.
  4923. // For base initializers, this is keyed with a Type*.
  4924. llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
  4925. // Mapping for the inconsistent anonymous-union initializers check.
  4926. RedundantUnionMap MemberUnions;
  4927. bool HadError = false;
  4928. for (unsigned i = 0; i < MemInits.size(); i++) {
  4929. CXXCtorInitializer *Init = MemInits[i];
  4930. // Set the source order index.
  4931. Init->setSourceOrder(i);
  4932. if (Init->isAnyMemberInitializer()) {
  4933. const void *Key = GetKeyForMember(Context, Init);
  4934. if (CheckRedundantInit(*this, Init, Members[Key]) ||
  4935. CheckRedundantUnionInit(*this, Init, MemberUnions))
  4936. HadError = true;
  4937. } else if (Init->isBaseInitializer()) {
  4938. const void *Key = GetKeyForMember(Context, Init);
  4939. if (CheckRedundantInit(*this, Init, Members[Key]))
  4940. HadError = true;
  4941. } else {
  4942. assert(Init->isDelegatingInitializer());
  4943. // This must be the only initializer
  4944. if (MemInits.size() != 1) {
  4945. Diag(Init->getSourceLocation(),
  4946. diag::err_delegating_initializer_alone)
  4947. << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
  4948. // We will treat this as being the only initializer.
  4949. }
  4950. SetDelegatingInitializer(Constructor, MemInits[i]);
  4951. // Return immediately as the initializer is set.
  4952. return;
  4953. }
  4954. }
  4955. if (HadError)
  4956. return;
  4957. DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
  4958. SetCtorInitializers(Constructor, AnyErrors, MemInits);
  4959. DiagnoseUninitializedFields(*this, Constructor);
  4960. }
  4961. void
  4962. Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
  4963. CXXRecordDecl *ClassDecl) {
  4964. // Ignore dependent contexts. Also ignore unions, since their members never
  4965. // have destructors implicitly called.
  4966. if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
  4967. return;
  4968. // FIXME: all the access-control diagnostics are positioned on the
  4969. // field/base declaration. That's probably good; that said, the
  4970. // user might reasonably want to know why the destructor is being
  4971. // emitted, and we currently don't say.
  4972. // Non-static data members.
  4973. for (auto *Field : ClassDecl->fields()) {
  4974. if (Field->isInvalidDecl())
  4975. continue;
  4976. // Don't destroy incomplete or zero-length arrays.
  4977. if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
  4978. continue;
  4979. QualType FieldType = Context.getBaseElementType(Field->getType());
  4980. const RecordType* RT = FieldType->getAs<RecordType>();
  4981. if (!RT)
  4982. continue;
  4983. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4984. if (FieldClassDecl->isInvalidDecl())
  4985. continue;
  4986. if (FieldClassDecl->hasIrrelevantDestructor())
  4987. continue;
  4988. // The destructor for an implicit anonymous union member is never invoked.
  4989. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  4990. continue;
  4991. CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
  4992. // Dtor might still be missing, e.g because it's invalid.
  4993. if (!Dtor)
  4994. continue;
  4995. CheckDestructorAccess(Field->getLocation(), Dtor,
  4996. PDiag(diag::err_access_dtor_field)
  4997. << Field->getDeclName()
  4998. << FieldType);
  4999. MarkFunctionReferenced(Location, Dtor);
  5000. DiagnoseUseOfDecl(Dtor, Location);
  5001. }
  5002. // We only potentially invoke the destructors of potentially constructed
  5003. // subobjects.
  5004. bool VisitVirtualBases = !ClassDecl->isAbstract();
  5005. // If the destructor exists and has already been marked used in the MS ABI,
  5006. // then virtual base destructors have already been checked and marked used.
  5007. // Skip checking them again to avoid duplicate diagnostics.
  5008. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  5009. CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
  5010. if (Dtor && Dtor->isUsed())
  5011. VisitVirtualBases = false;
  5012. }
  5013. llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
  5014. // Bases.
  5015. for (const auto &Base : ClassDecl->bases()) {
  5016. const RecordType *RT = Base.getType()->getAs<RecordType>();
  5017. if (!RT)
  5018. continue;
  5019. // Remember direct virtual bases.
  5020. if (Base.isVirtual()) {
  5021. if (!VisitVirtualBases)
  5022. continue;
  5023. DirectVirtualBases.insert(RT);
  5024. }
  5025. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  5026. // If our base class is invalid, we probably can't get its dtor anyway.
  5027. if (BaseClassDecl->isInvalidDecl())
  5028. continue;
  5029. if (BaseClassDecl->hasIrrelevantDestructor())
  5030. continue;
  5031. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  5032. // Dtor might still be missing, e.g because it's invalid.
  5033. if (!Dtor)
  5034. continue;
  5035. // FIXME: caret should be on the start of the class name
  5036. CheckDestructorAccess(Base.getBeginLoc(), Dtor,
  5037. PDiag(diag::err_access_dtor_base)
  5038. << Base.getType() << Base.getSourceRange(),
  5039. Context.getTypeDeclType(ClassDecl));
  5040. MarkFunctionReferenced(Location, Dtor);
  5041. DiagnoseUseOfDecl(Dtor, Location);
  5042. }
  5043. if (VisitVirtualBases)
  5044. MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
  5045. &DirectVirtualBases);
  5046. }
  5047. void Sema::MarkVirtualBaseDestructorsReferenced(
  5048. SourceLocation Location, CXXRecordDecl *ClassDecl,
  5049. llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
  5050. // Virtual bases.
  5051. for (const auto &VBase : ClassDecl->vbases()) {
  5052. // Bases are always records in a well-formed non-dependent class.
  5053. const RecordType *RT = VBase.getType()->castAs<RecordType>();
  5054. // Ignore already visited direct virtual bases.
  5055. if (DirectVirtualBases && DirectVirtualBases->count(RT))
  5056. continue;
  5057. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  5058. // If our base class is invalid, we probably can't get its dtor anyway.
  5059. if (BaseClassDecl->isInvalidDecl())
  5060. continue;
  5061. if (BaseClassDecl->hasIrrelevantDestructor())
  5062. continue;
  5063. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  5064. // Dtor might still be missing, e.g because it's invalid.
  5065. if (!Dtor)
  5066. continue;
  5067. if (CheckDestructorAccess(
  5068. ClassDecl->getLocation(), Dtor,
  5069. PDiag(diag::err_access_dtor_vbase)
  5070. << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
  5071. Context.getTypeDeclType(ClassDecl)) ==
  5072. AR_accessible) {
  5073. CheckDerivedToBaseConversion(
  5074. Context.getTypeDeclType(ClassDecl), VBase.getType(),
  5075. diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
  5076. SourceRange(), DeclarationName(), nullptr);
  5077. }
  5078. MarkFunctionReferenced(Location, Dtor);
  5079. DiagnoseUseOfDecl(Dtor, Location);
  5080. }
  5081. }
  5082. void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
  5083. if (!CDtorDecl)
  5084. return;
  5085. if (CXXConstructorDecl *Constructor
  5086. = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
  5087. SetCtorInitializers(Constructor, /*AnyErrors=*/false);
  5088. DiagnoseUninitializedFields(*this, Constructor);
  5089. }
  5090. }
  5091. bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
  5092. if (!getLangOpts().CPlusPlus)
  5093. return false;
  5094. const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
  5095. if (!RD)
  5096. return false;
  5097. // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
  5098. // class template specialization here, but doing so breaks a lot of code.
  5099. // We can't answer whether something is abstract until it has a
  5100. // definition. If it's currently being defined, we'll walk back
  5101. // over all the declarations when we have a full definition.
  5102. const CXXRecordDecl *Def = RD->getDefinition();
  5103. if (!Def || Def->isBeingDefined())
  5104. return false;
  5105. return RD->isAbstract();
  5106. }
  5107. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  5108. TypeDiagnoser &Diagnoser) {
  5109. if (!isAbstractType(Loc, T))
  5110. return false;
  5111. T = Context.getBaseElementType(T);
  5112. Diagnoser.diagnose(*this, Loc, T);
  5113. DiagnoseAbstractType(T->getAsCXXRecordDecl());
  5114. return true;
  5115. }
  5116. void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
  5117. // Check if we've already emitted the list of pure virtual functions
  5118. // for this class.
  5119. if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
  5120. return;
  5121. // If the diagnostic is suppressed, don't emit the notes. We're only
  5122. // going to emit them once, so try to attach them to a diagnostic we're
  5123. // actually going to show.
  5124. if (Diags.isLastDiagnosticIgnored())
  5125. return;
  5126. CXXFinalOverriderMap FinalOverriders;
  5127. RD->getFinalOverriders(FinalOverriders);
  5128. // Keep a set of seen pure methods so we won't diagnose the same method
  5129. // more than once.
  5130. llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
  5131. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  5132. MEnd = FinalOverriders.end();
  5133. M != MEnd;
  5134. ++M) {
  5135. for (OverridingMethods::iterator SO = M->second.begin(),
  5136. SOEnd = M->second.end();
  5137. SO != SOEnd; ++SO) {
  5138. // C++ [class.abstract]p4:
  5139. // A class is abstract if it contains or inherits at least one
  5140. // pure virtual function for which the final overrider is pure
  5141. // virtual.
  5142. //
  5143. if (SO->second.size() != 1)
  5144. continue;
  5145. if (!SO->second.front().Method->isPure())
  5146. continue;
  5147. if (!SeenPureMethods.insert(SO->second.front().Method).second)
  5148. continue;
  5149. Diag(SO->second.front().Method->getLocation(),
  5150. diag::note_pure_virtual_function)
  5151. << SO->second.front().Method->getDeclName() << RD->getDeclName();
  5152. }
  5153. }
  5154. if (!PureVirtualClassDiagSet)
  5155. PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
  5156. PureVirtualClassDiagSet->insert(RD);
  5157. }
  5158. namespace {
  5159. struct AbstractUsageInfo {
  5160. Sema &S;
  5161. CXXRecordDecl *Record;
  5162. CanQualType AbstractType;
  5163. bool Invalid;
  5164. AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
  5165. : S(S), Record(Record),
  5166. AbstractType(S.Context.getCanonicalType(
  5167. S.Context.getTypeDeclType(Record))),
  5168. Invalid(false) {}
  5169. void DiagnoseAbstractType() {
  5170. if (Invalid) return;
  5171. S.DiagnoseAbstractType(Record);
  5172. Invalid = true;
  5173. }
  5174. void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
  5175. };
  5176. struct CheckAbstractUsage {
  5177. AbstractUsageInfo &Info;
  5178. const NamedDecl *Ctx;
  5179. CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
  5180. : Info(Info), Ctx(Ctx) {}
  5181. void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  5182. switch (TL.getTypeLocClass()) {
  5183. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  5184. #define TYPELOC(CLASS, PARENT) \
  5185. case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
  5186. #include "clang/AST/TypeLocNodes.def"
  5187. }
  5188. }
  5189. void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  5190. Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
  5191. for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
  5192. if (!TL.getParam(I))
  5193. continue;
  5194. TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
  5195. if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
  5196. }
  5197. }
  5198. void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  5199. Visit(TL.getElementLoc(), Sema::AbstractArrayType);
  5200. }
  5201. void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  5202. // Visit the type parameters from a permissive context.
  5203. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
  5204. TemplateArgumentLoc TAL = TL.getArgLoc(I);
  5205. if (TAL.getArgument().getKind() == TemplateArgument::Type)
  5206. if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
  5207. Visit(TSI->getTypeLoc(), Sema::AbstractNone);
  5208. // TODO: other template argument types?
  5209. }
  5210. }
  5211. // Visit pointee types from a permissive context.
  5212. #define CheckPolymorphic(Type) \
  5213. void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
  5214. Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
  5215. }
  5216. CheckPolymorphic(PointerTypeLoc)
  5217. CheckPolymorphic(ReferenceTypeLoc)
  5218. CheckPolymorphic(MemberPointerTypeLoc)
  5219. CheckPolymorphic(BlockPointerTypeLoc)
  5220. CheckPolymorphic(AtomicTypeLoc)
  5221. /// Handle all the types we haven't given a more specific
  5222. /// implementation for above.
  5223. void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  5224. // Every other kind of type that we haven't called out already
  5225. // that has an inner type is either (1) sugar or (2) contains that
  5226. // inner type in some way as a subobject.
  5227. if (TypeLoc Next = TL.getNextTypeLoc())
  5228. return Visit(Next, Sel);
  5229. // If there's no inner type and we're in a permissive context,
  5230. // don't diagnose.
  5231. if (Sel == Sema::AbstractNone) return;
  5232. // Check whether the type matches the abstract type.
  5233. QualType T = TL.getType();
  5234. if (T->isArrayType()) {
  5235. Sel = Sema::AbstractArrayType;
  5236. T = Info.S.Context.getBaseElementType(T);
  5237. }
  5238. CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
  5239. if (CT != Info.AbstractType) return;
  5240. // It matched; do some magic.
  5241. // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
  5242. if (Sel == Sema::AbstractArrayType) {
  5243. Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
  5244. << T << TL.getSourceRange();
  5245. } else {
  5246. Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
  5247. << Sel << T << TL.getSourceRange();
  5248. }
  5249. Info.DiagnoseAbstractType();
  5250. }
  5251. };
  5252. void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
  5253. Sema::AbstractDiagSelID Sel) {
  5254. CheckAbstractUsage(*this, D).Visit(TL, Sel);
  5255. }
  5256. }
  5257. /// Check for invalid uses of an abstract type in a function declaration.
  5258. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  5259. FunctionDecl *FD) {
  5260. // No need to do the check on definitions, which require that
  5261. // the return/param types be complete.
  5262. if (FD->doesThisDeclarationHaveABody())
  5263. return;
  5264. // For safety's sake, just ignore it if we don't have type source
  5265. // information. This should never happen for non-implicit methods,
  5266. // but...
  5267. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  5268. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
  5269. }
  5270. /// Check for invalid uses of an abstract type in a variable0 declaration.
  5271. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  5272. VarDecl *VD) {
  5273. // No need to do the check on definitions, which require that
  5274. // the type is complete.
  5275. if (VD->isThisDeclarationADefinition())
  5276. return;
  5277. Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
  5278. Sema::AbstractVariableType);
  5279. }
  5280. /// Check for invalid uses of an abstract type within a class definition.
  5281. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  5282. CXXRecordDecl *RD) {
  5283. for (auto *D : RD->decls()) {
  5284. if (D->isImplicit()) continue;
  5285. // Step through friends to the befriended declaration.
  5286. if (auto *FD = dyn_cast<FriendDecl>(D)) {
  5287. D = FD->getFriendDecl();
  5288. if (!D) continue;
  5289. }
  5290. // Functions and function templates.
  5291. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  5292. CheckAbstractClassUsage(Info, FD);
  5293. } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
  5294. CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
  5295. // Fields and static variables.
  5296. } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
  5297. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  5298. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
  5299. } else if (auto *VD = dyn_cast<VarDecl>(D)) {
  5300. CheckAbstractClassUsage(Info, VD);
  5301. } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
  5302. CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
  5303. // Nested classes and class templates.
  5304. } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  5305. CheckAbstractClassUsage(Info, RD);
  5306. } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
  5307. CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
  5308. }
  5309. }
  5310. }
  5311. static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
  5312. Attr *ClassAttr = getDLLAttr(Class);
  5313. if (!ClassAttr)
  5314. return;
  5315. assert(ClassAttr->getKind() == attr::DLLExport);
  5316. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  5317. if (TSK == TSK_ExplicitInstantiationDeclaration)
  5318. // Don't go any further if this is just an explicit instantiation
  5319. // declaration.
  5320. return;
  5321. // Add a context note to explain how we got to any diagnostics produced below.
  5322. struct MarkingClassDllexported {
  5323. Sema &S;
  5324. MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
  5325. SourceLocation AttrLoc)
  5326. : S(S) {
  5327. Sema::CodeSynthesisContext Ctx;
  5328. Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
  5329. Ctx.PointOfInstantiation = AttrLoc;
  5330. Ctx.Entity = Class;
  5331. S.pushCodeSynthesisContext(Ctx);
  5332. }
  5333. ~MarkingClassDllexported() {
  5334. S.popCodeSynthesisContext();
  5335. }
  5336. } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
  5337. if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
  5338. S.MarkVTableUsed(Class->getLocation(), Class, true);
  5339. for (Decl *Member : Class->decls()) {
  5340. // Skip members that were not marked exported.
  5341. if (!Member->hasAttr<DLLExportAttr>())
  5342. continue;
  5343. // Defined static variables that are members of an exported base
  5344. // class must be marked export too.
  5345. auto *VD = dyn_cast<VarDecl>(Member);
  5346. if (VD && VD->getStorageClass() == SC_Static &&
  5347. TSK == TSK_ImplicitInstantiation)
  5348. S.MarkVariableReferenced(VD->getLocation(), VD);
  5349. auto *MD = dyn_cast<CXXMethodDecl>(Member);
  5350. if (!MD)
  5351. continue;
  5352. if (MD->isUserProvided()) {
  5353. // Instantiate non-default class member functions ...
  5354. // .. except for certain kinds of template specializations.
  5355. if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
  5356. continue;
  5357. // If this is an MS ABI dllexport default constructor, instantiate any
  5358. // default arguments.
  5359. if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  5360. auto *CD = dyn_cast<CXXConstructorDecl>(MD);
  5361. if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
  5362. S.InstantiateDefaultCtorDefaultArgs(CD);
  5363. }
  5364. }
  5365. S.MarkFunctionReferenced(Class->getLocation(), MD);
  5366. // The function will be passed to the consumer when its definition is
  5367. // encountered.
  5368. } else if (MD->isExplicitlyDefaulted()) {
  5369. // Synthesize and instantiate explicitly defaulted methods.
  5370. S.MarkFunctionReferenced(Class->getLocation(), MD);
  5371. if (TSK != TSK_ExplicitInstantiationDefinition) {
  5372. // Except for explicit instantiation defs, we will not see the
  5373. // definition again later, so pass it to the consumer now.
  5374. S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
  5375. }
  5376. } else if (!MD->isTrivial() ||
  5377. MD->isCopyAssignmentOperator() ||
  5378. MD->isMoveAssignmentOperator()) {
  5379. // Synthesize and instantiate non-trivial implicit methods, and the copy
  5380. // and move assignment operators. The latter are exported even if they
  5381. // are trivial, because the address of an operator can be taken and
  5382. // should compare equal across libraries.
  5383. S.MarkFunctionReferenced(Class->getLocation(), MD);
  5384. // There is no later point when we will see the definition of this
  5385. // function, so pass it to the consumer now.
  5386. S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
  5387. }
  5388. }
  5389. }
  5390. static void checkForMultipleExportedDefaultConstructors(Sema &S,
  5391. CXXRecordDecl *Class) {
  5392. // Only the MS ABI has default constructor closures, so we don't need to do
  5393. // this semantic checking anywhere else.
  5394. if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
  5395. return;
  5396. CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
  5397. for (Decl *Member : Class->decls()) {
  5398. // Look for exported default constructors.
  5399. auto *CD = dyn_cast<CXXConstructorDecl>(Member);
  5400. if (!CD || !CD->isDefaultConstructor())
  5401. continue;
  5402. auto *Attr = CD->getAttr<DLLExportAttr>();
  5403. if (!Attr)
  5404. continue;
  5405. // If the class is non-dependent, mark the default arguments as ODR-used so
  5406. // that we can properly codegen the constructor closure.
  5407. if (!Class->isDependentContext()) {
  5408. for (ParmVarDecl *PD : CD->parameters()) {
  5409. (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
  5410. S.DiscardCleanupsInEvaluationContext();
  5411. }
  5412. }
  5413. if (LastExportedDefaultCtor) {
  5414. S.Diag(LastExportedDefaultCtor->getLocation(),
  5415. diag::err_attribute_dll_ambiguous_default_ctor)
  5416. << Class;
  5417. S.Diag(CD->getLocation(), diag::note_entity_declared_at)
  5418. << CD->getDeclName();
  5419. return;
  5420. }
  5421. LastExportedDefaultCtor = CD;
  5422. }
  5423. }
  5424. static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
  5425. CXXRecordDecl *Class) {
  5426. bool ErrorReported = false;
  5427. auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
  5428. ClassTemplateDecl *TD) {
  5429. if (ErrorReported)
  5430. return;
  5431. S.Diag(TD->getLocation(),
  5432. diag::err_cuda_device_builtin_surftex_cls_template)
  5433. << /*surface*/ 0 << TD;
  5434. ErrorReported = true;
  5435. };
  5436. ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
  5437. if (!TD) {
  5438. auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
  5439. if (!SD) {
  5440. S.Diag(Class->getLocation(),
  5441. diag::err_cuda_device_builtin_surftex_ref_decl)
  5442. << /*surface*/ 0 << Class;
  5443. S.Diag(Class->getLocation(),
  5444. diag::note_cuda_device_builtin_surftex_should_be_template_class)
  5445. << Class;
  5446. return;
  5447. }
  5448. TD = SD->getSpecializedTemplate();
  5449. }
  5450. TemplateParameterList *Params = TD->getTemplateParameters();
  5451. unsigned N = Params->size();
  5452. if (N != 2) {
  5453. reportIllegalClassTemplate(S, TD);
  5454. S.Diag(TD->getLocation(),
  5455. diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
  5456. << TD << 2;
  5457. }
  5458. if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  5459. reportIllegalClassTemplate(S, TD);
  5460. S.Diag(TD->getLocation(),
  5461. diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
  5462. << TD << /*1st*/ 0 << /*type*/ 0;
  5463. }
  5464. if (N > 1) {
  5465. auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
  5466. if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
  5467. reportIllegalClassTemplate(S, TD);
  5468. S.Diag(TD->getLocation(),
  5469. diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
  5470. << TD << /*2nd*/ 1 << /*integer*/ 1;
  5471. }
  5472. }
  5473. }
  5474. static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
  5475. CXXRecordDecl *Class) {
  5476. bool ErrorReported = false;
  5477. auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
  5478. ClassTemplateDecl *TD) {
  5479. if (ErrorReported)
  5480. return;
  5481. S.Diag(TD->getLocation(),
  5482. diag::err_cuda_device_builtin_surftex_cls_template)
  5483. << /*texture*/ 1 << TD;
  5484. ErrorReported = true;
  5485. };
  5486. ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
  5487. if (!TD) {
  5488. auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
  5489. if (!SD) {
  5490. S.Diag(Class->getLocation(),
  5491. diag::err_cuda_device_builtin_surftex_ref_decl)
  5492. << /*texture*/ 1 << Class;
  5493. S.Diag(Class->getLocation(),
  5494. diag::note_cuda_device_builtin_surftex_should_be_template_class)
  5495. << Class;
  5496. return;
  5497. }
  5498. TD = SD->getSpecializedTemplate();
  5499. }
  5500. TemplateParameterList *Params = TD->getTemplateParameters();
  5501. unsigned N = Params->size();
  5502. if (N != 3) {
  5503. reportIllegalClassTemplate(S, TD);
  5504. S.Diag(TD->getLocation(),
  5505. diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
  5506. << TD << 3;
  5507. }
  5508. if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  5509. reportIllegalClassTemplate(S, TD);
  5510. S.Diag(TD->getLocation(),
  5511. diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
  5512. << TD << /*1st*/ 0 << /*type*/ 0;
  5513. }
  5514. if (N > 1) {
  5515. auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
  5516. if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
  5517. reportIllegalClassTemplate(S, TD);
  5518. S.Diag(TD->getLocation(),
  5519. diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
  5520. << TD << /*2nd*/ 1 << /*integer*/ 1;
  5521. }
  5522. }
  5523. if (N > 2) {
  5524. auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
  5525. if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
  5526. reportIllegalClassTemplate(S, TD);
  5527. S.Diag(TD->getLocation(),
  5528. diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
  5529. << TD << /*3rd*/ 2 << /*integer*/ 1;
  5530. }
  5531. }
  5532. }
  5533. void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
  5534. // Mark any compiler-generated routines with the implicit code_seg attribute.
  5535. for (auto *Method : Class->methods()) {
  5536. if (Method->isUserProvided())
  5537. continue;
  5538. if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
  5539. Method->addAttr(A);
  5540. }
  5541. }
  5542. /// Check class-level dllimport/dllexport attribute.
  5543. void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
  5544. Attr *ClassAttr = getDLLAttr(Class);
  5545. // MSVC inherits DLL attributes to partial class template specializations.
  5546. if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
  5547. if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
  5548. if (Attr *TemplateAttr =
  5549. getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
  5550. auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
  5551. A->setInherited(true);
  5552. ClassAttr = A;
  5553. }
  5554. }
  5555. }
  5556. if (!ClassAttr)
  5557. return;
  5558. if (!Class->isExternallyVisible()) {
  5559. Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
  5560. << Class << ClassAttr;
  5561. return;
  5562. }
  5563. if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
  5564. !ClassAttr->isInherited()) {
  5565. // Diagnose dll attributes on members of class with dll attribute.
  5566. for (Decl *Member : Class->decls()) {
  5567. if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
  5568. continue;
  5569. InheritableAttr *MemberAttr = getDLLAttr(Member);
  5570. if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
  5571. continue;
  5572. Diag(MemberAttr->getLocation(),
  5573. diag::err_attribute_dll_member_of_dll_class)
  5574. << MemberAttr << ClassAttr;
  5575. Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
  5576. Member->setInvalidDecl();
  5577. }
  5578. }
  5579. if (Class->getDescribedClassTemplate())
  5580. // Don't inherit dll attribute until the template is instantiated.
  5581. return;
  5582. // The class is either imported or exported.
  5583. const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
  5584. // Check if this was a dllimport attribute propagated from a derived class to
  5585. // a base class template specialization. We don't apply these attributes to
  5586. // static data members.
  5587. const bool PropagatedImport =
  5588. !ClassExported &&
  5589. cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
  5590. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  5591. // Ignore explicit dllexport on explicit class template instantiation
  5592. // declarations, except in MinGW mode.
  5593. if (ClassExported && !ClassAttr->isInherited() &&
  5594. TSK == TSK_ExplicitInstantiationDeclaration &&
  5595. !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
  5596. Class->dropAttr<DLLExportAttr>();
  5597. return;
  5598. }
  5599. // Force declaration of implicit members so they can inherit the attribute.
  5600. ForceDeclarationOfImplicitMembers(Class);
  5601. // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
  5602. // seem to be true in practice?
  5603. for (Decl *Member : Class->decls()) {
  5604. VarDecl *VD = dyn_cast<VarDecl>(Member);
  5605. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
  5606. // Only methods and static fields inherit the attributes.
  5607. if (!VD && !MD)
  5608. continue;
  5609. if (MD) {
  5610. // Don't process deleted methods.
  5611. if (MD->isDeleted())
  5612. continue;
  5613. if (MD->isInlined()) {
  5614. // MinGW does not import or export inline methods. But do it for
  5615. // template instantiations.
  5616. if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
  5617. TSK != TSK_ExplicitInstantiationDeclaration &&
  5618. TSK != TSK_ExplicitInstantiationDefinition)
  5619. continue;
  5620. // MSVC versions before 2015 don't export the move assignment operators
  5621. // and move constructor, so don't attempt to import/export them if
  5622. // we have a definition.
  5623. auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
  5624. if ((MD->isMoveAssignmentOperator() ||
  5625. (Ctor && Ctor->isMoveConstructor())) &&
  5626. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
  5627. continue;
  5628. // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
  5629. // operator is exported anyway.
  5630. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  5631. (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
  5632. continue;
  5633. }
  5634. }
  5635. // Don't apply dllimport attributes to static data members of class template
  5636. // instantiations when the attribute is propagated from a derived class.
  5637. if (VD && PropagatedImport)
  5638. continue;
  5639. if (!cast<NamedDecl>(Member)->isExternallyVisible())
  5640. continue;
  5641. if (!getDLLAttr(Member)) {
  5642. InheritableAttr *NewAttr = nullptr;
  5643. // Do not export/import inline function when -fno-dllexport-inlines is
  5644. // passed. But add attribute for later local static var check.
  5645. if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
  5646. TSK != TSK_ExplicitInstantiationDeclaration &&
  5647. TSK != TSK_ExplicitInstantiationDefinition) {
  5648. if (ClassExported) {
  5649. NewAttr = ::new (getASTContext())
  5650. DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
  5651. } else {
  5652. NewAttr = ::new (getASTContext())
  5653. DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
  5654. }
  5655. } else {
  5656. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5657. }
  5658. NewAttr->setInherited(true);
  5659. Member->addAttr(NewAttr);
  5660. if (MD) {
  5661. // Propagate DLLAttr to friend re-declarations of MD that have already
  5662. // been constructed.
  5663. for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
  5664. FD = FD->getPreviousDecl()) {
  5665. if (FD->getFriendObjectKind() == Decl::FOK_None)
  5666. continue;
  5667. assert(!getDLLAttr(FD) &&
  5668. "friend re-decl should not already have a DLLAttr");
  5669. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5670. NewAttr->setInherited(true);
  5671. FD->addAttr(NewAttr);
  5672. }
  5673. }
  5674. }
  5675. }
  5676. if (ClassExported)
  5677. DelayedDllExportClasses.push_back(Class);
  5678. }
  5679. /// Perform propagation of DLL attributes from a derived class to a
  5680. /// templated base class for MS compatibility.
  5681. void Sema::propagateDLLAttrToBaseClassTemplate(
  5682. CXXRecordDecl *Class, Attr *ClassAttr,
  5683. ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
  5684. if (getDLLAttr(
  5685. BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
  5686. // If the base class template has a DLL attribute, don't try to change it.
  5687. return;
  5688. }
  5689. auto TSK = BaseTemplateSpec->getSpecializationKind();
  5690. if (!getDLLAttr(BaseTemplateSpec) &&
  5691. (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
  5692. TSK == TSK_ImplicitInstantiation)) {
  5693. // The template hasn't been instantiated yet (or it has, but only as an
  5694. // explicit instantiation declaration or implicit instantiation, which means
  5695. // we haven't codegenned any members yet), so propagate the attribute.
  5696. auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5697. NewAttr->setInherited(true);
  5698. BaseTemplateSpec->addAttr(NewAttr);
  5699. // If this was an import, mark that we propagated it from a derived class to
  5700. // a base class template specialization.
  5701. if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
  5702. ImportAttr->setPropagatedToBaseTemplate();
  5703. // If the template is already instantiated, checkDLLAttributeRedeclaration()
  5704. // needs to be run again to work see the new attribute. Otherwise this will
  5705. // get run whenever the template is instantiated.
  5706. if (TSK != TSK_Undeclared)
  5707. checkClassLevelDLLAttribute(BaseTemplateSpec);
  5708. return;
  5709. }
  5710. if (getDLLAttr(BaseTemplateSpec)) {
  5711. // The template has already been specialized or instantiated with an
  5712. // attribute, explicitly or through propagation. We should not try to change
  5713. // it.
  5714. return;
  5715. }
  5716. // The template was previously instantiated or explicitly specialized without
  5717. // a dll attribute, It's too late for us to add an attribute, so warn that
  5718. // this is unsupported.
  5719. Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
  5720. << BaseTemplateSpec->isExplicitSpecialization();
  5721. Diag(ClassAttr->getLocation(), diag::note_attribute);
  5722. if (BaseTemplateSpec->isExplicitSpecialization()) {
  5723. Diag(BaseTemplateSpec->getLocation(),
  5724. diag::note_template_class_explicit_specialization_was_here)
  5725. << BaseTemplateSpec;
  5726. } else {
  5727. Diag(BaseTemplateSpec->getPointOfInstantiation(),
  5728. diag::note_template_class_instantiation_was_here)
  5729. << BaseTemplateSpec;
  5730. }
  5731. }
  5732. /// Determine the kind of defaulting that would be done for a given function.
  5733. ///
  5734. /// If the function is both a default constructor and a copy / move constructor
  5735. /// (due to having a default argument for the first parameter), this picks
  5736. /// CXXDefaultConstructor.
  5737. ///
  5738. /// FIXME: Check that case is properly handled by all callers.
  5739. Sema::DefaultedFunctionKind
  5740. Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
  5741. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  5742. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
  5743. if (Ctor->isDefaultConstructor())
  5744. return Sema::CXXDefaultConstructor;
  5745. if (Ctor->isCopyConstructor())
  5746. return Sema::CXXCopyConstructor;
  5747. if (Ctor->isMoveConstructor())
  5748. return Sema::CXXMoveConstructor;
  5749. }
  5750. if (MD->isCopyAssignmentOperator())
  5751. return Sema::CXXCopyAssignment;
  5752. if (MD->isMoveAssignmentOperator())
  5753. return Sema::CXXMoveAssignment;
  5754. if (isa<CXXDestructorDecl>(FD))
  5755. return Sema::CXXDestructor;
  5756. }
  5757. switch (FD->getDeclName().getCXXOverloadedOperator()) {
  5758. case OO_EqualEqual:
  5759. return DefaultedComparisonKind::Equal;
  5760. case OO_ExclaimEqual:
  5761. return DefaultedComparisonKind::NotEqual;
  5762. case OO_Spaceship:
  5763. // No point allowing this if <=> doesn't exist in the current language mode.
  5764. if (!getLangOpts().CPlusPlus20)
  5765. break;
  5766. return DefaultedComparisonKind::ThreeWay;
  5767. case OO_Less:
  5768. case OO_LessEqual:
  5769. case OO_Greater:
  5770. case OO_GreaterEqual:
  5771. // No point allowing this if <=> doesn't exist in the current language mode.
  5772. if (!getLangOpts().CPlusPlus20)
  5773. break;
  5774. return DefaultedComparisonKind::Relational;
  5775. default:
  5776. break;
  5777. }
  5778. // Not defaultable.
  5779. return DefaultedFunctionKind();
  5780. }
  5781. static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
  5782. SourceLocation DefaultLoc) {
  5783. Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
  5784. if (DFK.isComparison())
  5785. return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
  5786. switch (DFK.asSpecialMember()) {
  5787. case Sema::CXXDefaultConstructor:
  5788. S.DefineImplicitDefaultConstructor(DefaultLoc,
  5789. cast<CXXConstructorDecl>(FD));
  5790. break;
  5791. case Sema::CXXCopyConstructor:
  5792. S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
  5793. break;
  5794. case Sema::CXXCopyAssignment:
  5795. S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
  5796. break;
  5797. case Sema::CXXDestructor:
  5798. S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
  5799. break;
  5800. case Sema::CXXMoveConstructor:
  5801. S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
  5802. break;
  5803. case Sema::CXXMoveAssignment:
  5804. S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
  5805. break;
  5806. case Sema::CXXInvalid:
  5807. llvm_unreachable("Invalid special member.");
  5808. }
  5809. }
  5810. /// Determine whether a type is permitted to be passed or returned in
  5811. /// registers, per C++ [class.temporary]p3.
  5812. static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
  5813. TargetInfo::CallingConvKind CCK) {
  5814. if (D->isDependentType() || D->isInvalidDecl())
  5815. return false;
  5816. // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
  5817. // The PS4 platform ABI follows the behavior of Clang 3.2.
  5818. if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
  5819. return !D->hasNonTrivialDestructorForCall() &&
  5820. !D->hasNonTrivialCopyConstructorForCall();
  5821. if (CCK == TargetInfo::CCK_MicrosoftWin64) {
  5822. bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
  5823. bool DtorIsTrivialForCall = false;
  5824. // If a class has at least one eligible, trivial copy constructor, it
  5825. // is passed according to the C ABI. Otherwise, it is passed indirectly.
  5826. //
  5827. // Note: This permits classes with non-trivial copy or move ctors to be
  5828. // passed in registers, so long as they *also* have a trivial copy ctor,
  5829. // which is non-conforming.
  5830. if (D->needsImplicitCopyConstructor()) {
  5831. if (!D->defaultedCopyConstructorIsDeleted()) {
  5832. if (D->hasTrivialCopyConstructor())
  5833. CopyCtorIsTrivial = true;
  5834. if (D->hasTrivialCopyConstructorForCall())
  5835. CopyCtorIsTrivialForCall = true;
  5836. }
  5837. } else {
  5838. for (const CXXConstructorDecl *CD : D->ctors()) {
  5839. if (CD->isCopyConstructor() && !CD->isDeleted() &&
  5840. !CD->isIneligibleOrNotSelected()) {
  5841. if (CD->isTrivial())
  5842. CopyCtorIsTrivial = true;
  5843. if (CD->isTrivialForCall())
  5844. CopyCtorIsTrivialForCall = true;
  5845. }
  5846. }
  5847. }
  5848. if (D->needsImplicitDestructor()) {
  5849. if (!D->defaultedDestructorIsDeleted() &&
  5850. D->hasTrivialDestructorForCall())
  5851. DtorIsTrivialForCall = true;
  5852. } else if (const auto *DD = D->getDestructor()) {
  5853. if (!DD->isDeleted() && DD->isTrivialForCall())
  5854. DtorIsTrivialForCall = true;
  5855. }
  5856. // If the copy ctor and dtor are both trivial-for-calls, pass direct.
  5857. if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
  5858. return true;
  5859. // If a class has a destructor, we'd really like to pass it indirectly
  5860. // because it allows us to elide copies. Unfortunately, MSVC makes that
  5861. // impossible for small types, which it will pass in a single register or
  5862. // stack slot. Most objects with dtors are large-ish, so handle that early.
  5863. // We can't call out all large objects as being indirect because there are
  5864. // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
  5865. // how we pass large POD types.
  5866. // Note: This permits small classes with nontrivial destructors to be
  5867. // passed in registers, which is non-conforming.
  5868. bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
  5869. uint64_t TypeSize = isAArch64 ? 128 : 64;
  5870. if (CopyCtorIsTrivial &&
  5871. S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
  5872. return true;
  5873. return false;
  5874. }
  5875. // Per C++ [class.temporary]p3, the relevant condition is:
  5876. // each copy constructor, move constructor, and destructor of X is
  5877. // either trivial or deleted, and X has at least one non-deleted copy
  5878. // or move constructor
  5879. bool HasNonDeletedCopyOrMove = false;
  5880. if (D->needsImplicitCopyConstructor() &&
  5881. !D->defaultedCopyConstructorIsDeleted()) {
  5882. if (!D->hasTrivialCopyConstructorForCall())
  5883. return false;
  5884. HasNonDeletedCopyOrMove = true;
  5885. }
  5886. if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
  5887. !D->defaultedMoveConstructorIsDeleted()) {
  5888. if (!D->hasTrivialMoveConstructorForCall())
  5889. return false;
  5890. HasNonDeletedCopyOrMove = true;
  5891. }
  5892. if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
  5893. !D->hasTrivialDestructorForCall())
  5894. return false;
  5895. for (const CXXMethodDecl *MD : D->methods()) {
  5896. if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
  5897. continue;
  5898. auto *CD = dyn_cast<CXXConstructorDecl>(MD);
  5899. if (CD && CD->isCopyOrMoveConstructor())
  5900. HasNonDeletedCopyOrMove = true;
  5901. else if (!isa<CXXDestructorDecl>(MD))
  5902. continue;
  5903. if (!MD->isTrivialForCall())
  5904. return false;
  5905. }
  5906. return HasNonDeletedCopyOrMove;
  5907. }
  5908. /// Report an error regarding overriding, along with any relevant
  5909. /// overridden methods.
  5910. ///
  5911. /// \param DiagID the primary error to report.
  5912. /// \param MD the overriding method.
  5913. static bool
  5914. ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
  5915. llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
  5916. bool IssuedDiagnostic = false;
  5917. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  5918. if (Report(O)) {
  5919. if (!IssuedDiagnostic) {
  5920. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  5921. IssuedDiagnostic = true;
  5922. }
  5923. S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
  5924. }
  5925. }
  5926. return IssuedDiagnostic;
  5927. }
  5928. /// Perform semantic checks on a class definition that has been
  5929. /// completing, introducing implicitly-declared members, checking for
  5930. /// abstract types, etc.
  5931. ///
  5932. /// \param S The scope in which the class was parsed. Null if we didn't just
  5933. /// parse a class definition.
  5934. /// \param Record The completed class.
  5935. void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
  5936. if (!Record)
  5937. return;
  5938. if (Record->isAbstract() && !Record->isInvalidDecl()) {
  5939. AbstractUsageInfo Info(*this, Record);
  5940. CheckAbstractClassUsage(Info, Record);
  5941. }
  5942. // If this is not an aggregate type and has no user-declared constructor,
  5943. // complain about any non-static data members of reference or const scalar
  5944. // type, since they will never get initializers.
  5945. if (!Record->isInvalidDecl() && !Record->isDependentType() &&
  5946. !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
  5947. !Record->isLambda()) {
  5948. bool Complained = false;
  5949. for (const auto *F : Record->fields()) {
  5950. if (F->hasInClassInitializer() || F->isUnnamedBitfield())
  5951. continue;
  5952. if (F->getType()->isReferenceType() ||
  5953. (F->getType().isConstQualified() && F->getType()->isScalarType())) {
  5954. if (!Complained) {
  5955. Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
  5956. << Record->getTagKind() << Record;
  5957. Complained = true;
  5958. }
  5959. Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
  5960. << F->getType()->isReferenceType()
  5961. << F->getDeclName();
  5962. }
  5963. }
  5964. }
  5965. if (Record->getIdentifier()) {
  5966. // C++ [class.mem]p13:
  5967. // If T is the name of a class, then each of the following shall have a
  5968. // name different from T:
  5969. // - every member of every anonymous union that is a member of class T.
  5970. //
  5971. // C++ [class.mem]p14:
  5972. // In addition, if class T has a user-declared constructor (12.1), every
  5973. // non-static data member of class T shall have a name different from T.
  5974. DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
  5975. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
  5976. ++I) {
  5977. NamedDecl *D = (*I)->getUnderlyingDecl();
  5978. if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
  5979. Record->hasUserDeclaredConstructor()) ||
  5980. isa<IndirectFieldDecl>(D)) {
  5981. Diag((*I)->getLocation(), diag::err_member_name_of_class)
  5982. << D->getDeclName();
  5983. break;
  5984. }
  5985. }
  5986. }
  5987. // Warn if the class has virtual methods but non-virtual public destructor.
  5988. if (Record->isPolymorphic() && !Record->isDependentType()) {
  5989. CXXDestructorDecl *dtor = Record->getDestructor();
  5990. if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
  5991. !Record->hasAttr<FinalAttr>())
  5992. Diag(dtor ? dtor->getLocation() : Record->getLocation(),
  5993. diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
  5994. }
  5995. if (Record->isAbstract()) {
  5996. if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
  5997. Diag(Record->getLocation(), diag::warn_abstract_final_class)
  5998. << FA->isSpelledAsSealed();
  5999. DiagnoseAbstractType(Record);
  6000. }
  6001. }
  6002. // Warn if the class has a final destructor but is not itself marked final.
  6003. if (!Record->hasAttr<FinalAttr>()) {
  6004. if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
  6005. if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
  6006. Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
  6007. << FA->isSpelledAsSealed()
  6008. << FixItHint::CreateInsertion(
  6009. getLocForEndOfToken(Record->getLocation()),
  6010. (FA->isSpelledAsSealed() ? " sealed" : " final"));
  6011. Diag(Record->getLocation(),
  6012. diag::note_final_dtor_non_final_class_silence)
  6013. << Context.getRecordType(Record) << FA->isSpelledAsSealed();
  6014. }
  6015. }
  6016. }
  6017. // See if trivial_abi has to be dropped.
  6018. if (Record->hasAttr<TrivialABIAttr>())
  6019. checkIllFormedTrivialABIStruct(*Record);
  6020. // Set HasTrivialSpecialMemberForCall if the record has attribute
  6021. // "trivial_abi".
  6022. bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
  6023. if (HasTrivialABI)
  6024. Record->setHasTrivialSpecialMemberForCall();
  6025. // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
  6026. // We check these last because they can depend on the properties of the
  6027. // primary comparison functions (==, <=>).
  6028. llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
  6029. // Perform checks that can't be done until we know all the properties of a
  6030. // member function (whether it's defaulted, deleted, virtual, overriding,
  6031. // ...).
  6032. auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
  6033. // A static function cannot override anything.
  6034. if (MD->getStorageClass() == SC_Static) {
  6035. if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
  6036. [](const CXXMethodDecl *) { return true; }))
  6037. return;
  6038. }
  6039. // A deleted function cannot override a non-deleted function and vice
  6040. // versa.
  6041. if (ReportOverrides(*this,
  6042. MD->isDeleted() ? diag::err_deleted_override
  6043. : diag::err_non_deleted_override,
  6044. MD, [&](const CXXMethodDecl *V) {
  6045. return MD->isDeleted() != V->isDeleted();
  6046. })) {
  6047. if (MD->isDefaulted() && MD->isDeleted())
  6048. // Explain why this defaulted function was deleted.
  6049. DiagnoseDeletedDefaultedFunction(MD);
  6050. return;
  6051. }
  6052. // A consteval function cannot override a non-consteval function and vice
  6053. // versa.
  6054. if (ReportOverrides(*this,
  6055. MD->isConsteval() ? diag::err_consteval_override
  6056. : diag::err_non_consteval_override,
  6057. MD, [&](const CXXMethodDecl *V) {
  6058. return MD->isConsteval() != V->isConsteval();
  6059. })) {
  6060. if (MD->isDefaulted() && MD->isDeleted())
  6061. // Explain why this defaulted function was deleted.
  6062. DiagnoseDeletedDefaultedFunction(MD);
  6063. return;
  6064. }
  6065. };
  6066. auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
  6067. if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
  6068. return false;
  6069. DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
  6070. if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
  6071. DFK.asComparison() == DefaultedComparisonKind::Relational) {
  6072. DefaultedSecondaryComparisons.push_back(FD);
  6073. return true;
  6074. }
  6075. CheckExplicitlyDefaultedFunction(S, FD);
  6076. return false;
  6077. };
  6078. auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
  6079. // Check whether the explicitly-defaulted members are valid.
  6080. bool Incomplete = CheckForDefaultedFunction(M);
  6081. // Skip the rest of the checks for a member of a dependent class.
  6082. if (Record->isDependentType())
  6083. return;
  6084. // For an explicitly defaulted or deleted special member, we defer
  6085. // determining triviality until the class is complete. That time is now!
  6086. CXXSpecialMember CSM = getSpecialMember(M);
  6087. if (!M->isImplicit() && !M->isUserProvided()) {
  6088. if (CSM != CXXInvalid) {
  6089. M->setTrivial(SpecialMemberIsTrivial(M, CSM));
  6090. // Inform the class that we've finished declaring this member.
  6091. Record->finishedDefaultedOrDeletedMember(M);
  6092. M->setTrivialForCall(
  6093. HasTrivialABI ||
  6094. SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
  6095. Record->setTrivialForCallFlags(M);
  6096. }
  6097. }
  6098. // Set triviality for the purpose of calls if this is a user-provided
  6099. // copy/move constructor or destructor.
  6100. if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
  6101. CSM == CXXDestructor) && M->isUserProvided()) {
  6102. M->setTrivialForCall(HasTrivialABI);
  6103. Record->setTrivialForCallFlags(M);
  6104. }
  6105. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
  6106. M->hasAttr<DLLExportAttr>()) {
  6107. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  6108. M->isTrivial() &&
  6109. (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
  6110. CSM == CXXDestructor))
  6111. M->dropAttr<DLLExportAttr>();
  6112. if (M->hasAttr<DLLExportAttr>()) {
  6113. // Define after any fields with in-class initializers have been parsed.
  6114. DelayedDllExportMemberFunctions.push_back(M);
  6115. }
  6116. }
  6117. // Define defaulted constexpr virtual functions that override a base class
  6118. // function right away.
  6119. // FIXME: We can defer doing this until the vtable is marked as used.
  6120. if (CSM != CXXInvalid && !M->isDeleted() && M->isDefaulted() &&
  6121. M->isConstexpr() && M->size_overridden_methods())
  6122. DefineDefaultedFunction(*this, M, M->getLocation());
  6123. if (!Incomplete)
  6124. CheckCompletedMemberFunction(M);
  6125. };
  6126. // Check the destructor before any other member function. We need to
  6127. // determine whether it's trivial in order to determine whether the claas
  6128. // type is a literal type, which is a prerequisite for determining whether
  6129. // other special member functions are valid and whether they're implicitly
  6130. // 'constexpr'.
  6131. if (CXXDestructorDecl *Dtor = Record->getDestructor())
  6132. CompleteMemberFunction(Dtor);
  6133. bool HasMethodWithOverrideControl = false,
  6134. HasOverridingMethodWithoutOverrideControl = false;
  6135. for (auto *D : Record->decls()) {
  6136. if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
  6137. // FIXME: We could do this check for dependent types with non-dependent
  6138. // bases.
  6139. if (!Record->isDependentType()) {
  6140. // See if a method overloads virtual methods in a base
  6141. // class without overriding any.
  6142. if (!M->isStatic())
  6143. DiagnoseHiddenVirtualMethods(M);
  6144. if (M->hasAttr<OverrideAttr>())
  6145. HasMethodWithOverrideControl = true;
  6146. else if (M->size_overridden_methods() > 0)
  6147. HasOverridingMethodWithoutOverrideControl = true;
  6148. }
  6149. if (!isa<CXXDestructorDecl>(M))
  6150. CompleteMemberFunction(M);
  6151. } else if (auto *F = dyn_cast<FriendDecl>(D)) {
  6152. CheckForDefaultedFunction(
  6153. dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
  6154. }
  6155. }
  6156. if (HasOverridingMethodWithoutOverrideControl) {
  6157. bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
  6158. for (auto *M : Record->methods())
  6159. DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
  6160. }
  6161. // Check the defaulted secondary comparisons after any other member functions.
  6162. for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
  6163. CheckExplicitlyDefaultedFunction(S, FD);
  6164. // If this is a member function, we deferred checking it until now.
  6165. if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
  6166. CheckCompletedMemberFunction(MD);
  6167. }
  6168. // ms_struct is a request to use the same ABI rules as MSVC. Check
  6169. // whether this class uses any C++ features that are implemented
  6170. // completely differently in MSVC, and if so, emit a diagnostic.
  6171. // That diagnostic defaults to an error, but we allow projects to
  6172. // map it down to a warning (or ignore it). It's a fairly common
  6173. // practice among users of the ms_struct pragma to mass-annotate
  6174. // headers, sweeping up a bunch of types that the project doesn't
  6175. // really rely on MSVC-compatible layout for. We must therefore
  6176. // support "ms_struct except for C++ stuff" as a secondary ABI.
  6177. // Don't emit this diagnostic if the feature was enabled as a
  6178. // language option (as opposed to via a pragma or attribute), as
  6179. // the option -mms-bitfields otherwise essentially makes it impossible
  6180. // to build C++ code, unless this diagnostic is turned off.
  6181. if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
  6182. (Record->isPolymorphic() || Record->getNumBases())) {
  6183. Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
  6184. }
  6185. checkClassLevelDLLAttribute(Record);
  6186. checkClassLevelCodeSegAttribute(Record);
  6187. bool ClangABICompat4 =
  6188. Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
  6189. TargetInfo::CallingConvKind CCK =
  6190. Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
  6191. bool CanPass = canPassInRegisters(*this, Record, CCK);
  6192. // Do not change ArgPassingRestrictions if it has already been set to
  6193. // APK_CanNeverPassInRegs.
  6194. if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
  6195. Record->setArgPassingRestrictions(CanPass
  6196. ? RecordDecl::APK_CanPassInRegs
  6197. : RecordDecl::APK_CannotPassInRegs);
  6198. // If canPassInRegisters returns true despite the record having a non-trivial
  6199. // destructor, the record is destructed in the callee. This happens only when
  6200. // the record or one of its subobjects has a field annotated with trivial_abi
  6201. // or a field qualified with ObjC __strong/__weak.
  6202. if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
  6203. Record->setParamDestroyedInCallee(true);
  6204. else if (Record->hasNonTrivialDestructor())
  6205. Record->setParamDestroyedInCallee(CanPass);
  6206. if (getLangOpts().ForceEmitVTables) {
  6207. // If we want to emit all the vtables, we need to mark it as used. This
  6208. // is especially required for cases like vtable assumption loads.
  6209. MarkVTableUsed(Record->getInnerLocStart(), Record);
  6210. }
  6211. if (getLangOpts().CUDA) {
  6212. if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
  6213. checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
  6214. else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
  6215. checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
  6216. }
  6217. }
  6218. /// Look up the special member function that would be called by a special
  6219. /// member function for a subobject of class type.
  6220. ///
  6221. /// \param Class The class type of the subobject.
  6222. /// \param CSM The kind of special member function.
  6223. /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
  6224. /// \param ConstRHS True if this is a copy operation with a const object
  6225. /// on its RHS, that is, if the argument to the outer special member
  6226. /// function is 'const' and this is not a field marked 'mutable'.
  6227. static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
  6228. Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
  6229. unsigned FieldQuals, bool ConstRHS) {
  6230. unsigned LHSQuals = 0;
  6231. if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
  6232. LHSQuals = FieldQuals;
  6233. unsigned RHSQuals = FieldQuals;
  6234. if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
  6235. RHSQuals = 0;
  6236. else if (ConstRHS)
  6237. RHSQuals |= Qualifiers::Const;
  6238. return S.LookupSpecialMember(Class, CSM,
  6239. RHSQuals & Qualifiers::Const,
  6240. RHSQuals & Qualifiers::Volatile,
  6241. false,
  6242. LHSQuals & Qualifiers::Const,
  6243. LHSQuals & Qualifiers::Volatile);
  6244. }
  6245. class Sema::InheritedConstructorInfo {
  6246. Sema &S;
  6247. SourceLocation UseLoc;
  6248. /// A mapping from the base classes through which the constructor was
  6249. /// inherited to the using shadow declaration in that base class (or a null
  6250. /// pointer if the constructor was declared in that base class).
  6251. llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
  6252. InheritedFromBases;
  6253. public:
  6254. InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
  6255. ConstructorUsingShadowDecl *Shadow)
  6256. : S(S), UseLoc(UseLoc) {
  6257. bool DiagnosedMultipleConstructedBases = false;
  6258. CXXRecordDecl *ConstructedBase = nullptr;
  6259. BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
  6260. // Find the set of such base class subobjects and check that there's a
  6261. // unique constructed subobject.
  6262. for (auto *D : Shadow->redecls()) {
  6263. auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
  6264. auto *DNominatedBase = DShadow->getNominatedBaseClass();
  6265. auto *DConstructedBase = DShadow->getConstructedBaseClass();
  6266. InheritedFromBases.insert(
  6267. std::make_pair(DNominatedBase->getCanonicalDecl(),
  6268. DShadow->getNominatedBaseClassShadowDecl()));
  6269. if (DShadow->constructsVirtualBase())
  6270. InheritedFromBases.insert(
  6271. std::make_pair(DConstructedBase->getCanonicalDecl(),
  6272. DShadow->getConstructedBaseClassShadowDecl()));
  6273. else
  6274. assert(DNominatedBase == DConstructedBase);
  6275. // [class.inhctor.init]p2:
  6276. // If the constructor was inherited from multiple base class subobjects
  6277. // of type B, the program is ill-formed.
  6278. if (!ConstructedBase) {
  6279. ConstructedBase = DConstructedBase;
  6280. ConstructedBaseIntroducer = D->getIntroducer();
  6281. } else if (ConstructedBase != DConstructedBase &&
  6282. !Shadow->isInvalidDecl()) {
  6283. if (!DiagnosedMultipleConstructedBases) {
  6284. S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
  6285. << Shadow->getTargetDecl();
  6286. S.Diag(ConstructedBaseIntroducer->getLocation(),
  6287. diag::note_ambiguous_inherited_constructor_using)
  6288. << ConstructedBase;
  6289. DiagnosedMultipleConstructedBases = true;
  6290. }
  6291. S.Diag(D->getIntroducer()->getLocation(),
  6292. diag::note_ambiguous_inherited_constructor_using)
  6293. << DConstructedBase;
  6294. }
  6295. }
  6296. if (DiagnosedMultipleConstructedBases)
  6297. Shadow->setInvalidDecl();
  6298. }
  6299. /// Find the constructor to use for inherited construction of a base class,
  6300. /// and whether that base class constructor inherits the constructor from a
  6301. /// virtual base class (in which case it won't actually invoke it).
  6302. std::pair<CXXConstructorDecl *, bool>
  6303. findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
  6304. auto It = InheritedFromBases.find(Base->getCanonicalDecl());
  6305. if (It == InheritedFromBases.end())
  6306. return std::make_pair(nullptr, false);
  6307. // This is an intermediary class.
  6308. if (It->second)
  6309. return std::make_pair(
  6310. S.findInheritingConstructor(UseLoc, Ctor, It->second),
  6311. It->second->constructsVirtualBase());
  6312. // This is the base class from which the constructor was inherited.
  6313. return std::make_pair(Ctor, false);
  6314. }
  6315. };
  6316. /// Is the special member function which would be selected to perform the
  6317. /// specified operation on the specified class type a constexpr constructor?
  6318. static bool
  6319. specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
  6320. Sema::CXXSpecialMember CSM, unsigned Quals,
  6321. bool ConstRHS,
  6322. CXXConstructorDecl *InheritedCtor = nullptr,
  6323. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  6324. // Suppress duplicate constraint checking here, in case a constraint check
  6325. // caused us to decide to do this. Any truely recursive checks will get
  6326. // caught during these checks anyway.
  6327. Sema::SatisfactionStackResetRAII SSRAII{S};
  6328. // If we're inheriting a constructor, see if we need to call it for this base
  6329. // class.
  6330. if (InheritedCtor) {
  6331. assert(CSM == Sema::CXXDefaultConstructor);
  6332. auto BaseCtor =
  6333. Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
  6334. if (BaseCtor)
  6335. return BaseCtor->isConstexpr();
  6336. }
  6337. if (CSM == Sema::CXXDefaultConstructor)
  6338. return ClassDecl->hasConstexprDefaultConstructor();
  6339. if (CSM == Sema::CXXDestructor)
  6340. return ClassDecl->hasConstexprDestructor();
  6341. Sema::SpecialMemberOverloadResult SMOR =
  6342. lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
  6343. if (!SMOR.getMethod())
  6344. // A constructor we wouldn't select can't be "involved in initializing"
  6345. // anything.
  6346. return true;
  6347. return SMOR.getMethod()->isConstexpr();
  6348. }
  6349. /// Determine whether the specified special member function would be constexpr
  6350. /// if it were implicitly defined.
  6351. static bool defaultedSpecialMemberIsConstexpr(
  6352. Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
  6353. bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
  6354. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  6355. if (!S.getLangOpts().CPlusPlus11)
  6356. return false;
  6357. // C++11 [dcl.constexpr]p4:
  6358. // In the definition of a constexpr constructor [...]
  6359. bool Ctor = true;
  6360. switch (CSM) {
  6361. case Sema::CXXDefaultConstructor:
  6362. if (Inherited)
  6363. break;
  6364. // Since default constructor lookup is essentially trivial (and cannot
  6365. // involve, for instance, template instantiation), we compute whether a
  6366. // defaulted default constructor is constexpr directly within CXXRecordDecl.
  6367. //
  6368. // This is important for performance; we need to know whether the default
  6369. // constructor is constexpr to determine whether the type is a literal type.
  6370. return ClassDecl->defaultedDefaultConstructorIsConstexpr();
  6371. case Sema::CXXCopyConstructor:
  6372. case Sema::CXXMoveConstructor:
  6373. // For copy or move constructors, we need to perform overload resolution.
  6374. break;
  6375. case Sema::CXXCopyAssignment:
  6376. case Sema::CXXMoveAssignment:
  6377. if (!S.getLangOpts().CPlusPlus14)
  6378. return false;
  6379. // In C++1y, we need to perform overload resolution.
  6380. Ctor = false;
  6381. break;
  6382. case Sema::CXXDestructor:
  6383. return ClassDecl->defaultedDestructorIsConstexpr();
  6384. case Sema::CXXInvalid:
  6385. return false;
  6386. }
  6387. // -- if the class is a non-empty union, or for each non-empty anonymous
  6388. // union member of a non-union class, exactly one non-static data member
  6389. // shall be initialized; [DR1359]
  6390. //
  6391. // If we squint, this is guaranteed, since exactly one non-static data member
  6392. // will be initialized (if the constructor isn't deleted), we just don't know
  6393. // which one.
  6394. if (Ctor && ClassDecl->isUnion())
  6395. return CSM == Sema::CXXDefaultConstructor
  6396. ? ClassDecl->hasInClassInitializer() ||
  6397. !ClassDecl->hasVariantMembers()
  6398. : true;
  6399. // -- the class shall not have any virtual base classes;
  6400. if (Ctor && ClassDecl->getNumVBases())
  6401. return false;
  6402. // C++1y [class.copy]p26:
  6403. // -- [the class] is a literal type, and
  6404. if (!Ctor && !ClassDecl->isLiteral())
  6405. return false;
  6406. // -- every constructor involved in initializing [...] base class
  6407. // sub-objects shall be a constexpr constructor;
  6408. // -- the assignment operator selected to copy/move each direct base
  6409. // class is a constexpr function, and
  6410. for (const auto &B : ClassDecl->bases()) {
  6411. const RecordType *BaseType = B.getType()->getAs<RecordType>();
  6412. if (!BaseType)
  6413. continue;
  6414. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  6415. if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
  6416. InheritedCtor, Inherited))
  6417. return false;
  6418. }
  6419. // -- every constructor involved in initializing non-static data members
  6420. // [...] shall be a constexpr constructor;
  6421. // -- every non-static data member and base class sub-object shall be
  6422. // initialized
  6423. // -- for each non-static data member of X that is of class type (or array
  6424. // thereof), the assignment operator selected to copy/move that member is
  6425. // a constexpr function
  6426. for (const auto *F : ClassDecl->fields()) {
  6427. if (F->isInvalidDecl())
  6428. continue;
  6429. if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
  6430. continue;
  6431. QualType BaseType = S.Context.getBaseElementType(F->getType());
  6432. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  6433. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  6434. if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
  6435. BaseType.getCVRQualifiers(),
  6436. ConstArg && !F->isMutable()))
  6437. return false;
  6438. } else if (CSM == Sema::CXXDefaultConstructor) {
  6439. return false;
  6440. }
  6441. }
  6442. // All OK, it's constexpr!
  6443. return true;
  6444. }
  6445. namespace {
  6446. /// RAII object to register a defaulted function as having its exception
  6447. /// specification computed.
  6448. struct ComputingExceptionSpec {
  6449. Sema &S;
  6450. ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
  6451. : S(S) {
  6452. Sema::CodeSynthesisContext Ctx;
  6453. Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
  6454. Ctx.PointOfInstantiation = Loc;
  6455. Ctx.Entity = FD;
  6456. S.pushCodeSynthesisContext(Ctx);
  6457. }
  6458. ~ComputingExceptionSpec() {
  6459. S.popCodeSynthesisContext();
  6460. }
  6461. };
  6462. }
  6463. static Sema::ImplicitExceptionSpecification
  6464. ComputeDefaultedSpecialMemberExceptionSpec(
  6465. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  6466. Sema::InheritedConstructorInfo *ICI);
  6467. static Sema::ImplicitExceptionSpecification
  6468. ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
  6469. FunctionDecl *FD,
  6470. Sema::DefaultedComparisonKind DCK);
  6471. static Sema::ImplicitExceptionSpecification
  6472. computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
  6473. auto DFK = S.getDefaultedFunctionKind(FD);
  6474. if (DFK.isSpecialMember())
  6475. return ComputeDefaultedSpecialMemberExceptionSpec(
  6476. S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
  6477. if (DFK.isComparison())
  6478. return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
  6479. DFK.asComparison());
  6480. auto *CD = cast<CXXConstructorDecl>(FD);
  6481. assert(CD->getInheritedConstructor() &&
  6482. "only defaulted functions and inherited constructors have implicit "
  6483. "exception specs");
  6484. Sema::InheritedConstructorInfo ICI(
  6485. S, Loc, CD->getInheritedConstructor().getShadowDecl());
  6486. return ComputeDefaultedSpecialMemberExceptionSpec(
  6487. S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
  6488. }
  6489. static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
  6490. CXXMethodDecl *MD) {
  6491. FunctionProtoType::ExtProtoInfo EPI;
  6492. // Build an exception specification pointing back at this member.
  6493. EPI.ExceptionSpec.Type = EST_Unevaluated;
  6494. EPI.ExceptionSpec.SourceDecl = MD;
  6495. // Set the calling convention to the default for C++ instance methods.
  6496. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
  6497. S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  6498. /*IsCXXMethod=*/true));
  6499. return EPI;
  6500. }
  6501. void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
  6502. const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
  6503. if (FPT->getExceptionSpecType() != EST_Unevaluated)
  6504. return;
  6505. // Evaluate the exception specification.
  6506. auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
  6507. auto ESI = IES.getExceptionSpec();
  6508. // Update the type of the special member to use it.
  6509. UpdateExceptionSpec(FD, ESI);
  6510. }
  6511. void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
  6512. assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
  6513. DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
  6514. if (!DefKind) {
  6515. assert(FD->getDeclContext()->isDependentContext());
  6516. return;
  6517. }
  6518. if (DefKind.isComparison())
  6519. UnusedPrivateFields.clear();
  6520. if (DefKind.isSpecialMember()
  6521. ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
  6522. DefKind.asSpecialMember(),
  6523. FD->getDefaultLoc())
  6524. : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
  6525. FD->setInvalidDecl();
  6526. }
  6527. bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
  6528. CXXSpecialMember CSM,
  6529. SourceLocation DefaultLoc) {
  6530. CXXRecordDecl *RD = MD->getParent();
  6531. assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
  6532. "not an explicitly-defaulted special member");
  6533. // Defer all checking for special members of a dependent type.
  6534. if (RD->isDependentType())
  6535. return false;
  6536. // Whether this was the first-declared instance of the constructor.
  6537. // This affects whether we implicitly add an exception spec and constexpr.
  6538. bool First = MD == MD->getCanonicalDecl();
  6539. bool HadError = false;
  6540. // C++11 [dcl.fct.def.default]p1:
  6541. // A function that is explicitly defaulted shall
  6542. // -- be a special member function [...] (checked elsewhere),
  6543. // -- have the same type (except for ref-qualifiers, and except that a
  6544. // copy operation can take a non-const reference) as an implicit
  6545. // declaration, and
  6546. // -- not have default arguments.
  6547. // C++2a changes the second bullet to instead delete the function if it's
  6548. // defaulted on its first declaration, unless it's "an assignment operator,
  6549. // and its return type differs or its parameter type is not a reference".
  6550. bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
  6551. bool ShouldDeleteForTypeMismatch = false;
  6552. unsigned ExpectedParams = 1;
  6553. if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
  6554. ExpectedParams = 0;
  6555. if (MD->getNumParams() != ExpectedParams) {
  6556. // This checks for default arguments: a copy or move constructor with a
  6557. // default argument is classified as a default constructor, and assignment
  6558. // operations and destructors can't have default arguments.
  6559. Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
  6560. << CSM << MD->getSourceRange();
  6561. HadError = true;
  6562. } else if (MD->isVariadic()) {
  6563. if (DeleteOnTypeMismatch)
  6564. ShouldDeleteForTypeMismatch = true;
  6565. else {
  6566. Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
  6567. << CSM << MD->getSourceRange();
  6568. HadError = true;
  6569. }
  6570. }
  6571. const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
  6572. bool CanHaveConstParam = false;
  6573. if (CSM == CXXCopyConstructor)
  6574. CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
  6575. else if (CSM == CXXCopyAssignment)
  6576. CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
  6577. QualType ReturnType = Context.VoidTy;
  6578. if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
  6579. // Check for return type matching.
  6580. ReturnType = Type->getReturnType();
  6581. QualType DeclType = Context.getTypeDeclType(RD);
  6582. DeclType = Context.getElaboratedType(ETK_None, nullptr, DeclType, nullptr);
  6583. DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
  6584. QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
  6585. if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
  6586. Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
  6587. << (CSM == CXXMoveAssignment) << ExpectedReturnType;
  6588. HadError = true;
  6589. }
  6590. // A defaulted special member cannot have cv-qualifiers.
  6591. if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
  6592. if (DeleteOnTypeMismatch)
  6593. ShouldDeleteForTypeMismatch = true;
  6594. else {
  6595. Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
  6596. << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
  6597. HadError = true;
  6598. }
  6599. }
  6600. }
  6601. // Check for parameter type matching.
  6602. QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
  6603. bool HasConstParam = false;
  6604. if (ExpectedParams && ArgType->isReferenceType()) {
  6605. // Argument must be reference to possibly-const T.
  6606. QualType ReferentType = ArgType->getPointeeType();
  6607. HasConstParam = ReferentType.isConstQualified();
  6608. if (ReferentType.isVolatileQualified()) {
  6609. if (DeleteOnTypeMismatch)
  6610. ShouldDeleteForTypeMismatch = true;
  6611. else {
  6612. Diag(MD->getLocation(),
  6613. diag::err_defaulted_special_member_volatile_param) << CSM;
  6614. HadError = true;
  6615. }
  6616. }
  6617. if (HasConstParam && !CanHaveConstParam) {
  6618. if (DeleteOnTypeMismatch)
  6619. ShouldDeleteForTypeMismatch = true;
  6620. else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
  6621. Diag(MD->getLocation(),
  6622. diag::err_defaulted_special_member_copy_const_param)
  6623. << (CSM == CXXCopyAssignment);
  6624. // FIXME: Explain why this special member can't be const.
  6625. HadError = true;
  6626. } else {
  6627. Diag(MD->getLocation(),
  6628. diag::err_defaulted_special_member_move_const_param)
  6629. << (CSM == CXXMoveAssignment);
  6630. HadError = true;
  6631. }
  6632. }
  6633. } else if (ExpectedParams) {
  6634. // A copy assignment operator can take its argument by value, but a
  6635. // defaulted one cannot.
  6636. assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
  6637. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
  6638. HadError = true;
  6639. }
  6640. // C++11 [dcl.fct.def.default]p2:
  6641. // An explicitly-defaulted function may be declared constexpr only if it
  6642. // would have been implicitly declared as constexpr,
  6643. // Do not apply this rule to members of class templates, since core issue 1358
  6644. // makes such functions always instantiate to constexpr functions. For
  6645. // functions which cannot be constexpr (for non-constructors in C++11 and for
  6646. // destructors in C++14 and C++17), this is checked elsewhere.
  6647. //
  6648. // FIXME: This should not apply if the member is deleted.
  6649. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
  6650. HasConstParam);
  6651. // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
  6652. // If the instantiated template specialization of a constexpr function
  6653. // template or member function of a class template would fail to satisfy
  6654. // the requirements for a constexpr function or constexpr constructor, that
  6655. // specialization is still a constexpr function or constexpr constructor,
  6656. // even though a call to such a function cannot appear in a constant
  6657. // expression.
  6658. if (MD->isTemplateInstantiation() && MD->isConstexpr())
  6659. Constexpr = true;
  6660. if ((getLangOpts().CPlusPlus20 ||
  6661. (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
  6662. : isa<CXXConstructorDecl>(MD))) &&
  6663. MD->isConstexpr() && !Constexpr &&
  6664. MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
  6665. Diag(MD->getBeginLoc(), MD->isConsteval()
  6666. ? diag::err_incorrect_defaulted_consteval
  6667. : diag::err_incorrect_defaulted_constexpr)
  6668. << CSM;
  6669. // FIXME: Explain why the special member can't be constexpr.
  6670. HadError = true;
  6671. }
  6672. if (First) {
  6673. // C++2a [dcl.fct.def.default]p3:
  6674. // If a function is explicitly defaulted on its first declaration, it is
  6675. // implicitly considered to be constexpr if the implicit declaration
  6676. // would be.
  6677. MD->setConstexprKind(Constexpr ? (MD->isConsteval()
  6678. ? ConstexprSpecKind::Consteval
  6679. : ConstexprSpecKind::Constexpr)
  6680. : ConstexprSpecKind::Unspecified);
  6681. if (!Type->hasExceptionSpec()) {
  6682. // C++2a [except.spec]p3:
  6683. // If a declaration of a function does not have a noexcept-specifier
  6684. // [and] is defaulted on its first declaration, [...] the exception
  6685. // specification is as specified below
  6686. FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
  6687. EPI.ExceptionSpec.Type = EST_Unevaluated;
  6688. EPI.ExceptionSpec.SourceDecl = MD;
  6689. MD->setType(Context.getFunctionType(
  6690. ReturnType, llvm::ArrayRef(&ArgType, ExpectedParams), EPI));
  6691. }
  6692. }
  6693. if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
  6694. if (First) {
  6695. SetDeclDeleted(MD, MD->getLocation());
  6696. if (!inTemplateInstantiation() && !HadError) {
  6697. Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
  6698. if (ShouldDeleteForTypeMismatch) {
  6699. Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
  6700. } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
  6701. /*Diagnose*/ true) &&
  6702. DefaultLoc.isValid()) {
  6703. Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
  6704. << FixItHint::CreateReplacement(DefaultLoc, "delete");
  6705. }
  6706. }
  6707. if (ShouldDeleteForTypeMismatch && !HadError) {
  6708. Diag(MD->getLocation(),
  6709. diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
  6710. }
  6711. } else {
  6712. // C++11 [dcl.fct.def.default]p4:
  6713. // [For a] user-provided explicitly-defaulted function [...] if such a
  6714. // function is implicitly defined as deleted, the program is ill-formed.
  6715. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
  6716. assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
  6717. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  6718. HadError = true;
  6719. }
  6720. }
  6721. return HadError;
  6722. }
  6723. namespace {
  6724. /// Helper class for building and checking a defaulted comparison.
  6725. ///
  6726. /// Defaulted functions are built in two phases:
  6727. ///
  6728. /// * First, the set of operations that the function will perform are
  6729. /// identified, and some of them are checked. If any of the checked
  6730. /// operations is invalid in certain ways, the comparison function is
  6731. /// defined as deleted and no body is built.
  6732. /// * Then, if the function is not defined as deleted, the body is built.
  6733. ///
  6734. /// This is accomplished by performing two visitation steps over the eventual
  6735. /// body of the function.
  6736. template<typename Derived, typename ResultList, typename Result,
  6737. typename Subobject>
  6738. class DefaultedComparisonVisitor {
  6739. public:
  6740. using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
  6741. DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
  6742. DefaultedComparisonKind DCK)
  6743. : S(S), RD(RD), FD(FD), DCK(DCK) {
  6744. if (auto *Info = FD->getDefaultedFunctionInfo()) {
  6745. // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
  6746. // UnresolvedSet to avoid this copy.
  6747. Fns.assign(Info->getUnqualifiedLookups().begin(),
  6748. Info->getUnqualifiedLookups().end());
  6749. }
  6750. }
  6751. ResultList visit() {
  6752. // The type of an lvalue naming a parameter of this function.
  6753. QualType ParamLvalType =
  6754. FD->getParamDecl(0)->getType().getNonReferenceType();
  6755. ResultList Results;
  6756. switch (DCK) {
  6757. case DefaultedComparisonKind::None:
  6758. llvm_unreachable("not a defaulted comparison");
  6759. case DefaultedComparisonKind::Equal:
  6760. case DefaultedComparisonKind::ThreeWay:
  6761. getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
  6762. return Results;
  6763. case DefaultedComparisonKind::NotEqual:
  6764. case DefaultedComparisonKind::Relational:
  6765. Results.add(getDerived().visitExpandedSubobject(
  6766. ParamLvalType, getDerived().getCompleteObject()));
  6767. return Results;
  6768. }
  6769. llvm_unreachable("");
  6770. }
  6771. protected:
  6772. Derived &getDerived() { return static_cast<Derived&>(*this); }
  6773. /// Visit the expanded list of subobjects of the given type, as specified in
  6774. /// C++2a [class.compare.default].
  6775. ///
  6776. /// \return \c true if the ResultList object said we're done, \c false if not.
  6777. bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
  6778. Qualifiers Quals) {
  6779. // C++2a [class.compare.default]p4:
  6780. // The direct base class subobjects of C
  6781. for (CXXBaseSpecifier &Base : Record->bases())
  6782. if (Results.add(getDerived().visitSubobject(
  6783. S.Context.getQualifiedType(Base.getType(), Quals),
  6784. getDerived().getBase(&Base))))
  6785. return true;
  6786. // followed by the non-static data members of C
  6787. for (FieldDecl *Field : Record->fields()) {
  6788. // Recursively expand anonymous structs.
  6789. if (Field->isAnonymousStructOrUnion()) {
  6790. if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
  6791. Quals))
  6792. return true;
  6793. continue;
  6794. }
  6795. // Figure out the type of an lvalue denoting this field.
  6796. Qualifiers FieldQuals = Quals;
  6797. if (Field->isMutable())
  6798. FieldQuals.removeConst();
  6799. QualType FieldType =
  6800. S.Context.getQualifiedType(Field->getType(), FieldQuals);
  6801. if (Results.add(getDerived().visitSubobject(
  6802. FieldType, getDerived().getField(Field))))
  6803. return true;
  6804. }
  6805. // form a list of subobjects.
  6806. return false;
  6807. }
  6808. Result visitSubobject(QualType Type, Subobject Subobj) {
  6809. // In that list, any subobject of array type is recursively expanded
  6810. const ArrayType *AT = S.Context.getAsArrayType(Type);
  6811. if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
  6812. return getDerived().visitSubobjectArray(CAT->getElementType(),
  6813. CAT->getSize(), Subobj);
  6814. return getDerived().visitExpandedSubobject(Type, Subobj);
  6815. }
  6816. Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
  6817. Subobject Subobj) {
  6818. return getDerived().visitSubobject(Type, Subobj);
  6819. }
  6820. protected:
  6821. Sema &S;
  6822. CXXRecordDecl *RD;
  6823. FunctionDecl *FD;
  6824. DefaultedComparisonKind DCK;
  6825. UnresolvedSet<16> Fns;
  6826. };
  6827. /// Information about a defaulted comparison, as determined by
  6828. /// DefaultedComparisonAnalyzer.
  6829. struct DefaultedComparisonInfo {
  6830. bool Deleted = false;
  6831. bool Constexpr = true;
  6832. ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
  6833. static DefaultedComparisonInfo deleted() {
  6834. DefaultedComparisonInfo Deleted;
  6835. Deleted.Deleted = true;
  6836. return Deleted;
  6837. }
  6838. bool add(const DefaultedComparisonInfo &R) {
  6839. Deleted |= R.Deleted;
  6840. Constexpr &= R.Constexpr;
  6841. Category = commonComparisonType(Category, R.Category);
  6842. return Deleted;
  6843. }
  6844. };
  6845. /// An element in the expanded list of subobjects of a defaulted comparison, as
  6846. /// specified in C++2a [class.compare.default]p4.
  6847. struct DefaultedComparisonSubobject {
  6848. enum { CompleteObject, Member, Base } Kind;
  6849. NamedDecl *Decl;
  6850. SourceLocation Loc;
  6851. };
  6852. /// A visitor over the notional body of a defaulted comparison that determines
  6853. /// whether that body would be deleted or constexpr.
  6854. class DefaultedComparisonAnalyzer
  6855. : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
  6856. DefaultedComparisonInfo,
  6857. DefaultedComparisonInfo,
  6858. DefaultedComparisonSubobject> {
  6859. public:
  6860. enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
  6861. private:
  6862. DiagnosticKind Diagnose;
  6863. public:
  6864. using Base = DefaultedComparisonVisitor;
  6865. using Result = DefaultedComparisonInfo;
  6866. using Subobject = DefaultedComparisonSubobject;
  6867. friend Base;
  6868. DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
  6869. DefaultedComparisonKind DCK,
  6870. DiagnosticKind Diagnose = NoDiagnostics)
  6871. : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
  6872. Result visit() {
  6873. if ((DCK == DefaultedComparisonKind::Equal ||
  6874. DCK == DefaultedComparisonKind::ThreeWay) &&
  6875. RD->hasVariantMembers()) {
  6876. // C++2a [class.compare.default]p2 [P2002R0]:
  6877. // A defaulted comparison operator function for class C is defined as
  6878. // deleted if [...] C has variant members.
  6879. if (Diagnose == ExplainDeleted) {
  6880. S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
  6881. << FD << RD->isUnion() << RD;
  6882. }
  6883. return Result::deleted();
  6884. }
  6885. return Base::visit();
  6886. }
  6887. private:
  6888. Subobject getCompleteObject() {
  6889. return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
  6890. }
  6891. Subobject getBase(CXXBaseSpecifier *Base) {
  6892. return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
  6893. Base->getBaseTypeLoc()};
  6894. }
  6895. Subobject getField(FieldDecl *Field) {
  6896. return Subobject{Subobject::Member, Field, Field->getLocation()};
  6897. }
  6898. Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
  6899. // C++2a [class.compare.default]p2 [P2002R0]:
  6900. // A defaulted <=> or == operator function for class C is defined as
  6901. // deleted if any non-static data member of C is of reference type
  6902. if (Type->isReferenceType()) {
  6903. if (Diagnose == ExplainDeleted) {
  6904. S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
  6905. << FD << RD;
  6906. }
  6907. return Result::deleted();
  6908. }
  6909. // [...] Let xi be an lvalue denoting the ith element [...]
  6910. OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
  6911. Expr *Args[] = {&Xi, &Xi};
  6912. // All operators start by trying to apply that same operator recursively.
  6913. OverloadedOperatorKind OO = FD->getOverloadedOperator();
  6914. assert(OO != OO_None && "not an overloaded operator!");
  6915. return visitBinaryOperator(OO, Args, Subobj);
  6916. }
  6917. Result
  6918. visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
  6919. Subobject Subobj,
  6920. OverloadCandidateSet *SpaceshipCandidates = nullptr) {
  6921. // Note that there is no need to consider rewritten candidates here if
  6922. // we've already found there is no viable 'operator<=>' candidate (and are
  6923. // considering synthesizing a '<=>' from '==' and '<').
  6924. OverloadCandidateSet CandidateSet(
  6925. FD->getLocation(), OverloadCandidateSet::CSK_Operator,
  6926. OverloadCandidateSet::OperatorRewriteInfo(
  6927. OO, FD->getLocation(),
  6928. /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
  6929. /// C++2a [class.compare.default]p1 [P2002R0]:
  6930. /// [...] the defaulted function itself is never a candidate for overload
  6931. /// resolution [...]
  6932. CandidateSet.exclude(FD);
  6933. if (Args[0]->getType()->isOverloadableType())
  6934. S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
  6935. else
  6936. // FIXME: We determine whether this is a valid expression by checking to
  6937. // see if there's a viable builtin operator candidate for it. That isn't
  6938. // really what the rules ask us to do, but should give the right results.
  6939. S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
  6940. Result R;
  6941. OverloadCandidateSet::iterator Best;
  6942. switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
  6943. case OR_Success: {
  6944. // C++2a [class.compare.secondary]p2 [P2002R0]:
  6945. // The operator function [...] is defined as deleted if [...] the
  6946. // candidate selected by overload resolution is not a rewritten
  6947. // candidate.
  6948. if ((DCK == DefaultedComparisonKind::NotEqual ||
  6949. DCK == DefaultedComparisonKind::Relational) &&
  6950. !Best->RewriteKind) {
  6951. if (Diagnose == ExplainDeleted) {
  6952. if (Best->Function) {
  6953. S.Diag(Best->Function->getLocation(),
  6954. diag::note_defaulted_comparison_not_rewritten_callee)
  6955. << FD;
  6956. } else {
  6957. assert(Best->Conversions.size() == 2 &&
  6958. Best->Conversions[0].isUserDefined() &&
  6959. "non-user-defined conversion from class to built-in "
  6960. "comparison");
  6961. S.Diag(Best->Conversions[0]
  6962. .UserDefined.FoundConversionFunction.getDecl()
  6963. ->getLocation(),
  6964. diag::note_defaulted_comparison_not_rewritten_conversion)
  6965. << FD;
  6966. }
  6967. }
  6968. return Result::deleted();
  6969. }
  6970. // Throughout C++2a [class.compare]: if overload resolution does not
  6971. // result in a usable function, the candidate function is defined as
  6972. // deleted. This requires that we selected an accessible function.
  6973. //
  6974. // Note that this only considers the access of the function when named
  6975. // within the type of the subobject, and not the access path for any
  6976. // derived-to-base conversion.
  6977. CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
  6978. if (ArgClass && Best->FoundDecl.getDecl() &&
  6979. Best->FoundDecl.getDecl()->isCXXClassMember()) {
  6980. QualType ObjectType = Subobj.Kind == Subobject::Member
  6981. ? Args[0]->getType()
  6982. : S.Context.getRecordType(RD);
  6983. if (!S.isMemberAccessibleForDeletion(
  6984. ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
  6985. Diagnose == ExplainDeleted
  6986. ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
  6987. << FD << Subobj.Kind << Subobj.Decl
  6988. : S.PDiag()))
  6989. return Result::deleted();
  6990. }
  6991. bool NeedsDeducing =
  6992. OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
  6993. if (FunctionDecl *BestFD = Best->Function) {
  6994. // C++2a [class.compare.default]p3 [P2002R0]:
  6995. // A defaulted comparison function is constexpr-compatible if
  6996. // [...] no overlod resolution performed [...] results in a
  6997. // non-constexpr function.
  6998. assert(!BestFD->isDeleted() && "wrong overload resolution result");
  6999. // If it's not constexpr, explain why not.
  7000. if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
  7001. if (Subobj.Kind != Subobject::CompleteObject)
  7002. S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
  7003. << Subobj.Kind << Subobj.Decl;
  7004. S.Diag(BestFD->getLocation(),
  7005. diag::note_defaulted_comparison_not_constexpr_here);
  7006. // Bail out after explaining; we don't want any more notes.
  7007. return Result::deleted();
  7008. }
  7009. R.Constexpr &= BestFD->isConstexpr();
  7010. if (NeedsDeducing) {
  7011. // If any callee has an undeduced return type, deduce it now.
  7012. // FIXME: It's not clear how a failure here should be handled. For
  7013. // now, we produce an eager diagnostic, because that is forward
  7014. // compatible with most (all?) other reasonable options.
  7015. if (BestFD->getReturnType()->isUndeducedType() &&
  7016. S.DeduceReturnType(BestFD, FD->getLocation(),
  7017. /*Diagnose=*/false)) {
  7018. // Don't produce a duplicate error when asked to explain why the
  7019. // comparison is deleted: we diagnosed that when initially checking
  7020. // the defaulted operator.
  7021. if (Diagnose == NoDiagnostics) {
  7022. S.Diag(
  7023. FD->getLocation(),
  7024. diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
  7025. << Subobj.Kind << Subobj.Decl;
  7026. S.Diag(
  7027. Subobj.Loc,
  7028. diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
  7029. << Subobj.Kind << Subobj.Decl;
  7030. S.Diag(BestFD->getLocation(),
  7031. diag::note_defaulted_comparison_cannot_deduce_callee)
  7032. << Subobj.Kind << Subobj.Decl;
  7033. }
  7034. return Result::deleted();
  7035. }
  7036. auto *Info = S.Context.CompCategories.lookupInfoForType(
  7037. BestFD->getCallResultType());
  7038. if (!Info) {
  7039. if (Diagnose == ExplainDeleted) {
  7040. S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
  7041. << Subobj.Kind << Subobj.Decl
  7042. << BestFD->getCallResultType().withoutLocalFastQualifiers();
  7043. S.Diag(BestFD->getLocation(),
  7044. diag::note_defaulted_comparison_cannot_deduce_callee)
  7045. << Subobj.Kind << Subobj.Decl;
  7046. }
  7047. return Result::deleted();
  7048. }
  7049. R.Category = Info->Kind;
  7050. }
  7051. } else {
  7052. QualType T = Best->BuiltinParamTypes[0];
  7053. assert(T == Best->BuiltinParamTypes[1] &&
  7054. "builtin comparison for different types?");
  7055. assert(Best->BuiltinParamTypes[2].isNull() &&
  7056. "invalid builtin comparison");
  7057. if (NeedsDeducing) {
  7058. std::optional<ComparisonCategoryType> Cat =
  7059. getComparisonCategoryForBuiltinCmp(T);
  7060. assert(Cat && "no category for builtin comparison?");
  7061. R.Category = *Cat;
  7062. }
  7063. }
  7064. // Note that we might be rewriting to a different operator. That call is
  7065. // not considered until we come to actually build the comparison function.
  7066. break;
  7067. }
  7068. case OR_Ambiguous:
  7069. if (Diagnose == ExplainDeleted) {
  7070. unsigned Kind = 0;
  7071. if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
  7072. Kind = OO == OO_EqualEqual ? 1 : 2;
  7073. CandidateSet.NoteCandidates(
  7074. PartialDiagnosticAt(
  7075. Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
  7076. << FD << Kind << Subobj.Kind << Subobj.Decl),
  7077. S, OCD_AmbiguousCandidates, Args);
  7078. }
  7079. R = Result::deleted();
  7080. break;
  7081. case OR_Deleted:
  7082. if (Diagnose == ExplainDeleted) {
  7083. if ((DCK == DefaultedComparisonKind::NotEqual ||
  7084. DCK == DefaultedComparisonKind::Relational) &&
  7085. !Best->RewriteKind) {
  7086. S.Diag(Best->Function->getLocation(),
  7087. diag::note_defaulted_comparison_not_rewritten_callee)
  7088. << FD;
  7089. } else {
  7090. S.Diag(Subobj.Loc,
  7091. diag::note_defaulted_comparison_calls_deleted)
  7092. << FD << Subobj.Kind << Subobj.Decl;
  7093. S.NoteDeletedFunction(Best->Function);
  7094. }
  7095. }
  7096. R = Result::deleted();
  7097. break;
  7098. case OR_No_Viable_Function:
  7099. // If there's no usable candidate, we're done unless we can rewrite a
  7100. // '<=>' in terms of '==' and '<'.
  7101. if (OO == OO_Spaceship &&
  7102. S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
  7103. // For any kind of comparison category return type, we need a usable
  7104. // '==' and a usable '<'.
  7105. if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
  7106. &CandidateSet)))
  7107. R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
  7108. break;
  7109. }
  7110. if (Diagnose == ExplainDeleted) {
  7111. S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
  7112. << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
  7113. // For a three-way comparison, list both the candidates for the
  7114. // original operator and the candidates for the synthesized operator.
  7115. if (SpaceshipCandidates) {
  7116. SpaceshipCandidates->NoteCandidates(
  7117. S, Args,
  7118. SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
  7119. Args, FD->getLocation()));
  7120. S.Diag(Subobj.Loc,
  7121. diag::note_defaulted_comparison_no_viable_function_synthesized)
  7122. << (OO == OO_EqualEqual ? 0 : 1);
  7123. }
  7124. CandidateSet.NoteCandidates(
  7125. S, Args,
  7126. CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
  7127. FD->getLocation()));
  7128. }
  7129. R = Result::deleted();
  7130. break;
  7131. }
  7132. return R;
  7133. }
  7134. };
  7135. /// A list of statements.
  7136. struct StmtListResult {
  7137. bool IsInvalid = false;
  7138. llvm::SmallVector<Stmt*, 16> Stmts;
  7139. bool add(const StmtResult &S) {
  7140. IsInvalid |= S.isInvalid();
  7141. if (IsInvalid)
  7142. return true;
  7143. Stmts.push_back(S.get());
  7144. return false;
  7145. }
  7146. };
  7147. /// A visitor over the notional body of a defaulted comparison that synthesizes
  7148. /// the actual body.
  7149. class DefaultedComparisonSynthesizer
  7150. : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
  7151. StmtListResult, StmtResult,
  7152. std::pair<ExprResult, ExprResult>> {
  7153. SourceLocation Loc;
  7154. unsigned ArrayDepth = 0;
  7155. public:
  7156. using Base = DefaultedComparisonVisitor;
  7157. using ExprPair = std::pair<ExprResult, ExprResult>;
  7158. friend Base;
  7159. DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
  7160. DefaultedComparisonKind DCK,
  7161. SourceLocation BodyLoc)
  7162. : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
  7163. /// Build a suitable function body for this defaulted comparison operator.
  7164. StmtResult build() {
  7165. Sema::CompoundScopeRAII CompoundScope(S);
  7166. StmtListResult Stmts = visit();
  7167. if (Stmts.IsInvalid)
  7168. return StmtError();
  7169. ExprResult RetVal;
  7170. switch (DCK) {
  7171. case DefaultedComparisonKind::None:
  7172. llvm_unreachable("not a defaulted comparison");
  7173. case DefaultedComparisonKind::Equal: {
  7174. // C++2a [class.eq]p3:
  7175. // [...] compar[e] the corresponding elements [...] until the first
  7176. // index i where xi == yi yields [...] false. If no such index exists,
  7177. // V is true. Otherwise, V is false.
  7178. //
  7179. // Join the comparisons with '&&'s and return the result. Use a right
  7180. // fold (traversing the conditions right-to-left), because that
  7181. // short-circuits more naturally.
  7182. auto OldStmts = std::move(Stmts.Stmts);
  7183. Stmts.Stmts.clear();
  7184. ExprResult CmpSoFar;
  7185. // Finish a particular comparison chain.
  7186. auto FinishCmp = [&] {
  7187. if (Expr *Prior = CmpSoFar.get()) {
  7188. // Convert the last expression to 'return ...;'
  7189. if (RetVal.isUnset() && Stmts.Stmts.empty())
  7190. RetVal = CmpSoFar;
  7191. // Convert any prior comparison to 'if (!(...)) return false;'
  7192. else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
  7193. return true;
  7194. CmpSoFar = ExprResult();
  7195. }
  7196. return false;
  7197. };
  7198. for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
  7199. Expr *E = dyn_cast<Expr>(EAsStmt);
  7200. if (!E) {
  7201. // Found an array comparison.
  7202. if (FinishCmp() || Stmts.add(EAsStmt))
  7203. return StmtError();
  7204. continue;
  7205. }
  7206. if (CmpSoFar.isUnset()) {
  7207. CmpSoFar = E;
  7208. continue;
  7209. }
  7210. CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
  7211. if (CmpSoFar.isInvalid())
  7212. return StmtError();
  7213. }
  7214. if (FinishCmp())
  7215. return StmtError();
  7216. std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
  7217. // If no such index exists, V is true.
  7218. if (RetVal.isUnset())
  7219. RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
  7220. break;
  7221. }
  7222. case DefaultedComparisonKind::ThreeWay: {
  7223. // Per C++2a [class.spaceship]p3, as a fallback add:
  7224. // return static_cast<R>(std::strong_ordering::equal);
  7225. QualType StrongOrdering = S.CheckComparisonCategoryType(
  7226. ComparisonCategoryType::StrongOrdering, Loc,
  7227. Sema::ComparisonCategoryUsage::DefaultedOperator);
  7228. if (StrongOrdering.isNull())
  7229. return StmtError();
  7230. VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
  7231. .getValueInfo(ComparisonCategoryResult::Equal)
  7232. ->VD;
  7233. RetVal = getDecl(EqualVD);
  7234. if (RetVal.isInvalid())
  7235. return StmtError();
  7236. RetVal = buildStaticCastToR(RetVal.get());
  7237. break;
  7238. }
  7239. case DefaultedComparisonKind::NotEqual:
  7240. case DefaultedComparisonKind::Relational:
  7241. RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
  7242. break;
  7243. }
  7244. // Build the final return statement.
  7245. if (RetVal.isInvalid())
  7246. return StmtError();
  7247. StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
  7248. if (ReturnStmt.isInvalid())
  7249. return StmtError();
  7250. Stmts.Stmts.push_back(ReturnStmt.get());
  7251. return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
  7252. }
  7253. private:
  7254. ExprResult getDecl(ValueDecl *VD) {
  7255. return S.BuildDeclarationNameExpr(
  7256. CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
  7257. }
  7258. ExprResult getParam(unsigned I) {
  7259. ParmVarDecl *PD = FD->getParamDecl(I);
  7260. return getDecl(PD);
  7261. }
  7262. ExprPair getCompleteObject() {
  7263. unsigned Param = 0;
  7264. ExprResult LHS;
  7265. if (isa<CXXMethodDecl>(FD)) {
  7266. // LHS is '*this'.
  7267. LHS = S.ActOnCXXThis(Loc);
  7268. if (!LHS.isInvalid())
  7269. LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
  7270. } else {
  7271. LHS = getParam(Param++);
  7272. }
  7273. ExprResult RHS = getParam(Param++);
  7274. assert(Param == FD->getNumParams());
  7275. return {LHS, RHS};
  7276. }
  7277. ExprPair getBase(CXXBaseSpecifier *Base) {
  7278. ExprPair Obj = getCompleteObject();
  7279. if (Obj.first.isInvalid() || Obj.second.isInvalid())
  7280. return {ExprError(), ExprError()};
  7281. CXXCastPath Path = {Base};
  7282. return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
  7283. CK_DerivedToBase, VK_LValue, &Path),
  7284. S.ImpCastExprToType(Obj.second.get(), Base->getType(),
  7285. CK_DerivedToBase, VK_LValue, &Path)};
  7286. }
  7287. ExprPair getField(FieldDecl *Field) {
  7288. ExprPair Obj = getCompleteObject();
  7289. if (Obj.first.isInvalid() || Obj.second.isInvalid())
  7290. return {ExprError(), ExprError()};
  7291. DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
  7292. DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
  7293. return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
  7294. CXXScopeSpec(), Field, Found, NameInfo),
  7295. S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
  7296. CXXScopeSpec(), Field, Found, NameInfo)};
  7297. }
  7298. // FIXME: When expanding a subobject, register a note in the code synthesis
  7299. // stack to say which subobject we're comparing.
  7300. StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
  7301. if (Cond.isInvalid())
  7302. return StmtError();
  7303. ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
  7304. if (NotCond.isInvalid())
  7305. return StmtError();
  7306. ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
  7307. assert(!False.isInvalid() && "should never fail");
  7308. StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
  7309. if (ReturnFalse.isInvalid())
  7310. return StmtError();
  7311. return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
  7312. S.ActOnCondition(nullptr, Loc, NotCond.get(),
  7313. Sema::ConditionKind::Boolean),
  7314. Loc, ReturnFalse.get(), SourceLocation(), nullptr);
  7315. }
  7316. StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
  7317. ExprPair Subobj) {
  7318. QualType SizeType = S.Context.getSizeType();
  7319. Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
  7320. // Build 'size_t i$n = 0'.
  7321. IdentifierInfo *IterationVarName = nullptr;
  7322. {
  7323. SmallString<8> Str;
  7324. llvm::raw_svector_ostream OS(Str);
  7325. OS << "i" << ArrayDepth;
  7326. IterationVarName = &S.Context.Idents.get(OS.str());
  7327. }
  7328. VarDecl *IterationVar = VarDecl::Create(
  7329. S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
  7330. S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
  7331. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  7332. IterationVar->setInit(
  7333. IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  7334. Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
  7335. auto IterRef = [&] {
  7336. ExprResult Ref = S.BuildDeclarationNameExpr(
  7337. CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
  7338. IterationVar);
  7339. assert(!Ref.isInvalid() && "can't reference our own variable?");
  7340. return Ref.get();
  7341. };
  7342. // Build 'i$n != Size'.
  7343. ExprResult Cond = S.CreateBuiltinBinOp(
  7344. Loc, BO_NE, IterRef(),
  7345. IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
  7346. assert(!Cond.isInvalid() && "should never fail");
  7347. // Build '++i$n'.
  7348. ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
  7349. assert(!Inc.isInvalid() && "should never fail");
  7350. // Build 'a[i$n]' and 'b[i$n]'.
  7351. auto Index = [&](ExprResult E) {
  7352. if (E.isInvalid())
  7353. return ExprError();
  7354. return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
  7355. };
  7356. Subobj.first = Index(Subobj.first);
  7357. Subobj.second = Index(Subobj.second);
  7358. // Compare the array elements.
  7359. ++ArrayDepth;
  7360. StmtResult Substmt = visitSubobject(Type, Subobj);
  7361. --ArrayDepth;
  7362. if (Substmt.isInvalid())
  7363. return StmtError();
  7364. // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
  7365. // For outer levels or for an 'operator<=>' we already have a suitable
  7366. // statement that returns as necessary.
  7367. if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
  7368. assert(DCK == DefaultedComparisonKind::Equal &&
  7369. "should have non-expression statement");
  7370. Substmt = buildIfNotCondReturnFalse(ElemCmp);
  7371. if (Substmt.isInvalid())
  7372. return StmtError();
  7373. }
  7374. // Build 'for (...) ...'
  7375. return S.ActOnForStmt(Loc, Loc, Init,
  7376. S.ActOnCondition(nullptr, Loc, Cond.get(),
  7377. Sema::ConditionKind::Boolean),
  7378. S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
  7379. Substmt.get());
  7380. }
  7381. StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
  7382. if (Obj.first.isInvalid() || Obj.second.isInvalid())
  7383. return StmtError();
  7384. OverloadedOperatorKind OO = FD->getOverloadedOperator();
  7385. BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
  7386. ExprResult Op;
  7387. if (Type->isOverloadableType())
  7388. Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
  7389. Obj.second.get(), /*PerformADL=*/true,
  7390. /*AllowRewrittenCandidates=*/true, FD);
  7391. else
  7392. Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
  7393. if (Op.isInvalid())
  7394. return StmtError();
  7395. switch (DCK) {
  7396. case DefaultedComparisonKind::None:
  7397. llvm_unreachable("not a defaulted comparison");
  7398. case DefaultedComparisonKind::Equal:
  7399. // Per C++2a [class.eq]p2, each comparison is individually contextually
  7400. // converted to bool.
  7401. Op = S.PerformContextuallyConvertToBool(Op.get());
  7402. if (Op.isInvalid())
  7403. return StmtError();
  7404. return Op.get();
  7405. case DefaultedComparisonKind::ThreeWay: {
  7406. // Per C++2a [class.spaceship]p3, form:
  7407. // if (R cmp = static_cast<R>(op); cmp != 0)
  7408. // return cmp;
  7409. QualType R = FD->getReturnType();
  7410. Op = buildStaticCastToR(Op.get());
  7411. if (Op.isInvalid())
  7412. return StmtError();
  7413. // R cmp = ...;
  7414. IdentifierInfo *Name = &S.Context.Idents.get("cmp");
  7415. VarDecl *VD =
  7416. VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
  7417. S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
  7418. S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
  7419. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
  7420. // cmp != 0
  7421. ExprResult VDRef = getDecl(VD);
  7422. if (VDRef.isInvalid())
  7423. return StmtError();
  7424. llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
  7425. Expr *Zero =
  7426. IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
  7427. ExprResult Comp;
  7428. if (VDRef.get()->getType()->isOverloadableType())
  7429. Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
  7430. true, FD);
  7431. else
  7432. Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
  7433. if (Comp.isInvalid())
  7434. return StmtError();
  7435. Sema::ConditionResult Cond = S.ActOnCondition(
  7436. nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
  7437. if (Cond.isInvalid())
  7438. return StmtError();
  7439. // return cmp;
  7440. VDRef = getDecl(VD);
  7441. if (VDRef.isInvalid())
  7442. return StmtError();
  7443. StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
  7444. if (ReturnStmt.isInvalid())
  7445. return StmtError();
  7446. // if (...)
  7447. return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
  7448. Loc, ReturnStmt.get(),
  7449. /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
  7450. }
  7451. case DefaultedComparisonKind::NotEqual:
  7452. case DefaultedComparisonKind::Relational:
  7453. // C++2a [class.compare.secondary]p2:
  7454. // Otherwise, the operator function yields x @ y.
  7455. return Op.get();
  7456. }
  7457. llvm_unreachable("");
  7458. }
  7459. /// Build "static_cast<R>(E)".
  7460. ExprResult buildStaticCastToR(Expr *E) {
  7461. QualType R = FD->getReturnType();
  7462. assert(!R->isUndeducedType() && "type should have been deduced already");
  7463. // Don't bother forming a no-op cast in the common case.
  7464. if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
  7465. return E;
  7466. return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
  7467. S.Context.getTrivialTypeSourceInfo(R, Loc), E,
  7468. SourceRange(Loc, Loc), SourceRange(Loc, Loc));
  7469. }
  7470. };
  7471. }
  7472. /// Perform the unqualified lookups that might be needed to form a defaulted
  7473. /// comparison function for the given operator.
  7474. static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
  7475. UnresolvedSetImpl &Operators,
  7476. OverloadedOperatorKind Op) {
  7477. auto Lookup = [&](OverloadedOperatorKind OO) {
  7478. Self.LookupOverloadedOperatorName(OO, S, Operators);
  7479. };
  7480. // Every defaulted operator looks up itself.
  7481. Lookup(Op);
  7482. // ... and the rewritten form of itself, if any.
  7483. if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
  7484. Lookup(ExtraOp);
  7485. // For 'operator<=>', we also form a 'cmp != 0' expression, and might
  7486. // synthesize a three-way comparison from '<' and '=='. In a dependent
  7487. // context, we also need to look up '==' in case we implicitly declare a
  7488. // defaulted 'operator=='.
  7489. if (Op == OO_Spaceship) {
  7490. Lookup(OO_ExclaimEqual);
  7491. Lookup(OO_Less);
  7492. Lookup(OO_EqualEqual);
  7493. }
  7494. }
  7495. bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
  7496. DefaultedComparisonKind DCK) {
  7497. assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
  7498. // Perform any unqualified lookups we're going to need to default this
  7499. // function.
  7500. if (S) {
  7501. UnresolvedSet<32> Operators;
  7502. lookupOperatorsForDefaultedComparison(*this, S, Operators,
  7503. FD->getOverloadedOperator());
  7504. FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
  7505. Context, Operators.pairs()));
  7506. }
  7507. // C++2a [class.compare.default]p1:
  7508. // A defaulted comparison operator function for some class C shall be a
  7509. // non-template function declared in the member-specification of C that is
  7510. // -- a non-static const member of C having one parameter of type
  7511. // const C&, or
  7512. // -- a friend of C having two parameters of type const C& or two
  7513. // parameters of type C.
  7514. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
  7515. bool IsMethod = isa<CXXMethodDecl>(FD);
  7516. if (IsMethod) {
  7517. auto *MD = cast<CXXMethodDecl>(FD);
  7518. assert(!MD->isStatic() && "comparison function cannot be a static member");
  7519. // If we're out-of-class, this is the class we're comparing.
  7520. if (!RD)
  7521. RD = MD->getParent();
  7522. if (!MD->isConst()) {
  7523. SourceLocation InsertLoc;
  7524. if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
  7525. InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
  7526. // Don't diagnose an implicit 'operator=='; we will have diagnosed the
  7527. // corresponding defaulted 'operator<=>' already.
  7528. if (!MD->isImplicit()) {
  7529. Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
  7530. << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
  7531. }
  7532. // Add the 'const' to the type to recover.
  7533. const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
  7534. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  7535. EPI.TypeQuals.addConst();
  7536. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  7537. FPT->getParamTypes(), EPI));
  7538. }
  7539. }
  7540. if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
  7541. // Let's not worry about using a variadic template pack here -- who would do
  7542. // such a thing?
  7543. Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
  7544. << int(IsMethod) << int(DCK);
  7545. return true;
  7546. }
  7547. const ParmVarDecl *KnownParm = nullptr;
  7548. for (const ParmVarDecl *Param : FD->parameters()) {
  7549. QualType ParmTy = Param->getType();
  7550. if (ParmTy->isDependentType())
  7551. continue;
  7552. if (!KnownParm) {
  7553. auto CTy = ParmTy;
  7554. // Is it `T const &`?
  7555. bool Ok = !IsMethod;
  7556. QualType ExpectedTy;
  7557. if (RD)
  7558. ExpectedTy = Context.getRecordType(RD);
  7559. if (auto *Ref = CTy->getAs<ReferenceType>()) {
  7560. CTy = Ref->getPointeeType();
  7561. if (RD)
  7562. ExpectedTy.addConst();
  7563. Ok = true;
  7564. }
  7565. // Is T a class?
  7566. if (!Ok) {
  7567. } else if (RD) {
  7568. if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
  7569. Ok = false;
  7570. } else if (auto *CRD = CTy->getAsRecordDecl()) {
  7571. RD = cast<CXXRecordDecl>(CRD);
  7572. } else {
  7573. Ok = false;
  7574. }
  7575. if (Ok) {
  7576. KnownParm = Param;
  7577. } else {
  7578. // Don't diagnose an implicit 'operator=='; we will have diagnosed the
  7579. // corresponding defaulted 'operator<=>' already.
  7580. if (!FD->isImplicit()) {
  7581. if (RD) {
  7582. QualType PlainTy = Context.getRecordType(RD);
  7583. QualType RefTy =
  7584. Context.getLValueReferenceType(PlainTy.withConst());
  7585. Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
  7586. << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
  7587. << Param->getSourceRange();
  7588. } else {
  7589. assert(!IsMethod && "should know expected type for method");
  7590. Diag(FD->getLocation(),
  7591. diag::err_defaulted_comparison_param_unknown)
  7592. << int(DCK) << ParmTy << Param->getSourceRange();
  7593. }
  7594. }
  7595. return true;
  7596. }
  7597. } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
  7598. Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
  7599. << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
  7600. << ParmTy << Param->getSourceRange();
  7601. return true;
  7602. }
  7603. }
  7604. assert(RD && "must have determined class");
  7605. if (IsMethod) {
  7606. } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  7607. // In-class, must be a friend decl.
  7608. assert(FD->getFriendObjectKind() && "expected a friend declaration");
  7609. } else {
  7610. // Out of class, require the defaulted comparison to be a friend (of a
  7611. // complete type).
  7612. if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
  7613. diag::err_defaulted_comparison_not_friend, int(DCK),
  7614. int(1)))
  7615. return true;
  7616. if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
  7617. return FD->getCanonicalDecl() ==
  7618. F->getFriendDecl()->getCanonicalDecl();
  7619. })) {
  7620. Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
  7621. << int(DCK) << int(0) << RD;
  7622. Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
  7623. return true;
  7624. }
  7625. }
  7626. // C++2a [class.eq]p1, [class.rel]p1:
  7627. // A [defaulted comparison other than <=>] shall have a declared return
  7628. // type bool.
  7629. if (DCK != DefaultedComparisonKind::ThreeWay &&
  7630. !FD->getDeclaredReturnType()->isDependentType() &&
  7631. !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
  7632. Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
  7633. << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
  7634. << FD->getReturnTypeSourceRange();
  7635. return true;
  7636. }
  7637. // C++2a [class.spaceship]p2 [P2002R0]:
  7638. // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
  7639. // R shall not contain a placeholder type.
  7640. if (QualType RT = FD->getDeclaredReturnType();
  7641. DCK == DefaultedComparisonKind::ThreeWay &&
  7642. RT->getContainedDeducedType() &&
  7643. (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
  7644. RT->getContainedAutoType()->isConstrained())) {
  7645. Diag(FD->getLocation(),
  7646. diag::err_defaulted_comparison_deduced_return_type_not_auto)
  7647. << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
  7648. << FD->getReturnTypeSourceRange();
  7649. return true;
  7650. }
  7651. // For a defaulted function in a dependent class, defer all remaining checks
  7652. // until instantiation.
  7653. if (RD->isDependentType())
  7654. return false;
  7655. // Determine whether the function should be defined as deleted.
  7656. DefaultedComparisonInfo Info =
  7657. DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
  7658. bool First = FD == FD->getCanonicalDecl();
  7659. if (!First) {
  7660. if (Info.Deleted) {
  7661. // C++11 [dcl.fct.def.default]p4:
  7662. // [For a] user-provided explicitly-defaulted function [...] if such a
  7663. // function is implicitly defined as deleted, the program is ill-formed.
  7664. //
  7665. // This is really just a consequence of the general rule that you can
  7666. // only delete a function on its first declaration.
  7667. Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
  7668. << FD->isImplicit() << (int)DCK;
  7669. DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
  7670. DefaultedComparisonAnalyzer::ExplainDeleted)
  7671. .visit();
  7672. return true;
  7673. }
  7674. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  7675. // C++20 [class.compare.default]p1:
  7676. // [...] A definition of a comparison operator as defaulted that appears
  7677. // in a class shall be the first declaration of that function.
  7678. Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
  7679. << (int)DCK;
  7680. Diag(FD->getCanonicalDecl()->getLocation(),
  7681. diag::note_previous_declaration);
  7682. return true;
  7683. }
  7684. }
  7685. // If we want to delete the function, then do so; there's nothing else to
  7686. // check in that case.
  7687. if (Info.Deleted) {
  7688. SetDeclDeleted(FD, FD->getLocation());
  7689. if (!inTemplateInstantiation() && !FD->isImplicit()) {
  7690. Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
  7691. << (int)DCK;
  7692. DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
  7693. DefaultedComparisonAnalyzer::ExplainDeleted)
  7694. .visit();
  7695. if (FD->getDefaultLoc().isValid())
  7696. Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
  7697. << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
  7698. }
  7699. return false;
  7700. }
  7701. // C++2a [class.spaceship]p2:
  7702. // The return type is deduced as the common comparison type of R0, R1, ...
  7703. if (DCK == DefaultedComparisonKind::ThreeWay &&
  7704. FD->getDeclaredReturnType()->isUndeducedAutoType()) {
  7705. SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
  7706. if (RetLoc.isInvalid())
  7707. RetLoc = FD->getBeginLoc();
  7708. // FIXME: Should we really care whether we have the complete type and the
  7709. // 'enumerator' constants here? A forward declaration seems sufficient.
  7710. QualType Cat = CheckComparisonCategoryType(
  7711. Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
  7712. if (Cat.isNull())
  7713. return true;
  7714. Context.adjustDeducedFunctionResultType(
  7715. FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
  7716. }
  7717. // C++2a [dcl.fct.def.default]p3 [P2002R0]:
  7718. // An explicitly-defaulted function that is not defined as deleted may be
  7719. // declared constexpr or consteval only if it is constexpr-compatible.
  7720. // C++2a [class.compare.default]p3 [P2002R0]:
  7721. // A defaulted comparison function is constexpr-compatible if it satisfies
  7722. // the requirements for a constexpr function [...]
  7723. // The only relevant requirements are that the parameter and return types are
  7724. // literal types. The remaining conditions are checked by the analyzer.
  7725. if (FD->isConstexpr()) {
  7726. if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
  7727. CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
  7728. !Info.Constexpr) {
  7729. Diag(FD->getBeginLoc(),
  7730. diag::err_incorrect_defaulted_comparison_constexpr)
  7731. << FD->isImplicit() << (int)DCK << FD->isConsteval();
  7732. DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
  7733. DefaultedComparisonAnalyzer::ExplainConstexpr)
  7734. .visit();
  7735. }
  7736. }
  7737. // C++2a [dcl.fct.def.default]p3 [P2002R0]:
  7738. // If a constexpr-compatible function is explicitly defaulted on its first
  7739. // declaration, it is implicitly considered to be constexpr.
  7740. // FIXME: Only applying this to the first declaration seems problematic, as
  7741. // simple reorderings can affect the meaning of the program.
  7742. if (First && !FD->isConstexpr() && Info.Constexpr)
  7743. FD->setConstexprKind(ConstexprSpecKind::Constexpr);
  7744. // C++2a [except.spec]p3:
  7745. // If a declaration of a function does not have a noexcept-specifier
  7746. // [and] is defaulted on its first declaration, [...] the exception
  7747. // specification is as specified below
  7748. if (FD->getExceptionSpecType() == EST_None) {
  7749. auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  7750. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  7751. EPI.ExceptionSpec.Type = EST_Unevaluated;
  7752. EPI.ExceptionSpec.SourceDecl = FD;
  7753. FD->setType(Context.getFunctionType(FPT->getReturnType(),
  7754. FPT->getParamTypes(), EPI));
  7755. }
  7756. return false;
  7757. }
  7758. void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
  7759. FunctionDecl *Spaceship) {
  7760. Sema::CodeSynthesisContext Ctx;
  7761. Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
  7762. Ctx.PointOfInstantiation = Spaceship->getEndLoc();
  7763. Ctx.Entity = Spaceship;
  7764. pushCodeSynthesisContext(Ctx);
  7765. if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
  7766. EqualEqual->setImplicit();
  7767. popCodeSynthesisContext();
  7768. }
  7769. void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
  7770. DefaultedComparisonKind DCK) {
  7771. assert(FD->isDefaulted() && !FD->isDeleted() &&
  7772. !FD->doesThisDeclarationHaveABody());
  7773. if (FD->willHaveBody() || FD->isInvalidDecl())
  7774. return;
  7775. SynthesizedFunctionScope Scope(*this, FD);
  7776. // Add a context note for diagnostics produced after this point.
  7777. Scope.addContextNote(UseLoc);
  7778. {
  7779. // Build and set up the function body.
  7780. // The first parameter has type maybe-ref-to maybe-const T, use that to get
  7781. // the type of the class being compared.
  7782. auto PT = FD->getParamDecl(0)->getType();
  7783. CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
  7784. SourceLocation BodyLoc =
  7785. FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
  7786. StmtResult Body =
  7787. DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
  7788. if (Body.isInvalid()) {
  7789. FD->setInvalidDecl();
  7790. return;
  7791. }
  7792. FD->setBody(Body.get());
  7793. FD->markUsed(Context);
  7794. }
  7795. // The exception specification is needed because we are defining the
  7796. // function. Note that this will reuse the body we just built.
  7797. ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
  7798. if (ASTMutationListener *L = getASTMutationListener())
  7799. L->CompletedImplicitDefinition(FD);
  7800. }
  7801. static Sema::ImplicitExceptionSpecification
  7802. ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
  7803. FunctionDecl *FD,
  7804. Sema::DefaultedComparisonKind DCK) {
  7805. ComputingExceptionSpec CES(S, FD, Loc);
  7806. Sema::ImplicitExceptionSpecification ExceptSpec(S);
  7807. if (FD->isInvalidDecl())
  7808. return ExceptSpec;
  7809. // The common case is that we just defined the comparison function. In that
  7810. // case, just look at whether the body can throw.
  7811. if (FD->hasBody()) {
  7812. ExceptSpec.CalledStmt(FD->getBody());
  7813. } else {
  7814. // Otherwise, build a body so we can check it. This should ideally only
  7815. // happen when we're not actually marking the function referenced. (This is
  7816. // only really important for efficiency: we don't want to build and throw
  7817. // away bodies for comparison functions more than we strictly need to.)
  7818. // Pretend to synthesize the function body in an unevaluated context.
  7819. // Note that we can't actually just go ahead and define the function here:
  7820. // we are not permitted to mark its callees as referenced.
  7821. Sema::SynthesizedFunctionScope Scope(S, FD);
  7822. EnterExpressionEvaluationContext Context(
  7823. S, Sema::ExpressionEvaluationContext::Unevaluated);
  7824. CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
  7825. SourceLocation BodyLoc =
  7826. FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
  7827. StmtResult Body =
  7828. DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
  7829. if (!Body.isInvalid())
  7830. ExceptSpec.CalledStmt(Body.get());
  7831. // FIXME: Can we hold onto this body and just transform it to potentially
  7832. // evaluated when we're asked to define the function rather than rebuilding
  7833. // it? Either that, or we should only build the bits of the body that we
  7834. // need (the expressions, not the statements).
  7835. }
  7836. return ExceptSpec;
  7837. }
  7838. void Sema::CheckDelayedMemberExceptionSpecs() {
  7839. decltype(DelayedOverridingExceptionSpecChecks) Overriding;
  7840. decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
  7841. std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
  7842. std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
  7843. // Perform any deferred checking of exception specifications for virtual
  7844. // destructors.
  7845. for (auto &Check : Overriding)
  7846. CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
  7847. // Perform any deferred checking of exception specifications for befriended
  7848. // special members.
  7849. for (auto &Check : Equivalent)
  7850. CheckEquivalentExceptionSpec(Check.second, Check.first);
  7851. }
  7852. namespace {
  7853. /// CRTP base class for visiting operations performed by a special member
  7854. /// function (or inherited constructor).
  7855. template<typename Derived>
  7856. struct SpecialMemberVisitor {
  7857. Sema &S;
  7858. CXXMethodDecl *MD;
  7859. Sema::CXXSpecialMember CSM;
  7860. Sema::InheritedConstructorInfo *ICI;
  7861. // Properties of the special member, computed for convenience.
  7862. bool IsConstructor = false, IsAssignment = false, ConstArg = false;
  7863. SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  7864. Sema::InheritedConstructorInfo *ICI)
  7865. : S(S), MD(MD), CSM(CSM), ICI(ICI) {
  7866. switch (CSM) {
  7867. case Sema::CXXDefaultConstructor:
  7868. case Sema::CXXCopyConstructor:
  7869. case Sema::CXXMoveConstructor:
  7870. IsConstructor = true;
  7871. break;
  7872. case Sema::CXXCopyAssignment:
  7873. case Sema::CXXMoveAssignment:
  7874. IsAssignment = true;
  7875. break;
  7876. case Sema::CXXDestructor:
  7877. break;
  7878. case Sema::CXXInvalid:
  7879. llvm_unreachable("invalid special member kind");
  7880. }
  7881. if (MD->getNumParams()) {
  7882. if (const ReferenceType *RT =
  7883. MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
  7884. ConstArg = RT->getPointeeType().isConstQualified();
  7885. }
  7886. }
  7887. Derived &getDerived() { return static_cast<Derived&>(*this); }
  7888. /// Is this a "move" special member?
  7889. bool isMove() const {
  7890. return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
  7891. }
  7892. /// Look up the corresponding special member in the given class.
  7893. Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
  7894. unsigned Quals, bool IsMutable) {
  7895. return lookupCallFromSpecialMember(S, Class, CSM, Quals,
  7896. ConstArg && !IsMutable);
  7897. }
  7898. /// Look up the constructor for the specified base class to see if it's
  7899. /// overridden due to this being an inherited constructor.
  7900. Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
  7901. if (!ICI)
  7902. return {};
  7903. assert(CSM == Sema::CXXDefaultConstructor);
  7904. auto *BaseCtor =
  7905. cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
  7906. if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
  7907. return MD;
  7908. return {};
  7909. }
  7910. /// A base or member subobject.
  7911. typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
  7912. /// Get the location to use for a subobject in diagnostics.
  7913. static SourceLocation getSubobjectLoc(Subobject Subobj) {
  7914. // FIXME: For an indirect virtual base, the direct base leading to
  7915. // the indirect virtual base would be a more useful choice.
  7916. if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
  7917. return B->getBaseTypeLoc();
  7918. else
  7919. return Subobj.get<FieldDecl*>()->getLocation();
  7920. }
  7921. enum BasesToVisit {
  7922. /// Visit all non-virtual (direct) bases.
  7923. VisitNonVirtualBases,
  7924. /// Visit all direct bases, virtual or not.
  7925. VisitDirectBases,
  7926. /// Visit all non-virtual bases, and all virtual bases if the class
  7927. /// is not abstract.
  7928. VisitPotentiallyConstructedBases,
  7929. /// Visit all direct or virtual bases.
  7930. VisitAllBases
  7931. };
  7932. // Visit the bases and members of the class.
  7933. bool visit(BasesToVisit Bases) {
  7934. CXXRecordDecl *RD = MD->getParent();
  7935. if (Bases == VisitPotentiallyConstructedBases)
  7936. Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
  7937. for (auto &B : RD->bases())
  7938. if ((Bases == VisitDirectBases || !B.isVirtual()) &&
  7939. getDerived().visitBase(&B))
  7940. return true;
  7941. if (Bases == VisitAllBases)
  7942. for (auto &B : RD->vbases())
  7943. if (getDerived().visitBase(&B))
  7944. return true;
  7945. for (auto *F : RD->fields())
  7946. if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
  7947. getDerived().visitField(F))
  7948. return true;
  7949. return false;
  7950. }
  7951. };
  7952. }
  7953. namespace {
  7954. struct SpecialMemberDeletionInfo
  7955. : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
  7956. bool Diagnose;
  7957. SourceLocation Loc;
  7958. bool AllFieldsAreConst;
  7959. SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
  7960. Sema::CXXSpecialMember CSM,
  7961. Sema::InheritedConstructorInfo *ICI, bool Diagnose)
  7962. : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
  7963. Loc(MD->getLocation()), AllFieldsAreConst(true) {}
  7964. bool inUnion() const { return MD->getParent()->isUnion(); }
  7965. Sema::CXXSpecialMember getEffectiveCSM() {
  7966. return ICI ? Sema::CXXInvalid : CSM;
  7967. }
  7968. bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
  7969. bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
  7970. bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
  7971. bool shouldDeleteForBase(CXXBaseSpecifier *Base);
  7972. bool shouldDeleteForField(FieldDecl *FD);
  7973. bool shouldDeleteForAllConstMembers();
  7974. bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  7975. unsigned Quals);
  7976. bool shouldDeleteForSubobjectCall(Subobject Subobj,
  7977. Sema::SpecialMemberOverloadResult SMOR,
  7978. bool IsDtorCallInCtor);
  7979. bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
  7980. };
  7981. }
  7982. /// Is the given special member inaccessible when used on the given
  7983. /// sub-object.
  7984. bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
  7985. CXXMethodDecl *target) {
  7986. /// If we're operating on a base class, the object type is the
  7987. /// type of this special member.
  7988. QualType objectTy;
  7989. AccessSpecifier access = target->getAccess();
  7990. if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
  7991. objectTy = S.Context.getTypeDeclType(MD->getParent());
  7992. access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
  7993. // If we're operating on a field, the object type is the type of the field.
  7994. } else {
  7995. objectTy = S.Context.getTypeDeclType(target->getParent());
  7996. }
  7997. return S.isMemberAccessibleForDeletion(
  7998. target->getParent(), DeclAccessPair::make(target, access), objectTy);
  7999. }
  8000. /// Check whether we should delete a special member due to the implicit
  8001. /// definition containing a call to a special member of a subobject.
  8002. bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
  8003. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
  8004. bool IsDtorCallInCtor) {
  8005. CXXMethodDecl *Decl = SMOR.getMethod();
  8006. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  8007. int DiagKind = -1;
  8008. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
  8009. DiagKind = !Decl ? 0 : 1;
  8010. else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  8011. DiagKind = 2;
  8012. else if (!isAccessible(Subobj, Decl))
  8013. DiagKind = 3;
  8014. else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
  8015. !Decl->isTrivial()) {
  8016. // A member of a union must have a trivial corresponding special member.
  8017. // As a weird special case, a destructor call from a union's constructor
  8018. // must be accessible and non-deleted, but need not be trivial. Such a
  8019. // destructor is never actually called, but is semantically checked as
  8020. // if it were.
  8021. DiagKind = 4;
  8022. }
  8023. if (DiagKind == -1)
  8024. return false;
  8025. if (Diagnose) {
  8026. if (Field) {
  8027. S.Diag(Field->getLocation(),
  8028. diag::note_deleted_special_member_class_subobject)
  8029. << getEffectiveCSM() << MD->getParent() << /*IsField*/true
  8030. << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
  8031. } else {
  8032. CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
  8033. S.Diag(Base->getBeginLoc(),
  8034. diag::note_deleted_special_member_class_subobject)
  8035. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  8036. << Base->getType() << DiagKind << IsDtorCallInCtor
  8037. << /*IsObjCPtr*/false;
  8038. }
  8039. if (DiagKind == 1)
  8040. S.NoteDeletedFunction(Decl);
  8041. // FIXME: Explain inaccessibility if DiagKind == 3.
  8042. }
  8043. return true;
  8044. }
  8045. /// Check whether we should delete a special member function due to having a
  8046. /// direct or virtual base class or non-static data member of class type M.
  8047. bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
  8048. CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
  8049. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  8050. bool IsMutable = Field && Field->isMutable();
  8051. // C++11 [class.ctor]p5:
  8052. // -- any direct or virtual base class, or non-static data member with no
  8053. // brace-or-equal-initializer, has class type M (or array thereof) and
  8054. // either M has no default constructor or overload resolution as applied
  8055. // to M's default constructor results in an ambiguity or in a function
  8056. // that is deleted or inaccessible
  8057. // C++11 [class.copy]p11, C++11 [class.copy]p23:
  8058. // -- a direct or virtual base class B that cannot be copied/moved because
  8059. // overload resolution, as applied to B's corresponding special member,
  8060. // results in an ambiguity or a function that is deleted or inaccessible
  8061. // from the defaulted special member
  8062. // C++11 [class.dtor]p5:
  8063. // -- any direct or virtual base class [...] has a type with a destructor
  8064. // that is deleted or inaccessible
  8065. if (!(CSM == Sema::CXXDefaultConstructor &&
  8066. Field && Field->hasInClassInitializer()) &&
  8067. shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
  8068. false))
  8069. return true;
  8070. // C++11 [class.ctor]p5, C++11 [class.copy]p11:
  8071. // -- any direct or virtual base class or non-static data member has a
  8072. // type with a destructor that is deleted or inaccessible
  8073. if (IsConstructor) {
  8074. Sema::SpecialMemberOverloadResult SMOR =
  8075. S.LookupSpecialMember(Class, Sema::CXXDestructor,
  8076. false, false, false, false, false);
  8077. if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
  8078. return true;
  8079. }
  8080. return false;
  8081. }
  8082. bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
  8083. FieldDecl *FD, QualType FieldType) {
  8084. // The defaulted special functions are defined as deleted if this is a variant
  8085. // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
  8086. // type under ARC.
  8087. if (!FieldType.hasNonTrivialObjCLifetime())
  8088. return false;
  8089. // Don't make the defaulted default constructor defined as deleted if the
  8090. // member has an in-class initializer.
  8091. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
  8092. return false;
  8093. if (Diagnose) {
  8094. auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
  8095. S.Diag(FD->getLocation(),
  8096. diag::note_deleted_special_member_class_subobject)
  8097. << getEffectiveCSM() << ParentClass << /*IsField*/true
  8098. << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
  8099. }
  8100. return true;
  8101. }
  8102. /// Check whether we should delete a special member function due to the class
  8103. /// having a particular direct or virtual base class.
  8104. bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
  8105. CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
  8106. // If program is correct, BaseClass cannot be null, but if it is, the error
  8107. // must be reported elsewhere.
  8108. if (!BaseClass)
  8109. return false;
  8110. // If we have an inheriting constructor, check whether we're calling an
  8111. // inherited constructor instead of a default constructor.
  8112. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  8113. if (auto *BaseCtor = SMOR.getMethod()) {
  8114. // Note that we do not check access along this path; other than that,
  8115. // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
  8116. // FIXME: Check that the base has a usable destructor! Sink this into
  8117. // shouldDeleteForClassSubobject.
  8118. if (BaseCtor->isDeleted() && Diagnose) {
  8119. S.Diag(Base->getBeginLoc(),
  8120. diag::note_deleted_special_member_class_subobject)
  8121. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  8122. << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
  8123. << /*IsObjCPtr*/false;
  8124. S.NoteDeletedFunction(BaseCtor);
  8125. }
  8126. return BaseCtor->isDeleted();
  8127. }
  8128. return shouldDeleteForClassSubobject(BaseClass, Base, 0);
  8129. }
  8130. /// Check whether we should delete a special member function due to the class
  8131. /// having a particular non-static data member.
  8132. bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
  8133. QualType FieldType = S.Context.getBaseElementType(FD->getType());
  8134. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  8135. if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
  8136. return true;
  8137. if (CSM == Sema::CXXDefaultConstructor) {
  8138. // For a default constructor, all references must be initialized in-class
  8139. // and, if a union, it must have a non-const member.
  8140. if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
  8141. if (Diagnose)
  8142. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  8143. << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
  8144. return true;
  8145. }
  8146. // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
  8147. // data member of const-qualified type (or array thereof) with no
  8148. // brace-or-equal-initializer is not const-default-constructible.
  8149. if (!inUnion() && FieldType.isConstQualified() &&
  8150. !FD->hasInClassInitializer() &&
  8151. (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
  8152. if (Diagnose)
  8153. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  8154. << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
  8155. return true;
  8156. }
  8157. if (inUnion() && !FieldType.isConstQualified())
  8158. AllFieldsAreConst = false;
  8159. } else if (CSM == Sema::CXXCopyConstructor) {
  8160. // For a copy constructor, data members must not be of rvalue reference
  8161. // type.
  8162. if (FieldType->isRValueReferenceType()) {
  8163. if (Diagnose)
  8164. S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
  8165. << MD->getParent() << FD << FieldType;
  8166. return true;
  8167. }
  8168. } else if (IsAssignment) {
  8169. // For an assignment operator, data members must not be of reference type.
  8170. if (FieldType->isReferenceType()) {
  8171. if (Diagnose)
  8172. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  8173. << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
  8174. return true;
  8175. }
  8176. if (!FieldRecord && FieldType.isConstQualified()) {
  8177. // C++11 [class.copy]p23:
  8178. // -- a non-static data member of const non-class type (or array thereof)
  8179. if (Diagnose)
  8180. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  8181. << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
  8182. return true;
  8183. }
  8184. }
  8185. if (FieldRecord) {
  8186. // Some additional restrictions exist on the variant members.
  8187. if (!inUnion() && FieldRecord->isUnion() &&
  8188. FieldRecord->isAnonymousStructOrUnion()) {
  8189. bool AllVariantFieldsAreConst = true;
  8190. // FIXME: Handle anonymous unions declared within anonymous unions.
  8191. for (auto *UI : FieldRecord->fields()) {
  8192. QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
  8193. if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
  8194. return true;
  8195. if (!UnionFieldType.isConstQualified())
  8196. AllVariantFieldsAreConst = false;
  8197. CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
  8198. if (UnionFieldRecord &&
  8199. shouldDeleteForClassSubobject(UnionFieldRecord, UI,
  8200. UnionFieldType.getCVRQualifiers()))
  8201. return true;
  8202. }
  8203. // At least one member in each anonymous union must be non-const
  8204. if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
  8205. !FieldRecord->field_empty()) {
  8206. if (Diagnose)
  8207. S.Diag(FieldRecord->getLocation(),
  8208. diag::note_deleted_default_ctor_all_const)
  8209. << !!ICI << MD->getParent() << /*anonymous union*/1;
  8210. return true;
  8211. }
  8212. // Don't check the implicit member of the anonymous union type.
  8213. // This is technically non-conformant but supported, and we have a
  8214. // diagnostic for this elsewhere.
  8215. return false;
  8216. }
  8217. if (shouldDeleteForClassSubobject(FieldRecord, FD,
  8218. FieldType.getCVRQualifiers()))
  8219. return true;
  8220. }
  8221. return false;
  8222. }
  8223. /// C++11 [class.ctor] p5:
  8224. /// A defaulted default constructor for a class X is defined as deleted if
  8225. /// X is a union and all of its variant members are of const-qualified type.
  8226. bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
  8227. // This is a silly definition, because it gives an empty union a deleted
  8228. // default constructor. Don't do that.
  8229. if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
  8230. bool AnyFields = false;
  8231. for (auto *F : MD->getParent()->fields())
  8232. if ((AnyFields = !F->isUnnamedBitfield()))
  8233. break;
  8234. if (!AnyFields)
  8235. return false;
  8236. if (Diagnose)
  8237. S.Diag(MD->getParent()->getLocation(),
  8238. diag::note_deleted_default_ctor_all_const)
  8239. << !!ICI << MD->getParent() << /*not anonymous union*/0;
  8240. return true;
  8241. }
  8242. return false;
  8243. }
  8244. /// Determine whether a defaulted special member function should be defined as
  8245. /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
  8246. /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
  8247. bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
  8248. InheritedConstructorInfo *ICI,
  8249. bool Diagnose) {
  8250. if (MD->isInvalidDecl())
  8251. return false;
  8252. CXXRecordDecl *RD = MD->getParent();
  8253. assert(!RD->isDependentType() && "do deletion after instantiation");
  8254. if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
  8255. return false;
  8256. // C++11 [expr.lambda.prim]p19:
  8257. // The closure type associated with a lambda-expression has a
  8258. // deleted (8.4.3) default constructor and a deleted copy
  8259. // assignment operator.
  8260. // C++2a adds back these operators if the lambda has no lambda-capture.
  8261. if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
  8262. (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
  8263. if (Diagnose)
  8264. Diag(RD->getLocation(), diag::note_lambda_decl);
  8265. return true;
  8266. }
  8267. // For an anonymous struct or union, the copy and assignment special members
  8268. // will never be used, so skip the check. For an anonymous union declared at
  8269. // namespace scope, the constructor and destructor are used.
  8270. if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
  8271. RD->isAnonymousStructOrUnion())
  8272. return false;
  8273. // C++11 [class.copy]p7, p18:
  8274. // If the class definition declares a move constructor or move assignment
  8275. // operator, an implicitly declared copy constructor or copy assignment
  8276. // operator is defined as deleted.
  8277. if (MD->isImplicit() &&
  8278. (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
  8279. CXXMethodDecl *UserDeclaredMove = nullptr;
  8280. // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
  8281. // deletion of the corresponding copy operation, not both copy operations.
  8282. // MSVC 2015 has adopted the standards conforming behavior.
  8283. bool DeletesOnlyMatchingCopy =
  8284. getLangOpts().MSVCCompat &&
  8285. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
  8286. if (RD->hasUserDeclaredMoveConstructor() &&
  8287. (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
  8288. if (!Diagnose) return true;
  8289. // Find any user-declared move constructor.
  8290. for (auto *I : RD->ctors()) {
  8291. if (I->isMoveConstructor()) {
  8292. UserDeclaredMove = I;
  8293. break;
  8294. }
  8295. }
  8296. assert(UserDeclaredMove);
  8297. } else if (RD->hasUserDeclaredMoveAssignment() &&
  8298. (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
  8299. if (!Diagnose) return true;
  8300. // Find any user-declared move assignment operator.
  8301. for (auto *I : RD->methods()) {
  8302. if (I->isMoveAssignmentOperator()) {
  8303. UserDeclaredMove = I;
  8304. break;
  8305. }
  8306. }
  8307. assert(UserDeclaredMove);
  8308. }
  8309. if (UserDeclaredMove) {
  8310. Diag(UserDeclaredMove->getLocation(),
  8311. diag::note_deleted_copy_user_declared_move)
  8312. << (CSM == CXXCopyAssignment) << RD
  8313. << UserDeclaredMove->isMoveAssignmentOperator();
  8314. return true;
  8315. }
  8316. }
  8317. // Do access control from the special member function
  8318. ContextRAII MethodContext(*this, MD);
  8319. // C++11 [class.dtor]p5:
  8320. // -- for a virtual destructor, lookup of the non-array deallocation function
  8321. // results in an ambiguity or in a function that is deleted or inaccessible
  8322. if (CSM == CXXDestructor && MD->isVirtual()) {
  8323. FunctionDecl *OperatorDelete = nullptr;
  8324. DeclarationName Name =
  8325. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  8326. if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
  8327. OperatorDelete, /*Diagnose*/false)) {
  8328. if (Diagnose)
  8329. Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
  8330. return true;
  8331. }
  8332. }
  8333. SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
  8334. // Per DR1611, do not consider virtual bases of constructors of abstract
  8335. // classes, since we are not going to construct them.
  8336. // Per DR1658, do not consider virtual bases of destructors of abstract
  8337. // classes either.
  8338. // Per DR2180, for assignment operators we only assign (and thus only
  8339. // consider) direct bases.
  8340. if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
  8341. : SMI.VisitPotentiallyConstructedBases))
  8342. return true;
  8343. if (SMI.shouldDeleteForAllConstMembers())
  8344. return true;
  8345. if (getLangOpts().CUDA) {
  8346. // We should delete the special member in CUDA mode if target inference
  8347. // failed.
  8348. // For inherited constructors (non-null ICI), CSM may be passed so that MD
  8349. // is treated as certain special member, which may not reflect what special
  8350. // member MD really is. However inferCUDATargetForImplicitSpecialMember
  8351. // expects CSM to match MD, therefore recalculate CSM.
  8352. assert(ICI || CSM == getSpecialMember(MD));
  8353. auto RealCSM = CSM;
  8354. if (ICI)
  8355. RealCSM = getSpecialMember(MD);
  8356. return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
  8357. SMI.ConstArg, Diagnose);
  8358. }
  8359. return false;
  8360. }
  8361. void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
  8362. DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
  8363. assert(DFK && "not a defaultable function");
  8364. assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
  8365. if (DFK.isSpecialMember()) {
  8366. ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
  8367. nullptr, /*Diagnose=*/true);
  8368. } else {
  8369. DefaultedComparisonAnalyzer(
  8370. *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
  8371. DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
  8372. .visit();
  8373. }
  8374. }
  8375. /// Perform lookup for a special member of the specified kind, and determine
  8376. /// whether it is trivial. If the triviality can be determined without the
  8377. /// lookup, skip it. This is intended for use when determining whether a
  8378. /// special member of a containing object is trivial, and thus does not ever
  8379. /// perform overload resolution for default constructors.
  8380. ///
  8381. /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
  8382. /// member that was most likely to be intended to be trivial, if any.
  8383. ///
  8384. /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
  8385. /// determine whether the special member is trivial.
  8386. static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
  8387. Sema::CXXSpecialMember CSM, unsigned Quals,
  8388. bool ConstRHS,
  8389. Sema::TrivialABIHandling TAH,
  8390. CXXMethodDecl **Selected) {
  8391. if (Selected)
  8392. *Selected = nullptr;
  8393. switch (CSM) {
  8394. case Sema::CXXInvalid:
  8395. llvm_unreachable("not a special member");
  8396. case Sema::CXXDefaultConstructor:
  8397. // C++11 [class.ctor]p5:
  8398. // A default constructor is trivial if:
  8399. // - all the [direct subobjects] have trivial default constructors
  8400. //
  8401. // Note, no overload resolution is performed in this case.
  8402. if (RD->hasTrivialDefaultConstructor())
  8403. return true;
  8404. if (Selected) {
  8405. // If there's a default constructor which could have been trivial, dig it
  8406. // out. Otherwise, if there's any user-provided default constructor, point
  8407. // to that as an example of why there's not a trivial one.
  8408. CXXConstructorDecl *DefCtor = nullptr;
  8409. if (RD->needsImplicitDefaultConstructor())
  8410. S.DeclareImplicitDefaultConstructor(RD);
  8411. for (auto *CI : RD->ctors()) {
  8412. if (!CI->isDefaultConstructor())
  8413. continue;
  8414. DefCtor = CI;
  8415. if (!DefCtor->isUserProvided())
  8416. break;
  8417. }
  8418. *Selected = DefCtor;
  8419. }
  8420. return false;
  8421. case Sema::CXXDestructor:
  8422. // C++11 [class.dtor]p5:
  8423. // A destructor is trivial if:
  8424. // - all the direct [subobjects] have trivial destructors
  8425. if (RD->hasTrivialDestructor() ||
  8426. (TAH == Sema::TAH_ConsiderTrivialABI &&
  8427. RD->hasTrivialDestructorForCall()))
  8428. return true;
  8429. if (Selected) {
  8430. if (RD->needsImplicitDestructor())
  8431. S.DeclareImplicitDestructor(RD);
  8432. *Selected = RD->getDestructor();
  8433. }
  8434. return false;
  8435. case Sema::CXXCopyConstructor:
  8436. // C++11 [class.copy]p12:
  8437. // A copy constructor is trivial if:
  8438. // - the constructor selected to copy each direct [subobject] is trivial
  8439. if (RD->hasTrivialCopyConstructor() ||
  8440. (TAH == Sema::TAH_ConsiderTrivialABI &&
  8441. RD->hasTrivialCopyConstructorForCall())) {
  8442. if (Quals == Qualifiers::Const)
  8443. // We must either select the trivial copy constructor or reach an
  8444. // ambiguity; no need to actually perform overload resolution.
  8445. return true;
  8446. } else if (!Selected) {
  8447. return false;
  8448. }
  8449. // In C++98, we are not supposed to perform overload resolution here, but we
  8450. // treat that as a language defect, as suggested on cxx-abi-dev, to treat
  8451. // cases like B as having a non-trivial copy constructor:
  8452. // struct A { template<typename T> A(T&); };
  8453. // struct B { mutable A a; };
  8454. goto NeedOverloadResolution;
  8455. case Sema::CXXCopyAssignment:
  8456. // C++11 [class.copy]p25:
  8457. // A copy assignment operator is trivial if:
  8458. // - the assignment operator selected to copy each direct [subobject] is
  8459. // trivial
  8460. if (RD->hasTrivialCopyAssignment()) {
  8461. if (Quals == Qualifiers::Const)
  8462. return true;
  8463. } else if (!Selected) {
  8464. return false;
  8465. }
  8466. // In C++98, we are not supposed to perform overload resolution here, but we
  8467. // treat that as a language defect.
  8468. goto NeedOverloadResolution;
  8469. case Sema::CXXMoveConstructor:
  8470. case Sema::CXXMoveAssignment:
  8471. NeedOverloadResolution:
  8472. Sema::SpecialMemberOverloadResult SMOR =
  8473. lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
  8474. // The standard doesn't describe how to behave if the lookup is ambiguous.
  8475. // We treat it as not making the member non-trivial, just like the standard
  8476. // mandates for the default constructor. This should rarely matter, because
  8477. // the member will also be deleted.
  8478. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  8479. return true;
  8480. if (!SMOR.getMethod()) {
  8481. assert(SMOR.getKind() ==
  8482. Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
  8483. return false;
  8484. }
  8485. // We deliberately don't check if we found a deleted special member. We're
  8486. // not supposed to!
  8487. if (Selected)
  8488. *Selected = SMOR.getMethod();
  8489. if (TAH == Sema::TAH_ConsiderTrivialABI &&
  8490. (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
  8491. return SMOR.getMethod()->isTrivialForCall();
  8492. return SMOR.getMethod()->isTrivial();
  8493. }
  8494. llvm_unreachable("unknown special method kind");
  8495. }
  8496. static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
  8497. for (auto *CI : RD->ctors())
  8498. if (!CI->isImplicit())
  8499. return CI;
  8500. // Look for constructor templates.
  8501. typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
  8502. for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
  8503. if (CXXConstructorDecl *CD =
  8504. dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
  8505. return CD;
  8506. }
  8507. return nullptr;
  8508. }
  8509. /// The kind of subobject we are checking for triviality. The values of this
  8510. /// enumeration are used in diagnostics.
  8511. enum TrivialSubobjectKind {
  8512. /// The subobject is a base class.
  8513. TSK_BaseClass,
  8514. /// The subobject is a non-static data member.
  8515. TSK_Field,
  8516. /// The object is actually the complete object.
  8517. TSK_CompleteObject
  8518. };
  8519. /// Check whether the special member selected for a given type would be trivial.
  8520. static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
  8521. QualType SubType, bool ConstRHS,
  8522. Sema::CXXSpecialMember CSM,
  8523. TrivialSubobjectKind Kind,
  8524. Sema::TrivialABIHandling TAH, bool Diagnose) {
  8525. CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
  8526. if (!SubRD)
  8527. return true;
  8528. CXXMethodDecl *Selected;
  8529. if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
  8530. ConstRHS, TAH, Diagnose ? &Selected : nullptr))
  8531. return true;
  8532. if (Diagnose) {
  8533. if (ConstRHS)
  8534. SubType.addConst();
  8535. if (!Selected && CSM == Sema::CXXDefaultConstructor) {
  8536. S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
  8537. << Kind << SubType.getUnqualifiedType();
  8538. if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
  8539. S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
  8540. } else if (!Selected)
  8541. S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
  8542. << Kind << SubType.getUnqualifiedType() << CSM << SubType;
  8543. else if (Selected->isUserProvided()) {
  8544. if (Kind == TSK_CompleteObject)
  8545. S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
  8546. << Kind << SubType.getUnqualifiedType() << CSM;
  8547. else {
  8548. S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
  8549. << Kind << SubType.getUnqualifiedType() << CSM;
  8550. S.Diag(Selected->getLocation(), diag::note_declared_at);
  8551. }
  8552. } else {
  8553. if (Kind != TSK_CompleteObject)
  8554. S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
  8555. << Kind << SubType.getUnqualifiedType() << CSM;
  8556. // Explain why the defaulted or deleted special member isn't trivial.
  8557. S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
  8558. Diagnose);
  8559. }
  8560. }
  8561. return false;
  8562. }
  8563. /// Check whether the members of a class type allow a special member to be
  8564. /// trivial.
  8565. static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
  8566. Sema::CXXSpecialMember CSM,
  8567. bool ConstArg,
  8568. Sema::TrivialABIHandling TAH,
  8569. bool Diagnose) {
  8570. for (const auto *FI : RD->fields()) {
  8571. if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
  8572. continue;
  8573. QualType FieldType = S.Context.getBaseElementType(FI->getType());
  8574. // Pretend anonymous struct or union members are members of this class.
  8575. if (FI->isAnonymousStructOrUnion()) {
  8576. if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
  8577. CSM, ConstArg, TAH, Diagnose))
  8578. return false;
  8579. continue;
  8580. }
  8581. // C++11 [class.ctor]p5:
  8582. // A default constructor is trivial if [...]
  8583. // -- no non-static data member of its class has a
  8584. // brace-or-equal-initializer
  8585. if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
  8586. if (Diagnose)
  8587. S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
  8588. << FI;
  8589. return false;
  8590. }
  8591. // Objective C ARC 4.3.5:
  8592. // [...] nontrivally ownership-qualified types are [...] not trivially
  8593. // default constructible, copy constructible, move constructible, copy
  8594. // assignable, move assignable, or destructible [...]
  8595. if (FieldType.hasNonTrivialObjCLifetime()) {
  8596. if (Diagnose)
  8597. S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
  8598. << RD << FieldType.getObjCLifetime();
  8599. return false;
  8600. }
  8601. bool ConstRHS = ConstArg && !FI->isMutable();
  8602. if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
  8603. CSM, TSK_Field, TAH, Diagnose))
  8604. return false;
  8605. }
  8606. return true;
  8607. }
  8608. /// Diagnose why the specified class does not have a trivial special member of
  8609. /// the given kind.
  8610. void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
  8611. QualType Ty = Context.getRecordType(RD);
  8612. bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
  8613. checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
  8614. TSK_CompleteObject, TAH_IgnoreTrivialABI,
  8615. /*Diagnose*/true);
  8616. }
  8617. /// Determine whether a defaulted or deleted special member function is trivial,
  8618. /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
  8619. /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
  8620. bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
  8621. TrivialABIHandling TAH, bool Diagnose) {
  8622. assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
  8623. CXXRecordDecl *RD = MD->getParent();
  8624. bool ConstArg = false;
  8625. // C++11 [class.copy]p12, p25: [DR1593]
  8626. // A [special member] is trivial if [...] its parameter-type-list is
  8627. // equivalent to the parameter-type-list of an implicit declaration [...]
  8628. switch (CSM) {
  8629. case CXXDefaultConstructor:
  8630. case CXXDestructor:
  8631. // Trivial default constructors and destructors cannot have parameters.
  8632. break;
  8633. case CXXCopyConstructor:
  8634. case CXXCopyAssignment: {
  8635. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  8636. const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
  8637. // When ClangABICompat14 is true, CXX copy constructors will only be trivial
  8638. // if they are not user-provided and their parameter-type-list is equivalent
  8639. // to the parameter-type-list of an implicit declaration. This maintains the
  8640. // behavior before dr2171 was implemented.
  8641. //
  8642. // Otherwise, if ClangABICompat14 is false, All copy constructors can be
  8643. // trivial, if they are not user-provided, regardless of the qualifiers on
  8644. // the reference type.
  8645. const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
  8646. LangOptions::ClangABI::Ver14;
  8647. if (!RT ||
  8648. ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
  8649. ClangABICompat14)) {
  8650. if (Diagnose)
  8651. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  8652. << Param0->getSourceRange() << Param0->getType()
  8653. << Context.getLValueReferenceType(
  8654. Context.getRecordType(RD).withConst());
  8655. return false;
  8656. }
  8657. ConstArg = RT->getPointeeType().isConstQualified();
  8658. break;
  8659. }
  8660. case CXXMoveConstructor:
  8661. case CXXMoveAssignment: {
  8662. // Trivial move operations always have non-cv-qualified parameters.
  8663. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  8664. const RValueReferenceType *RT =
  8665. Param0->getType()->getAs<RValueReferenceType>();
  8666. if (!RT || RT->getPointeeType().getCVRQualifiers()) {
  8667. if (Diagnose)
  8668. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  8669. << Param0->getSourceRange() << Param0->getType()
  8670. << Context.getRValueReferenceType(Context.getRecordType(RD));
  8671. return false;
  8672. }
  8673. break;
  8674. }
  8675. case CXXInvalid:
  8676. llvm_unreachable("not a special member");
  8677. }
  8678. if (MD->getMinRequiredArguments() < MD->getNumParams()) {
  8679. if (Diagnose)
  8680. Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
  8681. diag::note_nontrivial_default_arg)
  8682. << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
  8683. return false;
  8684. }
  8685. if (MD->isVariadic()) {
  8686. if (Diagnose)
  8687. Diag(MD->getLocation(), diag::note_nontrivial_variadic);
  8688. return false;
  8689. }
  8690. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  8691. // A copy/move [constructor or assignment operator] is trivial if
  8692. // -- the [member] selected to copy/move each direct base class subobject
  8693. // is trivial
  8694. //
  8695. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  8696. // A [default constructor or destructor] is trivial if
  8697. // -- all the direct base classes have trivial [default constructors or
  8698. // destructors]
  8699. for (const auto &BI : RD->bases())
  8700. if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
  8701. ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
  8702. return false;
  8703. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  8704. // A copy/move [constructor or assignment operator] for a class X is
  8705. // trivial if
  8706. // -- for each non-static data member of X that is of class type (or array
  8707. // thereof), the constructor selected to copy/move that member is
  8708. // trivial
  8709. //
  8710. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  8711. // A [default constructor or destructor] is trivial if
  8712. // -- for all of the non-static data members of its class that are of class
  8713. // type (or array thereof), each such class has a trivial [default
  8714. // constructor or destructor]
  8715. if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
  8716. return false;
  8717. // C++11 [class.dtor]p5:
  8718. // A destructor is trivial if [...]
  8719. // -- the destructor is not virtual
  8720. if (CSM == CXXDestructor && MD->isVirtual()) {
  8721. if (Diagnose)
  8722. Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
  8723. return false;
  8724. }
  8725. // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
  8726. // A [special member] for class X is trivial if [...]
  8727. // -- class X has no virtual functions and no virtual base classes
  8728. if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
  8729. if (!Diagnose)
  8730. return false;
  8731. if (RD->getNumVBases()) {
  8732. // Check for virtual bases. We already know that the corresponding
  8733. // member in all bases is trivial, so vbases must all be direct.
  8734. CXXBaseSpecifier &BS = *RD->vbases_begin();
  8735. assert(BS.isVirtual());
  8736. Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
  8737. return false;
  8738. }
  8739. // Must have a virtual method.
  8740. for (const auto *MI : RD->methods()) {
  8741. if (MI->isVirtual()) {
  8742. SourceLocation MLoc = MI->getBeginLoc();
  8743. Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
  8744. return false;
  8745. }
  8746. }
  8747. llvm_unreachable("dynamic class with no vbases and no virtual functions");
  8748. }
  8749. // Looks like it's trivial!
  8750. return true;
  8751. }
  8752. namespace {
  8753. struct FindHiddenVirtualMethod {
  8754. Sema *S;
  8755. CXXMethodDecl *Method;
  8756. llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
  8757. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  8758. private:
  8759. /// Check whether any most overridden method from MD in Methods
  8760. static bool CheckMostOverridenMethods(
  8761. const CXXMethodDecl *MD,
  8762. const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
  8763. if (MD->size_overridden_methods() == 0)
  8764. return Methods.count(MD->getCanonicalDecl());
  8765. for (const CXXMethodDecl *O : MD->overridden_methods())
  8766. if (CheckMostOverridenMethods(O, Methods))
  8767. return true;
  8768. return false;
  8769. }
  8770. public:
  8771. /// Member lookup function that determines whether a given C++
  8772. /// method overloads virtual methods in a base class without overriding any,
  8773. /// to be used with CXXRecordDecl::lookupInBases().
  8774. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  8775. RecordDecl *BaseRecord =
  8776. Specifier->getType()->castAs<RecordType>()->getDecl();
  8777. DeclarationName Name = Method->getDeclName();
  8778. assert(Name.getNameKind() == DeclarationName::Identifier);
  8779. bool foundSameNameMethod = false;
  8780. SmallVector<CXXMethodDecl *, 8> overloadedMethods;
  8781. for (Path.Decls = BaseRecord->lookup(Name).begin();
  8782. Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
  8783. NamedDecl *D = *Path.Decls;
  8784. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  8785. MD = MD->getCanonicalDecl();
  8786. foundSameNameMethod = true;
  8787. // Interested only in hidden virtual methods.
  8788. if (!MD->isVirtual())
  8789. continue;
  8790. // If the method we are checking overrides a method from its base
  8791. // don't warn about the other overloaded methods. Clang deviates from
  8792. // GCC by only diagnosing overloads of inherited virtual functions that
  8793. // do not override any other virtual functions in the base. GCC's
  8794. // -Woverloaded-virtual diagnoses any derived function hiding a virtual
  8795. // function from a base class. These cases may be better served by a
  8796. // warning (not specific to virtual functions) on call sites when the
  8797. // call would select a different function from the base class, were it
  8798. // visible.
  8799. // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
  8800. if (!S->IsOverload(Method, MD, false))
  8801. return true;
  8802. // Collect the overload only if its hidden.
  8803. if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
  8804. overloadedMethods.push_back(MD);
  8805. }
  8806. }
  8807. if (foundSameNameMethod)
  8808. OverloadedMethods.append(overloadedMethods.begin(),
  8809. overloadedMethods.end());
  8810. return foundSameNameMethod;
  8811. }
  8812. };
  8813. } // end anonymous namespace
  8814. /// Add the most overridden methods from MD to Methods
  8815. static void AddMostOverridenMethods(const CXXMethodDecl *MD,
  8816. llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
  8817. if (MD->size_overridden_methods() == 0)
  8818. Methods.insert(MD->getCanonicalDecl());
  8819. else
  8820. for (const CXXMethodDecl *O : MD->overridden_methods())
  8821. AddMostOverridenMethods(O, Methods);
  8822. }
  8823. /// Check if a method overloads virtual methods in a base class without
  8824. /// overriding any.
  8825. void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
  8826. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  8827. if (!MD->getDeclName().isIdentifier())
  8828. return;
  8829. CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
  8830. /*bool RecordPaths=*/false,
  8831. /*bool DetectVirtual=*/false);
  8832. FindHiddenVirtualMethod FHVM;
  8833. FHVM.Method = MD;
  8834. FHVM.S = this;
  8835. // Keep the base methods that were overridden or introduced in the subclass
  8836. // by 'using' in a set. A base method not in this set is hidden.
  8837. CXXRecordDecl *DC = MD->getParent();
  8838. DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
  8839. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
  8840. NamedDecl *ND = *I;
  8841. if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
  8842. ND = shad->getTargetDecl();
  8843. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  8844. AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
  8845. }
  8846. if (DC->lookupInBases(FHVM, Paths))
  8847. OverloadedMethods = FHVM.OverloadedMethods;
  8848. }
  8849. void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
  8850. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  8851. for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
  8852. CXXMethodDecl *overloadedMD = OverloadedMethods[i];
  8853. PartialDiagnostic PD = PDiag(
  8854. diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
  8855. HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
  8856. Diag(overloadedMD->getLocation(), PD);
  8857. }
  8858. }
  8859. /// Diagnose methods which overload virtual methods in a base class
  8860. /// without overriding any.
  8861. void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
  8862. if (MD->isInvalidDecl())
  8863. return;
  8864. if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
  8865. return;
  8866. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  8867. FindHiddenVirtualMethods(MD, OverloadedMethods);
  8868. if (!OverloadedMethods.empty()) {
  8869. Diag(MD->getLocation(), diag::warn_overloaded_virtual)
  8870. << MD << (OverloadedMethods.size() > 1);
  8871. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  8872. }
  8873. }
  8874. void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
  8875. auto PrintDiagAndRemoveAttr = [&](unsigned N) {
  8876. // No diagnostics if this is a template instantiation.
  8877. if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
  8878. Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
  8879. diag::ext_cannot_use_trivial_abi) << &RD;
  8880. Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
  8881. diag::note_cannot_use_trivial_abi_reason) << &RD << N;
  8882. }
  8883. RD.dropAttr<TrivialABIAttr>();
  8884. };
  8885. // Ill-formed if the copy and move constructors are deleted.
  8886. auto HasNonDeletedCopyOrMoveConstructor = [&]() {
  8887. // If the type is dependent, then assume it might have
  8888. // implicit copy or move ctor because we won't know yet at this point.
  8889. if (RD.isDependentType())
  8890. return true;
  8891. if (RD.needsImplicitCopyConstructor() &&
  8892. !RD.defaultedCopyConstructorIsDeleted())
  8893. return true;
  8894. if (RD.needsImplicitMoveConstructor() &&
  8895. !RD.defaultedMoveConstructorIsDeleted())
  8896. return true;
  8897. for (const CXXConstructorDecl *CD : RD.ctors())
  8898. if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
  8899. return true;
  8900. return false;
  8901. };
  8902. if (!HasNonDeletedCopyOrMoveConstructor()) {
  8903. PrintDiagAndRemoveAttr(0);
  8904. return;
  8905. }
  8906. // Ill-formed if the struct has virtual functions.
  8907. if (RD.isPolymorphic()) {
  8908. PrintDiagAndRemoveAttr(1);
  8909. return;
  8910. }
  8911. for (const auto &B : RD.bases()) {
  8912. // Ill-formed if the base class is non-trivial for the purpose of calls or a
  8913. // virtual base.
  8914. if (!B.getType()->isDependentType() &&
  8915. !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
  8916. PrintDiagAndRemoveAttr(2);
  8917. return;
  8918. }
  8919. if (B.isVirtual()) {
  8920. PrintDiagAndRemoveAttr(3);
  8921. return;
  8922. }
  8923. }
  8924. for (const auto *FD : RD.fields()) {
  8925. // Ill-formed if the field is an ObjectiveC pointer or of a type that is
  8926. // non-trivial for the purpose of calls.
  8927. QualType FT = FD->getType();
  8928. if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
  8929. PrintDiagAndRemoveAttr(4);
  8930. return;
  8931. }
  8932. if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
  8933. if (!RT->isDependentType() &&
  8934. !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
  8935. PrintDiagAndRemoveAttr(5);
  8936. return;
  8937. }
  8938. }
  8939. }
  8940. void Sema::ActOnFinishCXXMemberSpecification(
  8941. Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
  8942. SourceLocation RBrac, const ParsedAttributesView &AttrList) {
  8943. if (!TagDecl)
  8944. return;
  8945. AdjustDeclIfTemplate(TagDecl);
  8946. for (const ParsedAttr &AL : AttrList) {
  8947. if (AL.getKind() != ParsedAttr::AT_Visibility)
  8948. continue;
  8949. AL.setInvalid();
  8950. Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
  8951. }
  8952. ActOnFields(S, RLoc, TagDecl,
  8953. llvm::ArrayRef(
  8954. // strict aliasing violation!
  8955. reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
  8956. FieldCollector->getCurNumFields()),
  8957. LBrac, RBrac, AttrList);
  8958. CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
  8959. }
  8960. /// Find the equality comparison functions that should be implicitly declared
  8961. /// in a given class definition, per C++2a [class.compare.default]p3.
  8962. static void findImplicitlyDeclaredEqualityComparisons(
  8963. ASTContext &Ctx, CXXRecordDecl *RD,
  8964. llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
  8965. DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
  8966. if (!RD->lookup(EqEq).empty())
  8967. // Member operator== explicitly declared: no implicit operator==s.
  8968. return;
  8969. // Traverse friends looking for an '==' or a '<=>'.
  8970. for (FriendDecl *Friend : RD->friends()) {
  8971. FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
  8972. if (!FD) continue;
  8973. if (FD->getOverloadedOperator() == OO_EqualEqual) {
  8974. // Friend operator== explicitly declared: no implicit operator==s.
  8975. Spaceships.clear();
  8976. return;
  8977. }
  8978. if (FD->getOverloadedOperator() == OO_Spaceship &&
  8979. FD->isExplicitlyDefaulted())
  8980. Spaceships.push_back(FD);
  8981. }
  8982. // Look for members named 'operator<=>'.
  8983. DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
  8984. for (NamedDecl *ND : RD->lookup(Cmp)) {
  8985. // Note that we could find a non-function here (either a function template
  8986. // or a using-declaration). Neither case results in an implicit
  8987. // 'operator=='.
  8988. if (auto *FD = dyn_cast<FunctionDecl>(ND))
  8989. if (FD->isExplicitlyDefaulted())
  8990. Spaceships.push_back(FD);
  8991. }
  8992. }
  8993. /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
  8994. /// special functions, such as the default constructor, copy
  8995. /// constructor, or destructor, to the given C++ class (C++
  8996. /// [special]p1). This routine can only be executed just before the
  8997. /// definition of the class is complete.
  8998. void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
  8999. // Don't add implicit special members to templated classes.
  9000. // FIXME: This means unqualified lookups for 'operator=' within a class
  9001. // template don't work properly.
  9002. if (!ClassDecl->isDependentType()) {
  9003. if (ClassDecl->needsImplicitDefaultConstructor()) {
  9004. ++getASTContext().NumImplicitDefaultConstructors;
  9005. if (ClassDecl->hasInheritedConstructor())
  9006. DeclareImplicitDefaultConstructor(ClassDecl);
  9007. }
  9008. if (ClassDecl->needsImplicitCopyConstructor()) {
  9009. ++getASTContext().NumImplicitCopyConstructors;
  9010. // If the properties or semantics of the copy constructor couldn't be
  9011. // determined while the class was being declared, force a declaration
  9012. // of it now.
  9013. if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
  9014. ClassDecl->hasInheritedConstructor())
  9015. DeclareImplicitCopyConstructor(ClassDecl);
  9016. // For the MS ABI we need to know whether the copy ctor is deleted. A
  9017. // prerequisite for deleting the implicit copy ctor is that the class has
  9018. // a move ctor or move assignment that is either user-declared or whose
  9019. // semantics are inherited from a subobject. FIXME: We should provide a
  9020. // more direct way for CodeGen to ask whether the constructor was deleted.
  9021. else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  9022. (ClassDecl->hasUserDeclaredMoveConstructor() ||
  9023. ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  9024. ClassDecl->hasUserDeclaredMoveAssignment() ||
  9025. ClassDecl->needsOverloadResolutionForMoveAssignment()))
  9026. DeclareImplicitCopyConstructor(ClassDecl);
  9027. }
  9028. if (getLangOpts().CPlusPlus11 &&
  9029. ClassDecl->needsImplicitMoveConstructor()) {
  9030. ++getASTContext().NumImplicitMoveConstructors;
  9031. if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  9032. ClassDecl->hasInheritedConstructor())
  9033. DeclareImplicitMoveConstructor(ClassDecl);
  9034. }
  9035. if (ClassDecl->needsImplicitCopyAssignment()) {
  9036. ++getASTContext().NumImplicitCopyAssignmentOperators;
  9037. // If we have a dynamic class, then the copy assignment operator may be
  9038. // virtual, so we have to declare it immediately. This ensures that, e.g.,
  9039. // it shows up in the right place in the vtable and that we diagnose
  9040. // problems with the implicit exception specification.
  9041. if (ClassDecl->isDynamicClass() ||
  9042. ClassDecl->needsOverloadResolutionForCopyAssignment() ||
  9043. ClassDecl->hasInheritedAssignment())
  9044. DeclareImplicitCopyAssignment(ClassDecl);
  9045. }
  9046. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
  9047. ++getASTContext().NumImplicitMoveAssignmentOperators;
  9048. // Likewise for the move assignment operator.
  9049. if (ClassDecl->isDynamicClass() ||
  9050. ClassDecl->needsOverloadResolutionForMoveAssignment() ||
  9051. ClassDecl->hasInheritedAssignment())
  9052. DeclareImplicitMoveAssignment(ClassDecl);
  9053. }
  9054. if (ClassDecl->needsImplicitDestructor()) {
  9055. ++getASTContext().NumImplicitDestructors;
  9056. // If we have a dynamic class, then the destructor may be virtual, so we
  9057. // have to declare the destructor immediately. This ensures that, e.g., it
  9058. // shows up in the right place in the vtable and that we diagnose problems
  9059. // with the implicit exception specification.
  9060. if (ClassDecl->isDynamicClass() ||
  9061. ClassDecl->needsOverloadResolutionForDestructor())
  9062. DeclareImplicitDestructor(ClassDecl);
  9063. }
  9064. }
  9065. // C++2a [class.compare.default]p3:
  9066. // If the member-specification does not explicitly declare any member or
  9067. // friend named operator==, an == operator function is declared implicitly
  9068. // for each defaulted three-way comparison operator function defined in
  9069. // the member-specification
  9070. // FIXME: Consider doing this lazily.
  9071. // We do this during the initial parse for a class template, not during
  9072. // instantiation, so that we can handle unqualified lookups for 'operator=='
  9073. // when parsing the template.
  9074. if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
  9075. llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
  9076. findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
  9077. DefaultedSpaceships);
  9078. for (auto *FD : DefaultedSpaceships)
  9079. DeclareImplicitEqualityComparison(ClassDecl, FD);
  9080. }
  9081. }
  9082. unsigned
  9083. Sema::ActOnReenterTemplateScope(Decl *D,
  9084. llvm::function_ref<Scope *()> EnterScope) {
  9085. if (!D)
  9086. return 0;
  9087. AdjustDeclIfTemplate(D);
  9088. // In order to get name lookup right, reenter template scopes in order from
  9089. // outermost to innermost.
  9090. SmallVector<TemplateParameterList *, 4> ParameterLists;
  9091. DeclContext *LookupDC = dyn_cast<DeclContext>(D);
  9092. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  9093. for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
  9094. ParameterLists.push_back(DD->getTemplateParameterList(i));
  9095. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  9096. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  9097. ParameterLists.push_back(FTD->getTemplateParameters());
  9098. } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  9099. LookupDC = VD->getDeclContext();
  9100. if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
  9101. ParameterLists.push_back(VTD->getTemplateParameters());
  9102. else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
  9103. ParameterLists.push_back(PSD->getTemplateParameters());
  9104. }
  9105. } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  9106. for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
  9107. ParameterLists.push_back(TD->getTemplateParameterList(i));
  9108. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
  9109. if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
  9110. ParameterLists.push_back(CTD->getTemplateParameters());
  9111. else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
  9112. ParameterLists.push_back(PSD->getTemplateParameters());
  9113. }
  9114. }
  9115. // FIXME: Alias declarations and concepts.
  9116. unsigned Count = 0;
  9117. Scope *InnermostTemplateScope = nullptr;
  9118. for (TemplateParameterList *Params : ParameterLists) {
  9119. // Ignore explicit specializations; they don't contribute to the template
  9120. // depth.
  9121. if (Params->size() == 0)
  9122. continue;
  9123. InnermostTemplateScope = EnterScope();
  9124. for (NamedDecl *Param : *Params) {
  9125. if (Param->getDeclName()) {
  9126. InnermostTemplateScope->AddDecl(Param);
  9127. IdResolver.AddDecl(Param);
  9128. }
  9129. }
  9130. ++Count;
  9131. }
  9132. // Associate the new template scopes with the corresponding entities.
  9133. if (InnermostTemplateScope) {
  9134. assert(LookupDC && "no enclosing DeclContext for template lookup");
  9135. EnterTemplatedContext(InnermostTemplateScope, LookupDC);
  9136. }
  9137. return Count;
  9138. }
  9139. void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  9140. if (!RecordD) return;
  9141. AdjustDeclIfTemplate(RecordD);
  9142. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
  9143. PushDeclContext(S, Record);
  9144. }
  9145. void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  9146. if (!RecordD) return;
  9147. PopDeclContext();
  9148. }
  9149. /// This is used to implement the constant expression evaluation part of the
  9150. /// attribute enable_if extension. There is nothing in standard C++ which would
  9151. /// require reentering parameters.
  9152. void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
  9153. if (!Param)
  9154. return;
  9155. S->AddDecl(Param);
  9156. if (Param->getDeclName())
  9157. IdResolver.AddDecl(Param);
  9158. }
  9159. /// ActOnStartDelayedCXXMethodDeclaration - We have completed
  9160. /// parsing a top-level (non-nested) C++ class, and we are now
  9161. /// parsing those parts of the given Method declaration that could
  9162. /// not be parsed earlier (C++ [class.mem]p2), such as default
  9163. /// arguments. This action should enter the scope of the given
  9164. /// Method declaration as if we had just parsed the qualified method
  9165. /// name. However, it should not bring the parameters into scope;
  9166. /// that will be performed by ActOnDelayedCXXMethodParameter.
  9167. void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  9168. }
  9169. /// ActOnDelayedCXXMethodParameter - We've already started a delayed
  9170. /// C++ method declaration. We're (re-)introducing the given
  9171. /// function parameter into scope for use in parsing later parts of
  9172. /// the method declaration. For example, we could see an
  9173. /// ActOnParamDefaultArgument event for this parameter.
  9174. void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
  9175. if (!ParamD)
  9176. return;
  9177. ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
  9178. S->AddDecl(Param);
  9179. if (Param->getDeclName())
  9180. IdResolver.AddDecl(Param);
  9181. }
  9182. /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
  9183. /// processing the delayed method declaration for Method. The method
  9184. /// declaration is now considered finished. There may be a separate
  9185. /// ActOnStartOfFunctionDef action later (not necessarily
  9186. /// immediately!) for this method, if it was also defined inside the
  9187. /// class body.
  9188. void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  9189. if (!MethodD)
  9190. return;
  9191. AdjustDeclIfTemplate(MethodD);
  9192. FunctionDecl *Method = cast<FunctionDecl>(MethodD);
  9193. // Now that we have our default arguments, check the constructor
  9194. // again. It could produce additional diagnostics or affect whether
  9195. // the class has implicitly-declared destructors, among other
  9196. // things.
  9197. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
  9198. CheckConstructor(Constructor);
  9199. // Check the default arguments, which we may have added.
  9200. if (!Method->isInvalidDecl())
  9201. CheckCXXDefaultArguments(Method);
  9202. }
  9203. // Emit the given diagnostic for each non-address-space qualifier.
  9204. // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
  9205. static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
  9206. const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  9207. if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
  9208. bool DiagOccured = false;
  9209. FTI.MethodQualifiers->forEachQualifier(
  9210. [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
  9211. SourceLocation SL) {
  9212. // This diagnostic should be emitted on any qualifier except an addr
  9213. // space qualifier. However, forEachQualifier currently doesn't visit
  9214. // addr space qualifiers, so there's no way to write this condition
  9215. // right now; we just diagnose on everything.
  9216. S.Diag(SL, DiagID) << QualName << SourceRange(SL);
  9217. DiagOccured = true;
  9218. });
  9219. if (DiagOccured)
  9220. D.setInvalidType();
  9221. }
  9222. }
  9223. /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
  9224. /// the well-formedness of the constructor declarator @p D with type @p
  9225. /// R. If there are any errors in the declarator, this routine will
  9226. /// emit diagnostics and set the invalid bit to true. In any case, the type
  9227. /// will be updated to reflect a well-formed type for the constructor and
  9228. /// returned.
  9229. QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
  9230. StorageClass &SC) {
  9231. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  9232. // C++ [class.ctor]p3:
  9233. // A constructor shall not be virtual (10.3) or static (9.4). A
  9234. // constructor can be invoked for a const, volatile or const
  9235. // volatile object. A constructor shall not be declared const,
  9236. // volatile, or const volatile (9.3.2).
  9237. if (isVirtual) {
  9238. if (!D.isInvalidType())
  9239. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  9240. << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
  9241. << SourceRange(D.getIdentifierLoc());
  9242. D.setInvalidType();
  9243. }
  9244. if (SC == SC_Static) {
  9245. if (!D.isInvalidType())
  9246. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  9247. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  9248. << SourceRange(D.getIdentifierLoc());
  9249. D.setInvalidType();
  9250. SC = SC_None;
  9251. }
  9252. if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  9253. diagnoseIgnoredQualifiers(
  9254. diag::err_constructor_return_type, TypeQuals, SourceLocation(),
  9255. D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
  9256. D.getDeclSpec().getRestrictSpecLoc(),
  9257. D.getDeclSpec().getAtomicSpecLoc());
  9258. D.setInvalidType();
  9259. }
  9260. checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
  9261. // C++0x [class.ctor]p4:
  9262. // A constructor shall not be declared with a ref-qualifier.
  9263. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  9264. if (FTI.hasRefQualifier()) {
  9265. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
  9266. << FTI.RefQualifierIsLValueRef
  9267. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  9268. D.setInvalidType();
  9269. }
  9270. // Rebuild the function type "R" without any type qualifiers (in
  9271. // case any of the errors above fired) and with "void" as the
  9272. // return type, since constructors don't have return types.
  9273. const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
  9274. if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
  9275. return R;
  9276. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  9277. EPI.TypeQuals = Qualifiers();
  9278. EPI.RefQualifier = RQ_None;
  9279. return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
  9280. }
  9281. /// CheckConstructor - Checks a fully-formed constructor for
  9282. /// well-formedness, issuing any diagnostics required. Returns true if
  9283. /// the constructor declarator is invalid.
  9284. void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
  9285. CXXRecordDecl *ClassDecl
  9286. = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
  9287. if (!ClassDecl)
  9288. return Constructor->setInvalidDecl();
  9289. // C++ [class.copy]p3:
  9290. // A declaration of a constructor for a class X is ill-formed if
  9291. // its first parameter is of type (optionally cv-qualified) X and
  9292. // either there are no other parameters or else all other
  9293. // parameters have default arguments.
  9294. if (!Constructor->isInvalidDecl() &&
  9295. Constructor->hasOneParamOrDefaultArgs() &&
  9296. Constructor->getTemplateSpecializationKind() !=
  9297. TSK_ImplicitInstantiation) {
  9298. QualType ParamType = Constructor->getParamDecl(0)->getType();
  9299. QualType ClassTy = Context.getTagDeclType(ClassDecl);
  9300. if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
  9301. SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
  9302. const char *ConstRef
  9303. = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
  9304. : " const &";
  9305. Diag(ParamLoc, diag::err_constructor_byvalue_arg)
  9306. << FixItHint::CreateInsertion(ParamLoc, ConstRef);
  9307. // FIXME: Rather that making the constructor invalid, we should endeavor
  9308. // to fix the type.
  9309. Constructor->setInvalidDecl();
  9310. }
  9311. }
  9312. }
  9313. /// CheckDestructor - Checks a fully-formed destructor definition for
  9314. /// well-formedness, issuing any diagnostics required. Returns true
  9315. /// on error.
  9316. bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
  9317. CXXRecordDecl *RD = Destructor->getParent();
  9318. if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
  9319. SourceLocation Loc;
  9320. if (!Destructor->isImplicit())
  9321. Loc = Destructor->getLocation();
  9322. else
  9323. Loc = RD->getLocation();
  9324. // If we have a virtual destructor, look up the deallocation function
  9325. if (FunctionDecl *OperatorDelete =
  9326. FindDeallocationFunctionForDestructor(Loc, RD)) {
  9327. Expr *ThisArg = nullptr;
  9328. // If the notional 'delete this' expression requires a non-trivial
  9329. // conversion from 'this' to the type of a destroying operator delete's
  9330. // first parameter, perform that conversion now.
  9331. if (OperatorDelete->isDestroyingOperatorDelete()) {
  9332. QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
  9333. if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
  9334. // C++ [class.dtor]p13:
  9335. // ... as if for the expression 'delete this' appearing in a
  9336. // non-virtual destructor of the destructor's class.
  9337. ContextRAII SwitchContext(*this, Destructor);
  9338. ExprResult This =
  9339. ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
  9340. assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
  9341. This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
  9342. if (This.isInvalid()) {
  9343. // FIXME: Register this as a context note so that it comes out
  9344. // in the right order.
  9345. Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
  9346. return true;
  9347. }
  9348. ThisArg = This.get();
  9349. }
  9350. }
  9351. DiagnoseUseOfDecl(OperatorDelete, Loc);
  9352. MarkFunctionReferenced(Loc, OperatorDelete);
  9353. Destructor->setOperatorDelete(OperatorDelete, ThisArg);
  9354. }
  9355. }
  9356. return false;
  9357. }
  9358. /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
  9359. /// the well-formednes of the destructor declarator @p D with type @p
  9360. /// R. If there are any errors in the declarator, this routine will
  9361. /// emit diagnostics and set the declarator to invalid. Even if this happens,
  9362. /// will be updated to reflect a well-formed type for the destructor and
  9363. /// returned.
  9364. QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
  9365. StorageClass& SC) {
  9366. // C++ [class.dtor]p1:
  9367. // [...] A typedef-name that names a class is a class-name
  9368. // (7.1.3); however, a typedef-name that names a class shall not
  9369. // be used as the identifier in the declarator for a destructor
  9370. // declaration.
  9371. QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
  9372. if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
  9373. Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
  9374. << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
  9375. else if (const TemplateSpecializationType *TST =
  9376. DeclaratorType->getAs<TemplateSpecializationType>())
  9377. if (TST->isTypeAlias())
  9378. Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
  9379. << DeclaratorType << 1;
  9380. // C++ [class.dtor]p2:
  9381. // A destructor is used to destroy objects of its class type. A
  9382. // destructor takes no parameters, and no return type can be
  9383. // specified for it (not even void). The address of a destructor
  9384. // shall not be taken. A destructor shall not be static. A
  9385. // destructor can be invoked for a const, volatile or const
  9386. // volatile object. A destructor shall not be declared const,
  9387. // volatile or const volatile (9.3.2).
  9388. if (SC == SC_Static) {
  9389. if (!D.isInvalidType())
  9390. Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
  9391. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  9392. << SourceRange(D.getIdentifierLoc())
  9393. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  9394. SC = SC_None;
  9395. }
  9396. if (!D.isInvalidType()) {
  9397. // Destructors don't have return types, but the parser will
  9398. // happily parse something like:
  9399. //
  9400. // class X {
  9401. // float ~X();
  9402. // };
  9403. //
  9404. // The return type will be eliminated later.
  9405. if (D.getDeclSpec().hasTypeSpecifier())
  9406. Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
  9407. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  9408. << SourceRange(D.getIdentifierLoc());
  9409. else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  9410. diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
  9411. SourceLocation(),
  9412. D.getDeclSpec().getConstSpecLoc(),
  9413. D.getDeclSpec().getVolatileSpecLoc(),
  9414. D.getDeclSpec().getRestrictSpecLoc(),
  9415. D.getDeclSpec().getAtomicSpecLoc());
  9416. D.setInvalidType();
  9417. }
  9418. }
  9419. checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
  9420. // C++0x [class.dtor]p2:
  9421. // A destructor shall not be declared with a ref-qualifier.
  9422. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  9423. if (FTI.hasRefQualifier()) {
  9424. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
  9425. << FTI.RefQualifierIsLValueRef
  9426. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  9427. D.setInvalidType();
  9428. }
  9429. // Make sure we don't have any parameters.
  9430. if (FTIHasNonVoidParameters(FTI)) {
  9431. Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
  9432. // Delete the parameters.
  9433. FTI.freeParams();
  9434. D.setInvalidType();
  9435. }
  9436. // Make sure the destructor isn't variadic.
  9437. if (FTI.isVariadic) {
  9438. Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
  9439. D.setInvalidType();
  9440. }
  9441. // Rebuild the function type "R" without any type qualifiers or
  9442. // parameters (in case any of the errors above fired) and with
  9443. // "void" as the return type, since destructors don't have return
  9444. // types.
  9445. if (!D.isInvalidType())
  9446. return R;
  9447. const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
  9448. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  9449. EPI.Variadic = false;
  9450. EPI.TypeQuals = Qualifiers();
  9451. EPI.RefQualifier = RQ_None;
  9452. return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
  9453. }
  9454. static void extendLeft(SourceRange &R, SourceRange Before) {
  9455. if (Before.isInvalid())
  9456. return;
  9457. R.setBegin(Before.getBegin());
  9458. if (R.getEnd().isInvalid())
  9459. R.setEnd(Before.getEnd());
  9460. }
  9461. static void extendRight(SourceRange &R, SourceRange After) {
  9462. if (After.isInvalid())
  9463. return;
  9464. if (R.getBegin().isInvalid())
  9465. R.setBegin(After.getBegin());
  9466. R.setEnd(After.getEnd());
  9467. }
  9468. /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
  9469. /// well-formednes of the conversion function declarator @p D with
  9470. /// type @p R. If there are any errors in the declarator, this routine
  9471. /// will emit diagnostics and return true. Otherwise, it will return
  9472. /// false. Either way, the type @p R will be updated to reflect a
  9473. /// well-formed type for the conversion operator.
  9474. void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
  9475. StorageClass& SC) {
  9476. // C++ [class.conv.fct]p1:
  9477. // Neither parameter types nor return type can be specified. The
  9478. // type of a conversion function (8.3.5) is "function taking no
  9479. // parameter returning conversion-type-id."
  9480. if (SC == SC_Static) {
  9481. if (!D.isInvalidType())
  9482. Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
  9483. << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  9484. << D.getName().getSourceRange();
  9485. D.setInvalidType();
  9486. SC = SC_None;
  9487. }
  9488. TypeSourceInfo *ConvTSI = nullptr;
  9489. QualType ConvType =
  9490. GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
  9491. const DeclSpec &DS = D.getDeclSpec();
  9492. if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
  9493. // Conversion functions don't have return types, but the parser will
  9494. // happily parse something like:
  9495. //
  9496. // class X {
  9497. // float operator bool();
  9498. // };
  9499. //
  9500. // The return type will be changed later anyway.
  9501. Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
  9502. << SourceRange(DS.getTypeSpecTypeLoc())
  9503. << SourceRange(D.getIdentifierLoc());
  9504. D.setInvalidType();
  9505. } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
  9506. // It's also plausible that the user writes type qualifiers in the wrong
  9507. // place, such as:
  9508. // struct S { const operator int(); };
  9509. // FIXME: we could provide a fixit to move the qualifiers onto the
  9510. // conversion type.
  9511. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
  9512. << SourceRange(D.getIdentifierLoc()) << 0;
  9513. D.setInvalidType();
  9514. }
  9515. const auto *Proto = R->castAs<FunctionProtoType>();
  9516. // Make sure we don't have any parameters.
  9517. if (Proto->getNumParams() > 0) {
  9518. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
  9519. // Delete the parameters.
  9520. D.getFunctionTypeInfo().freeParams();
  9521. D.setInvalidType();
  9522. } else if (Proto->isVariadic()) {
  9523. Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
  9524. D.setInvalidType();
  9525. }
  9526. // Diagnose "&operator bool()" and other such nonsense. This
  9527. // is actually a gcc extension which we don't support.
  9528. if (Proto->getReturnType() != ConvType) {
  9529. bool NeedsTypedef = false;
  9530. SourceRange Before, After;
  9531. // Walk the chunks and extract information on them for our diagnostic.
  9532. bool PastFunctionChunk = false;
  9533. for (auto &Chunk : D.type_objects()) {
  9534. switch (Chunk.Kind) {
  9535. case DeclaratorChunk::Function:
  9536. if (!PastFunctionChunk) {
  9537. if (Chunk.Fun.HasTrailingReturnType) {
  9538. TypeSourceInfo *TRT = nullptr;
  9539. GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
  9540. if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
  9541. }
  9542. PastFunctionChunk = true;
  9543. break;
  9544. }
  9545. [[fallthrough]];
  9546. case DeclaratorChunk::Array:
  9547. NeedsTypedef = true;
  9548. extendRight(After, Chunk.getSourceRange());
  9549. break;
  9550. case DeclaratorChunk::Pointer:
  9551. case DeclaratorChunk::BlockPointer:
  9552. case DeclaratorChunk::Reference:
  9553. case DeclaratorChunk::MemberPointer:
  9554. case DeclaratorChunk::Pipe:
  9555. extendLeft(Before, Chunk.getSourceRange());
  9556. break;
  9557. case DeclaratorChunk::Paren:
  9558. extendLeft(Before, Chunk.Loc);
  9559. extendRight(After, Chunk.EndLoc);
  9560. break;
  9561. }
  9562. }
  9563. SourceLocation Loc = Before.isValid() ? Before.getBegin() :
  9564. After.isValid() ? After.getBegin() :
  9565. D.getIdentifierLoc();
  9566. auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
  9567. DB << Before << After;
  9568. if (!NeedsTypedef) {
  9569. DB << /*don't need a typedef*/0;
  9570. // If we can provide a correct fix-it hint, do so.
  9571. if (After.isInvalid() && ConvTSI) {
  9572. SourceLocation InsertLoc =
  9573. getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
  9574. DB << FixItHint::CreateInsertion(InsertLoc, " ")
  9575. << FixItHint::CreateInsertionFromRange(
  9576. InsertLoc, CharSourceRange::getTokenRange(Before))
  9577. << FixItHint::CreateRemoval(Before);
  9578. }
  9579. } else if (!Proto->getReturnType()->isDependentType()) {
  9580. DB << /*typedef*/1 << Proto->getReturnType();
  9581. } else if (getLangOpts().CPlusPlus11) {
  9582. DB << /*alias template*/2 << Proto->getReturnType();
  9583. } else {
  9584. DB << /*might not be fixable*/3;
  9585. }
  9586. // Recover by incorporating the other type chunks into the result type.
  9587. // Note, this does *not* change the name of the function. This is compatible
  9588. // with the GCC extension:
  9589. // struct S { &operator int(); } s;
  9590. // int &r = s.operator int(); // ok in GCC
  9591. // S::operator int&() {} // error in GCC, function name is 'operator int'.
  9592. ConvType = Proto->getReturnType();
  9593. }
  9594. // C++ [class.conv.fct]p4:
  9595. // The conversion-type-id shall not represent a function type nor
  9596. // an array type.
  9597. if (ConvType->isArrayType()) {
  9598. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
  9599. ConvType = Context.getPointerType(ConvType);
  9600. D.setInvalidType();
  9601. } else if (ConvType->isFunctionType()) {
  9602. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
  9603. ConvType = Context.getPointerType(ConvType);
  9604. D.setInvalidType();
  9605. }
  9606. // Rebuild the function type "R" without any parameters (in case any
  9607. // of the errors above fired) and with the conversion type as the
  9608. // return type.
  9609. if (D.isInvalidType())
  9610. R = Context.getFunctionType(ConvType, std::nullopt,
  9611. Proto->getExtProtoInfo());
  9612. // C++0x explicit conversion operators.
  9613. if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
  9614. Diag(DS.getExplicitSpecLoc(),
  9615. getLangOpts().CPlusPlus11
  9616. ? diag::warn_cxx98_compat_explicit_conversion_functions
  9617. : diag::ext_explicit_conversion_functions)
  9618. << SourceRange(DS.getExplicitSpecRange());
  9619. }
  9620. /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
  9621. /// the declaration of the given C++ conversion function. This routine
  9622. /// is responsible for recording the conversion function in the C++
  9623. /// class, if possible.
  9624. Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
  9625. assert(Conversion && "Expected to receive a conversion function declaration");
  9626. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
  9627. // Make sure we aren't redeclaring the conversion function.
  9628. QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
  9629. // C++ [class.conv.fct]p1:
  9630. // [...] A conversion function is never used to convert a
  9631. // (possibly cv-qualified) object to the (possibly cv-qualified)
  9632. // same object type (or a reference to it), to a (possibly
  9633. // cv-qualified) base class of that type (or a reference to it),
  9634. // or to (possibly cv-qualified) void.
  9635. QualType ClassType
  9636. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  9637. if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
  9638. ConvType = ConvTypeRef->getPointeeType();
  9639. if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
  9640. Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  9641. /* Suppress diagnostics for instantiations. */;
  9642. else if (Conversion->size_overridden_methods() != 0)
  9643. /* Suppress diagnostics for overriding virtual function in a base class. */;
  9644. else if (ConvType->isRecordType()) {
  9645. ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
  9646. if (ConvType == ClassType)
  9647. Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
  9648. << ClassType;
  9649. else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
  9650. Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
  9651. << ClassType << ConvType;
  9652. } else if (ConvType->isVoidType()) {
  9653. Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
  9654. << ClassType << ConvType;
  9655. }
  9656. if (FunctionTemplateDecl *ConversionTemplate
  9657. = Conversion->getDescribedFunctionTemplate())
  9658. return ConversionTemplate;
  9659. return Conversion;
  9660. }
  9661. namespace {
  9662. /// Utility class to accumulate and print a diagnostic listing the invalid
  9663. /// specifier(s) on a declaration.
  9664. struct BadSpecifierDiagnoser {
  9665. BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
  9666. : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
  9667. ~BadSpecifierDiagnoser() {
  9668. Diagnostic << Specifiers;
  9669. }
  9670. template<typename T> void check(SourceLocation SpecLoc, T Spec) {
  9671. return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
  9672. }
  9673. void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
  9674. return check(SpecLoc,
  9675. DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
  9676. }
  9677. void check(SourceLocation SpecLoc, const char *Spec) {
  9678. if (SpecLoc.isInvalid()) return;
  9679. Diagnostic << SourceRange(SpecLoc, SpecLoc);
  9680. if (!Specifiers.empty()) Specifiers += " ";
  9681. Specifiers += Spec;
  9682. }
  9683. Sema &S;
  9684. Sema::SemaDiagnosticBuilder Diagnostic;
  9685. std::string Specifiers;
  9686. };
  9687. }
  9688. /// Check the validity of a declarator that we parsed for a deduction-guide.
  9689. /// These aren't actually declarators in the grammar, so we need to check that
  9690. /// the user didn't specify any pieces that are not part of the deduction-guide
  9691. /// grammar.
  9692. void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
  9693. StorageClass &SC) {
  9694. TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
  9695. TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
  9696. assert(GuidedTemplateDecl && "missing template decl for deduction guide");
  9697. // C++ [temp.deduct.guide]p3:
  9698. // A deduction-gide shall be declared in the same scope as the
  9699. // corresponding class template.
  9700. if (!CurContext->getRedeclContext()->Equals(
  9701. GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
  9702. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
  9703. << GuidedTemplateDecl;
  9704. Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
  9705. }
  9706. auto &DS = D.getMutableDeclSpec();
  9707. // We leave 'friend' and 'virtual' to be rejected in the normal way.
  9708. if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
  9709. DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
  9710. DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
  9711. BadSpecifierDiagnoser Diagnoser(
  9712. *this, D.getIdentifierLoc(),
  9713. diag::err_deduction_guide_invalid_specifier);
  9714. Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
  9715. DS.ClearStorageClassSpecs();
  9716. SC = SC_None;
  9717. // 'explicit' is permitted.
  9718. Diagnoser.check(DS.getInlineSpecLoc(), "inline");
  9719. Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
  9720. Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
  9721. DS.ClearConstexprSpec();
  9722. Diagnoser.check(DS.getConstSpecLoc(), "const");
  9723. Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
  9724. Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
  9725. Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
  9726. Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
  9727. DS.ClearTypeQualifiers();
  9728. Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
  9729. Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
  9730. Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
  9731. Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
  9732. DS.ClearTypeSpecType();
  9733. }
  9734. if (D.isInvalidType())
  9735. return;
  9736. // Check the declarator is simple enough.
  9737. bool FoundFunction = false;
  9738. for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
  9739. if (Chunk.Kind == DeclaratorChunk::Paren)
  9740. continue;
  9741. if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
  9742. Diag(D.getDeclSpec().getBeginLoc(),
  9743. diag::err_deduction_guide_with_complex_decl)
  9744. << D.getSourceRange();
  9745. break;
  9746. }
  9747. if (!Chunk.Fun.hasTrailingReturnType()) {
  9748. Diag(D.getName().getBeginLoc(),
  9749. diag::err_deduction_guide_no_trailing_return_type);
  9750. break;
  9751. }
  9752. // Check that the return type is written as a specialization of
  9753. // the template specified as the deduction-guide's name.
  9754. // The template name may not be qualified. [temp.deduct.guide]
  9755. ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
  9756. TypeSourceInfo *TSI = nullptr;
  9757. QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
  9758. assert(TSI && "deduction guide has valid type but invalid return type?");
  9759. bool AcceptableReturnType = false;
  9760. bool MightInstantiateToSpecialization = false;
  9761. if (auto RetTST =
  9762. TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
  9763. TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
  9764. bool TemplateMatches =
  9765. Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
  9766. auto TKind = SpecifiedName.getKind();
  9767. // A Using TemplateName can't actually be valid (either it's qualified, or
  9768. // we're in the wrong scope). But we have diagnosed these problems
  9769. // already.
  9770. bool SimplyWritten = TKind == TemplateName::Template ||
  9771. TKind == TemplateName::UsingTemplate;
  9772. if (SimplyWritten && TemplateMatches)
  9773. AcceptableReturnType = true;
  9774. else {
  9775. // This could still instantiate to the right type, unless we know it
  9776. // names the wrong class template.
  9777. auto *TD = SpecifiedName.getAsTemplateDecl();
  9778. MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
  9779. !TemplateMatches);
  9780. }
  9781. } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
  9782. MightInstantiateToSpecialization = true;
  9783. }
  9784. if (!AcceptableReturnType) {
  9785. Diag(TSI->getTypeLoc().getBeginLoc(),
  9786. diag::err_deduction_guide_bad_trailing_return_type)
  9787. << GuidedTemplate << TSI->getType()
  9788. << MightInstantiateToSpecialization
  9789. << TSI->getTypeLoc().getSourceRange();
  9790. }
  9791. // Keep going to check that we don't have any inner declarator pieces (we
  9792. // could still have a function returning a pointer to a function).
  9793. FoundFunction = true;
  9794. }
  9795. if (D.isFunctionDefinition())
  9796. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
  9797. }
  9798. //===----------------------------------------------------------------------===//
  9799. // Namespace Handling
  9800. //===----------------------------------------------------------------------===//
  9801. /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
  9802. /// reopened.
  9803. static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
  9804. SourceLocation Loc,
  9805. IdentifierInfo *II, bool *IsInline,
  9806. NamespaceDecl *PrevNS) {
  9807. assert(*IsInline != PrevNS->isInline());
  9808. // 'inline' must appear on the original definition, but not necessarily
  9809. // on all extension definitions, so the note should point to the first
  9810. // definition to avoid confusion.
  9811. PrevNS = PrevNS->getFirstDecl();
  9812. if (PrevNS->isInline())
  9813. // The user probably just forgot the 'inline', so suggest that it
  9814. // be added back.
  9815. S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
  9816. << FixItHint::CreateInsertion(KeywordLoc, "inline ");
  9817. else
  9818. S.Diag(Loc, diag::err_inline_namespace_mismatch);
  9819. S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
  9820. *IsInline = PrevNS->isInline();
  9821. }
  9822. /// ActOnStartNamespaceDef - This is called at the start of a namespace
  9823. /// definition.
  9824. Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
  9825. SourceLocation InlineLoc,
  9826. SourceLocation NamespaceLoc,
  9827. SourceLocation IdentLoc, IdentifierInfo *II,
  9828. SourceLocation LBrace,
  9829. const ParsedAttributesView &AttrList,
  9830. UsingDirectiveDecl *&UD, bool IsNested) {
  9831. SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
  9832. // For anonymous namespace, take the location of the left brace.
  9833. SourceLocation Loc = II ? IdentLoc : LBrace;
  9834. bool IsInline = InlineLoc.isValid();
  9835. bool IsInvalid = false;
  9836. bool IsStd = false;
  9837. bool AddToKnown = false;
  9838. Scope *DeclRegionScope = NamespcScope->getParent();
  9839. NamespaceDecl *PrevNS = nullptr;
  9840. if (II) {
  9841. // C++ [namespace.def]p2:
  9842. // The identifier in an original-namespace-definition shall not
  9843. // have been previously defined in the declarative region in
  9844. // which the original-namespace-definition appears. The
  9845. // identifier in an original-namespace-definition is the name of
  9846. // the namespace. Subsequently in that declarative region, it is
  9847. // treated as an original-namespace-name.
  9848. //
  9849. // Since namespace names are unique in their scope, and we don't
  9850. // look through using directives, just look for any ordinary names
  9851. // as if by qualified name lookup.
  9852. LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
  9853. ForExternalRedeclaration);
  9854. LookupQualifiedName(R, CurContext->getRedeclContext());
  9855. NamedDecl *PrevDecl =
  9856. R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
  9857. PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
  9858. if (PrevNS) {
  9859. // This is an extended namespace definition.
  9860. if (IsInline != PrevNS->isInline())
  9861. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
  9862. &IsInline, PrevNS);
  9863. } else if (PrevDecl) {
  9864. // This is an invalid name redefinition.
  9865. Diag(Loc, diag::err_redefinition_different_kind)
  9866. << II;
  9867. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  9868. IsInvalid = true;
  9869. // Continue on to push Namespc as current DeclContext and return it.
  9870. } else if (II->isStr("std") &&
  9871. CurContext->getRedeclContext()->isTranslationUnit()) {
  9872. // This is the first "real" definition of the namespace "std", so update
  9873. // our cache of the "std" namespace to point at this definition.
  9874. PrevNS = getStdNamespace();
  9875. IsStd = true;
  9876. AddToKnown = !IsInline;
  9877. } else {
  9878. // We've seen this namespace for the first time.
  9879. AddToKnown = !IsInline;
  9880. }
  9881. } else {
  9882. // Anonymous namespaces.
  9883. // Determine whether the parent already has an anonymous namespace.
  9884. DeclContext *Parent = CurContext->getRedeclContext();
  9885. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  9886. PrevNS = TU->getAnonymousNamespace();
  9887. } else {
  9888. NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
  9889. PrevNS = ND->getAnonymousNamespace();
  9890. }
  9891. if (PrevNS && IsInline != PrevNS->isInline())
  9892. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
  9893. &IsInline, PrevNS);
  9894. }
  9895. NamespaceDecl *Namespc = NamespaceDecl::Create(
  9896. Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
  9897. if (IsInvalid)
  9898. Namespc->setInvalidDecl();
  9899. ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
  9900. AddPragmaAttributes(DeclRegionScope, Namespc);
  9901. // FIXME: Should we be merging attributes?
  9902. if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
  9903. PushNamespaceVisibilityAttr(Attr, Loc);
  9904. if (IsStd)
  9905. StdNamespace = Namespc;
  9906. if (AddToKnown)
  9907. KnownNamespaces[Namespc] = false;
  9908. if (II) {
  9909. PushOnScopeChains(Namespc, DeclRegionScope);
  9910. } else {
  9911. // Link the anonymous namespace into its parent.
  9912. DeclContext *Parent = CurContext->getRedeclContext();
  9913. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  9914. TU->setAnonymousNamespace(Namespc);
  9915. } else {
  9916. cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
  9917. }
  9918. CurContext->addDecl(Namespc);
  9919. // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
  9920. // behaves as if it were replaced by
  9921. // namespace unique { /* empty body */ }
  9922. // using namespace unique;
  9923. // namespace unique { namespace-body }
  9924. // where all occurrences of 'unique' in a translation unit are
  9925. // replaced by the same identifier and this identifier differs
  9926. // from all other identifiers in the entire program.
  9927. // We just create the namespace with an empty name and then add an
  9928. // implicit using declaration, just like the standard suggests.
  9929. //
  9930. // CodeGen enforces the "universally unique" aspect by giving all
  9931. // declarations semantically contained within an anonymous
  9932. // namespace internal linkage.
  9933. if (!PrevNS) {
  9934. UD = UsingDirectiveDecl::Create(Context, Parent,
  9935. /* 'using' */ LBrace,
  9936. /* 'namespace' */ SourceLocation(),
  9937. /* qualifier */ NestedNameSpecifierLoc(),
  9938. /* identifier */ SourceLocation(),
  9939. Namespc,
  9940. /* Ancestor */ Parent);
  9941. UD->setImplicit();
  9942. Parent->addDecl(UD);
  9943. }
  9944. }
  9945. ActOnDocumentableDecl(Namespc);
  9946. // Although we could have an invalid decl (i.e. the namespace name is a
  9947. // redefinition), push it as current DeclContext and try to continue parsing.
  9948. // FIXME: We should be able to push Namespc here, so that the each DeclContext
  9949. // for the namespace has the declarations that showed up in that particular
  9950. // namespace definition.
  9951. PushDeclContext(NamespcScope, Namespc);
  9952. return Namespc;
  9953. }
  9954. /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
  9955. /// is a namespace alias, returns the namespace it points to.
  9956. static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
  9957. if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
  9958. return AD->getNamespace();
  9959. return dyn_cast_or_null<NamespaceDecl>(D);
  9960. }
  9961. /// ActOnFinishNamespaceDef - This callback is called after a namespace is
  9962. /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
  9963. void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
  9964. NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
  9965. assert(Namespc && "Invalid parameter, expected NamespaceDecl");
  9966. Namespc->setRBraceLoc(RBrace);
  9967. PopDeclContext();
  9968. if (Namespc->hasAttr<VisibilityAttr>())
  9969. PopPragmaVisibility(true, RBrace);
  9970. // If this namespace contains an export-declaration, export it now.
  9971. if (DeferredExportedNamespaces.erase(Namespc))
  9972. Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
  9973. }
  9974. CXXRecordDecl *Sema::getStdBadAlloc() const {
  9975. return cast_or_null<CXXRecordDecl>(
  9976. StdBadAlloc.get(Context.getExternalSource()));
  9977. }
  9978. EnumDecl *Sema::getStdAlignValT() const {
  9979. return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
  9980. }
  9981. NamespaceDecl *Sema::getStdNamespace() const {
  9982. return cast_or_null<NamespaceDecl>(
  9983. StdNamespace.get(Context.getExternalSource()));
  9984. }
  9985. NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
  9986. if (!StdExperimentalNamespaceCache) {
  9987. if (auto Std = getStdNamespace()) {
  9988. LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
  9989. SourceLocation(), LookupNamespaceName);
  9990. if (!LookupQualifiedName(Result, Std) ||
  9991. !(StdExperimentalNamespaceCache =
  9992. Result.getAsSingle<NamespaceDecl>()))
  9993. Result.suppressDiagnostics();
  9994. }
  9995. }
  9996. return StdExperimentalNamespaceCache;
  9997. }
  9998. namespace {
  9999. enum UnsupportedSTLSelect {
  10000. USS_InvalidMember,
  10001. USS_MissingMember,
  10002. USS_NonTrivial,
  10003. USS_Other
  10004. };
  10005. struct InvalidSTLDiagnoser {
  10006. Sema &S;
  10007. SourceLocation Loc;
  10008. QualType TyForDiags;
  10009. QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
  10010. const VarDecl *VD = nullptr) {
  10011. {
  10012. auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
  10013. << TyForDiags << ((int)Sel);
  10014. if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
  10015. assert(!Name.empty());
  10016. D << Name;
  10017. }
  10018. }
  10019. if (Sel == USS_InvalidMember) {
  10020. S.Diag(VD->getLocation(), diag::note_var_declared_here)
  10021. << VD << VD->getSourceRange();
  10022. }
  10023. return QualType();
  10024. }
  10025. };
  10026. } // namespace
  10027. QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
  10028. SourceLocation Loc,
  10029. ComparisonCategoryUsage Usage) {
  10030. assert(getLangOpts().CPlusPlus &&
  10031. "Looking for comparison category type outside of C++.");
  10032. // Use an elaborated type for diagnostics which has a name containing the
  10033. // prepended 'std' namespace but not any inline namespace names.
  10034. auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
  10035. auto *NNS =
  10036. NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
  10037. return Context.getElaboratedType(ETK_None, NNS, Info->getType());
  10038. };
  10039. // Check if we've already successfully checked the comparison category type
  10040. // before. If so, skip checking it again.
  10041. ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
  10042. if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
  10043. // The only thing we need to check is that the type has a reachable
  10044. // definition in the current context.
  10045. if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
  10046. return QualType();
  10047. return Info->getType();
  10048. }
  10049. // If lookup failed
  10050. if (!Info) {
  10051. std::string NameForDiags = "std::";
  10052. NameForDiags += ComparisonCategories::getCategoryString(Kind);
  10053. Diag(Loc, diag::err_implied_comparison_category_type_not_found)
  10054. << NameForDiags << (int)Usage;
  10055. return QualType();
  10056. }
  10057. assert(Info->Kind == Kind);
  10058. assert(Info->Record);
  10059. // Update the Record decl in case we encountered a forward declaration on our
  10060. // first pass. FIXME: This is a bit of a hack.
  10061. if (Info->Record->hasDefinition())
  10062. Info->Record = Info->Record->getDefinition();
  10063. if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
  10064. return QualType();
  10065. InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
  10066. if (!Info->Record->isTriviallyCopyable())
  10067. return UnsupportedSTLError(USS_NonTrivial);
  10068. for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
  10069. CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
  10070. // Tolerate empty base classes.
  10071. if (Base->isEmpty())
  10072. continue;
  10073. // Reject STL implementations which have at least one non-empty base.
  10074. return UnsupportedSTLError();
  10075. }
  10076. // Check that the STL has implemented the types using a single integer field.
  10077. // This expectation allows better codegen for builtin operators. We require:
  10078. // (1) The class has exactly one field.
  10079. // (2) The field is an integral or enumeration type.
  10080. auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
  10081. if (std::distance(FIt, FEnd) != 1 ||
  10082. !FIt->getType()->isIntegralOrEnumerationType()) {
  10083. return UnsupportedSTLError();
  10084. }
  10085. // Build each of the require values and store them in Info.
  10086. for (ComparisonCategoryResult CCR :
  10087. ComparisonCategories::getPossibleResultsForType(Kind)) {
  10088. StringRef MemName = ComparisonCategories::getResultString(CCR);
  10089. ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
  10090. if (!ValInfo)
  10091. return UnsupportedSTLError(USS_MissingMember, MemName);
  10092. VarDecl *VD = ValInfo->VD;
  10093. assert(VD && "should not be null!");
  10094. // Attempt to diagnose reasons why the STL definition of this type
  10095. // might be foobar, including it failing to be a constant expression.
  10096. // TODO Handle more ways the lookup or result can be invalid.
  10097. if (!VD->isStaticDataMember() ||
  10098. !VD->isUsableInConstantExpressions(Context))
  10099. return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
  10100. // Attempt to evaluate the var decl as a constant expression and extract
  10101. // the value of its first field as a ICE. If this fails, the STL
  10102. // implementation is not supported.
  10103. if (!ValInfo->hasValidIntValue())
  10104. return UnsupportedSTLError();
  10105. MarkVariableReferenced(Loc, VD);
  10106. }
  10107. // We've successfully built the required types and expressions. Update
  10108. // the cache and return the newly cached value.
  10109. FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
  10110. return Info->getType();
  10111. }
  10112. /// Retrieve the special "std" namespace, which may require us to
  10113. /// implicitly define the namespace.
  10114. NamespaceDecl *Sema::getOrCreateStdNamespace() {
  10115. if (!StdNamespace) {
  10116. // The "std" namespace has not yet been defined, so build one implicitly.
  10117. StdNamespace = NamespaceDecl::Create(
  10118. Context, Context.getTranslationUnitDecl(),
  10119. /*Inline=*/false, SourceLocation(), SourceLocation(),
  10120. &PP.getIdentifierTable().get("std"),
  10121. /*PrevDecl=*/nullptr, /*Nested=*/false);
  10122. getStdNamespace()->setImplicit(true);
  10123. }
  10124. return getStdNamespace();
  10125. }
  10126. bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
  10127. assert(getLangOpts().CPlusPlus &&
  10128. "Looking for std::initializer_list outside of C++.");
  10129. // We're looking for implicit instantiations of
  10130. // template <typename E> class std::initializer_list.
  10131. if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
  10132. return false;
  10133. ClassTemplateDecl *Template = nullptr;
  10134. const TemplateArgument *Arguments = nullptr;
  10135. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  10136. ClassTemplateSpecializationDecl *Specialization =
  10137. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  10138. if (!Specialization)
  10139. return false;
  10140. Template = Specialization->getSpecializedTemplate();
  10141. Arguments = Specialization->getTemplateArgs().data();
  10142. } else if (const TemplateSpecializationType *TST =
  10143. Ty->getAs<TemplateSpecializationType>()) {
  10144. Template = dyn_cast_or_null<ClassTemplateDecl>(
  10145. TST->getTemplateName().getAsTemplateDecl());
  10146. Arguments = TST->template_arguments().begin();
  10147. }
  10148. if (!Template)
  10149. return false;
  10150. if (!StdInitializerList) {
  10151. // Haven't recognized std::initializer_list yet, maybe this is it.
  10152. CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
  10153. if (TemplateClass->getIdentifier() !=
  10154. &PP.getIdentifierTable().get("initializer_list") ||
  10155. !getStdNamespace()->InEnclosingNamespaceSetOf(
  10156. TemplateClass->getDeclContext()))
  10157. return false;
  10158. // This is a template called std::initializer_list, but is it the right
  10159. // template?
  10160. TemplateParameterList *Params = Template->getTemplateParameters();
  10161. if (Params->getMinRequiredArguments() != 1)
  10162. return false;
  10163. if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
  10164. return false;
  10165. // It's the right template.
  10166. StdInitializerList = Template;
  10167. }
  10168. if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
  10169. return false;
  10170. // This is an instance of std::initializer_list. Find the argument type.
  10171. if (Element)
  10172. *Element = Arguments[0].getAsType();
  10173. return true;
  10174. }
  10175. static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
  10176. NamespaceDecl *Std = S.getStdNamespace();
  10177. if (!Std) {
  10178. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  10179. return nullptr;
  10180. }
  10181. LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
  10182. Loc, Sema::LookupOrdinaryName);
  10183. if (!S.LookupQualifiedName(Result, Std)) {
  10184. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  10185. return nullptr;
  10186. }
  10187. ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
  10188. if (!Template) {
  10189. Result.suppressDiagnostics();
  10190. // We found something weird. Complain about the first thing we found.
  10191. NamedDecl *Found = *Result.begin();
  10192. S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
  10193. return nullptr;
  10194. }
  10195. // We found some template called std::initializer_list. Now verify that it's
  10196. // correct.
  10197. TemplateParameterList *Params = Template->getTemplateParameters();
  10198. if (Params->getMinRequiredArguments() != 1 ||
  10199. !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  10200. S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
  10201. return nullptr;
  10202. }
  10203. return Template;
  10204. }
  10205. QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
  10206. if (!StdInitializerList) {
  10207. StdInitializerList = LookupStdInitializerList(*this, Loc);
  10208. if (!StdInitializerList)
  10209. return QualType();
  10210. }
  10211. TemplateArgumentListInfo Args(Loc, Loc);
  10212. Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
  10213. Context.getTrivialTypeSourceInfo(Element,
  10214. Loc)));
  10215. return Context.getElaboratedType(
  10216. ElaboratedTypeKeyword::ETK_None,
  10217. NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()),
  10218. CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
  10219. }
  10220. bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
  10221. // C++ [dcl.init.list]p2:
  10222. // A constructor is an initializer-list constructor if its first parameter
  10223. // is of type std::initializer_list<E> or reference to possibly cv-qualified
  10224. // std::initializer_list<E> for some type E, and either there are no other
  10225. // parameters or else all other parameters have default arguments.
  10226. if (!Ctor->hasOneParamOrDefaultArgs())
  10227. return false;
  10228. QualType ArgType = Ctor->getParamDecl(0)->getType();
  10229. if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
  10230. ArgType = RT->getPointeeType().getUnqualifiedType();
  10231. return isStdInitializerList(ArgType, nullptr);
  10232. }
  10233. /// Determine whether a using statement is in a context where it will be
  10234. /// apply in all contexts.
  10235. static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
  10236. switch (CurContext->getDeclKind()) {
  10237. case Decl::TranslationUnit:
  10238. return true;
  10239. case Decl::LinkageSpec:
  10240. return IsUsingDirectiveInToplevelContext(CurContext->getParent());
  10241. default:
  10242. return false;
  10243. }
  10244. }
  10245. namespace {
  10246. // Callback to only accept typo corrections that are namespaces.
  10247. class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
  10248. public:
  10249. bool ValidateCandidate(const TypoCorrection &candidate) override {
  10250. if (NamedDecl *ND = candidate.getCorrectionDecl())
  10251. return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
  10252. return false;
  10253. }
  10254. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  10255. return std::make_unique<NamespaceValidatorCCC>(*this);
  10256. }
  10257. };
  10258. }
  10259. static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
  10260. CXXScopeSpec &SS,
  10261. SourceLocation IdentLoc,
  10262. IdentifierInfo *Ident) {
  10263. R.clear();
  10264. NamespaceValidatorCCC CCC{};
  10265. if (TypoCorrection Corrected =
  10266. S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
  10267. Sema::CTK_ErrorRecovery)) {
  10268. if (DeclContext *DC = S.computeDeclContext(SS, false)) {
  10269. std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
  10270. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  10271. Ident->getName().equals(CorrectedStr);
  10272. S.diagnoseTypo(Corrected,
  10273. S.PDiag(diag::err_using_directive_member_suggest)
  10274. << Ident << DC << DroppedSpecifier << SS.getRange(),
  10275. S.PDiag(diag::note_namespace_defined_here));
  10276. } else {
  10277. S.diagnoseTypo(Corrected,
  10278. S.PDiag(diag::err_using_directive_suggest) << Ident,
  10279. S.PDiag(diag::note_namespace_defined_here));
  10280. }
  10281. R.addDecl(Corrected.getFoundDecl());
  10282. return true;
  10283. }
  10284. return false;
  10285. }
  10286. Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
  10287. SourceLocation NamespcLoc, CXXScopeSpec &SS,
  10288. SourceLocation IdentLoc,
  10289. IdentifierInfo *NamespcName,
  10290. const ParsedAttributesView &AttrList) {
  10291. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  10292. assert(NamespcName && "Invalid NamespcName.");
  10293. assert(IdentLoc.isValid() && "Invalid NamespceName location.");
  10294. // This can only happen along a recovery path.
  10295. while (S->isTemplateParamScope())
  10296. S = S->getParent();
  10297. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  10298. UsingDirectiveDecl *UDir = nullptr;
  10299. NestedNameSpecifier *Qualifier = nullptr;
  10300. if (SS.isSet())
  10301. Qualifier = SS.getScopeRep();
  10302. // Lookup namespace name.
  10303. LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
  10304. LookupParsedName(R, S, &SS);
  10305. if (R.isAmbiguous())
  10306. return nullptr;
  10307. if (R.empty()) {
  10308. R.clear();
  10309. // Allow "using namespace std;" or "using namespace ::std;" even if
  10310. // "std" hasn't been defined yet, for GCC compatibility.
  10311. if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
  10312. NamespcName->isStr("std")) {
  10313. Diag(IdentLoc, diag::ext_using_undefined_std);
  10314. R.addDecl(getOrCreateStdNamespace());
  10315. R.resolveKind();
  10316. }
  10317. // Otherwise, attempt typo correction.
  10318. else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
  10319. }
  10320. if (!R.empty()) {
  10321. NamedDecl *Named = R.getRepresentativeDecl();
  10322. NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
  10323. assert(NS && "expected namespace decl");
  10324. // The use of a nested name specifier may trigger deprecation warnings.
  10325. DiagnoseUseOfDecl(Named, IdentLoc);
  10326. // C++ [namespace.udir]p1:
  10327. // A using-directive specifies that the names in the nominated
  10328. // namespace can be used in the scope in which the
  10329. // using-directive appears after the using-directive. During
  10330. // unqualified name lookup (3.4.1), the names appear as if they
  10331. // were declared in the nearest enclosing namespace which
  10332. // contains both the using-directive and the nominated
  10333. // namespace. [Note: in this context, "contains" means "contains
  10334. // directly or indirectly". ]
  10335. // Find enclosing context containing both using-directive and
  10336. // nominated namespace.
  10337. DeclContext *CommonAncestor = NS;
  10338. while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
  10339. CommonAncestor = CommonAncestor->getParent();
  10340. UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
  10341. SS.getWithLocInContext(Context),
  10342. IdentLoc, Named, CommonAncestor);
  10343. if (IsUsingDirectiveInToplevelContext(CurContext) &&
  10344. !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
  10345. Diag(IdentLoc, diag::warn_using_directive_in_header);
  10346. }
  10347. PushUsingDirective(S, UDir);
  10348. } else {
  10349. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  10350. }
  10351. if (UDir)
  10352. ProcessDeclAttributeList(S, UDir, AttrList);
  10353. return UDir;
  10354. }
  10355. void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
  10356. // If the scope has an associated entity and the using directive is at
  10357. // namespace or translation unit scope, add the UsingDirectiveDecl into
  10358. // its lookup structure so qualified name lookup can find it.
  10359. DeclContext *Ctx = S->getEntity();
  10360. if (Ctx && !Ctx->isFunctionOrMethod())
  10361. Ctx->addDecl(UDir);
  10362. else
  10363. // Otherwise, it is at block scope. The using-directives will affect lookup
  10364. // only to the end of the scope.
  10365. S->PushUsingDirective(UDir);
  10366. }
  10367. Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
  10368. SourceLocation UsingLoc,
  10369. SourceLocation TypenameLoc, CXXScopeSpec &SS,
  10370. UnqualifiedId &Name,
  10371. SourceLocation EllipsisLoc,
  10372. const ParsedAttributesView &AttrList) {
  10373. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  10374. if (SS.isEmpty()) {
  10375. Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
  10376. return nullptr;
  10377. }
  10378. switch (Name.getKind()) {
  10379. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  10380. case UnqualifiedIdKind::IK_Identifier:
  10381. case UnqualifiedIdKind::IK_OperatorFunctionId:
  10382. case UnqualifiedIdKind::IK_LiteralOperatorId:
  10383. case UnqualifiedIdKind::IK_ConversionFunctionId:
  10384. break;
  10385. case UnqualifiedIdKind::IK_ConstructorName:
  10386. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  10387. // C++11 inheriting constructors.
  10388. Diag(Name.getBeginLoc(),
  10389. getLangOpts().CPlusPlus11
  10390. ? diag::warn_cxx98_compat_using_decl_constructor
  10391. : diag::err_using_decl_constructor)
  10392. << SS.getRange();
  10393. if (getLangOpts().CPlusPlus11) break;
  10394. return nullptr;
  10395. case UnqualifiedIdKind::IK_DestructorName:
  10396. Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
  10397. return nullptr;
  10398. case UnqualifiedIdKind::IK_TemplateId:
  10399. Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
  10400. << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
  10401. return nullptr;
  10402. case UnqualifiedIdKind::IK_DeductionGuideName:
  10403. llvm_unreachable("cannot parse qualified deduction guide name");
  10404. }
  10405. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  10406. DeclarationName TargetName = TargetNameInfo.getName();
  10407. if (!TargetName)
  10408. return nullptr;
  10409. // Warn about access declarations.
  10410. if (UsingLoc.isInvalid()) {
  10411. Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
  10412. ? diag::err_access_decl
  10413. : diag::warn_access_decl_deprecated)
  10414. << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
  10415. }
  10416. if (EllipsisLoc.isInvalid()) {
  10417. if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
  10418. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
  10419. return nullptr;
  10420. } else {
  10421. if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
  10422. !TargetNameInfo.containsUnexpandedParameterPack()) {
  10423. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  10424. << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
  10425. EllipsisLoc = SourceLocation();
  10426. }
  10427. }
  10428. NamedDecl *UD =
  10429. BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
  10430. SS, TargetNameInfo, EllipsisLoc, AttrList,
  10431. /*IsInstantiation*/ false,
  10432. AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
  10433. if (UD)
  10434. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  10435. return UD;
  10436. }
  10437. Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
  10438. SourceLocation UsingLoc,
  10439. SourceLocation EnumLoc,
  10440. SourceLocation IdentLoc,
  10441. IdentifierInfo &II, CXXScopeSpec *SS) {
  10442. assert(!SS->isInvalid() && "ScopeSpec is invalid");
  10443. TypeSourceInfo *TSI = nullptr;
  10444. QualType EnumTy = GetTypeFromParser(
  10445. getTypeName(II, IdentLoc, S, SS, /*isClassName=*/false,
  10446. /*HasTrailingDot=*/false,
  10447. /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
  10448. /*WantNontrivialTypeSourceInfo=*/true),
  10449. &TSI);
  10450. if (EnumTy.isNull()) {
  10451. Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
  10452. ? diag::err_using_enum_is_dependent
  10453. : diag::err_unknown_typename)
  10454. << II.getName()
  10455. << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc);
  10456. return nullptr;
  10457. }
  10458. auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
  10459. if (!Enum) {
  10460. Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
  10461. return nullptr;
  10462. }
  10463. if (auto *Def = Enum->getDefinition())
  10464. Enum = Def;
  10465. if (TSI == nullptr)
  10466. TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
  10467. auto *UD =
  10468. BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
  10469. if (UD)
  10470. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  10471. return UD;
  10472. }
  10473. /// Determine whether a using declaration considers the given
  10474. /// declarations as "equivalent", e.g., if they are redeclarations of
  10475. /// the same entity or are both typedefs of the same type.
  10476. static bool
  10477. IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
  10478. if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
  10479. return true;
  10480. if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
  10481. if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
  10482. return Context.hasSameType(TD1->getUnderlyingType(),
  10483. TD2->getUnderlyingType());
  10484. // Two using_if_exists using-declarations are equivalent if both are
  10485. // unresolved.
  10486. if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
  10487. isa<UnresolvedUsingIfExistsDecl>(D2))
  10488. return true;
  10489. return false;
  10490. }
  10491. /// Determines whether to create a using shadow decl for a particular
  10492. /// decl, given the set of decls existing prior to this using lookup.
  10493. bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
  10494. const LookupResult &Previous,
  10495. UsingShadowDecl *&PrevShadow) {
  10496. // Diagnose finding a decl which is not from a base class of the
  10497. // current class. We do this now because there are cases where this
  10498. // function will silently decide not to build a shadow decl, which
  10499. // will pre-empt further diagnostics.
  10500. //
  10501. // We don't need to do this in C++11 because we do the check once on
  10502. // the qualifier.
  10503. //
  10504. // FIXME: diagnose the following if we care enough:
  10505. // struct A { int foo; };
  10506. // struct B : A { using A::foo; };
  10507. // template <class T> struct C : A {};
  10508. // template <class T> struct D : C<T> { using B::foo; } // <---
  10509. // This is invalid (during instantiation) in C++03 because B::foo
  10510. // resolves to the using decl in B, which is not a base class of D<T>.
  10511. // We can't diagnose it immediately because C<T> is an unknown
  10512. // specialization. The UsingShadowDecl in D<T> then points directly
  10513. // to A::foo, which will look well-formed when we instantiate.
  10514. // The right solution is to not collapse the shadow-decl chain.
  10515. if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
  10516. if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
  10517. DeclContext *OrigDC = Orig->getDeclContext();
  10518. // Handle enums and anonymous structs.
  10519. if (isa<EnumDecl>(OrigDC))
  10520. OrigDC = OrigDC->getParent();
  10521. CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
  10522. while (OrigRec->isAnonymousStructOrUnion())
  10523. OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
  10524. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
  10525. if (OrigDC == CurContext) {
  10526. Diag(Using->getLocation(),
  10527. diag::err_using_decl_nested_name_specifier_is_current_class)
  10528. << Using->getQualifierLoc().getSourceRange();
  10529. Diag(Orig->getLocation(), diag::note_using_decl_target);
  10530. Using->setInvalidDecl();
  10531. return true;
  10532. }
  10533. Diag(Using->getQualifierLoc().getBeginLoc(),
  10534. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  10535. << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
  10536. << Using->getQualifierLoc().getSourceRange();
  10537. Diag(Orig->getLocation(), diag::note_using_decl_target);
  10538. Using->setInvalidDecl();
  10539. return true;
  10540. }
  10541. }
  10542. if (Previous.empty()) return false;
  10543. NamedDecl *Target = Orig;
  10544. if (isa<UsingShadowDecl>(Target))
  10545. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  10546. // If the target happens to be one of the previous declarations, we
  10547. // don't have a conflict.
  10548. //
  10549. // FIXME: but we might be increasing its access, in which case we
  10550. // should redeclare it.
  10551. NamedDecl *NonTag = nullptr, *Tag = nullptr;
  10552. bool FoundEquivalentDecl = false;
  10553. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  10554. I != E; ++I) {
  10555. NamedDecl *D = (*I)->getUnderlyingDecl();
  10556. // We can have UsingDecls in our Previous results because we use the same
  10557. // LookupResult for checking whether the UsingDecl itself is a valid
  10558. // redeclaration.
  10559. if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
  10560. continue;
  10561. if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  10562. // C++ [class.mem]p19:
  10563. // If T is the name of a class, then [every named member other than
  10564. // a non-static data member] shall have a name different from T
  10565. if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
  10566. !isa<IndirectFieldDecl>(Target) &&
  10567. !isa<UnresolvedUsingValueDecl>(Target) &&
  10568. DiagnoseClassNameShadow(
  10569. CurContext,
  10570. DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
  10571. return true;
  10572. }
  10573. if (IsEquivalentForUsingDecl(Context, D, Target)) {
  10574. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
  10575. PrevShadow = Shadow;
  10576. FoundEquivalentDecl = true;
  10577. } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
  10578. // We don't conflict with an existing using shadow decl of an equivalent
  10579. // declaration, but we're not a redeclaration of it.
  10580. FoundEquivalentDecl = true;
  10581. }
  10582. if (isVisible(D))
  10583. (isa<TagDecl>(D) ? Tag : NonTag) = D;
  10584. }
  10585. if (FoundEquivalentDecl)
  10586. return false;
  10587. // Always emit a diagnostic for a mismatch between an unresolved
  10588. // using_if_exists and a resolved using declaration in either direction.
  10589. if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
  10590. (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
  10591. if (!NonTag && !Tag)
  10592. return false;
  10593. Diag(BUD->getLocation(), diag::err_using_decl_conflict);
  10594. Diag(Target->getLocation(), diag::note_using_decl_target);
  10595. Diag((NonTag ? NonTag : Tag)->getLocation(),
  10596. diag::note_using_decl_conflict);
  10597. BUD->setInvalidDecl();
  10598. return true;
  10599. }
  10600. if (FunctionDecl *FD = Target->getAsFunction()) {
  10601. NamedDecl *OldDecl = nullptr;
  10602. switch (CheckOverload(nullptr, FD, Previous, OldDecl,
  10603. /*IsForUsingDecl*/ true)) {
  10604. case Ovl_Overload:
  10605. return false;
  10606. case Ovl_NonFunction:
  10607. Diag(BUD->getLocation(), diag::err_using_decl_conflict);
  10608. break;
  10609. // We found a decl with the exact signature.
  10610. case Ovl_Match:
  10611. // If we're in a record, we want to hide the target, so we
  10612. // return true (without a diagnostic) to tell the caller not to
  10613. // build a shadow decl.
  10614. if (CurContext->isRecord())
  10615. return true;
  10616. // If we're not in a record, this is an error.
  10617. Diag(BUD->getLocation(), diag::err_using_decl_conflict);
  10618. break;
  10619. }
  10620. Diag(Target->getLocation(), diag::note_using_decl_target);
  10621. Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
  10622. BUD->setInvalidDecl();
  10623. return true;
  10624. }
  10625. // Target is not a function.
  10626. if (isa<TagDecl>(Target)) {
  10627. // No conflict between a tag and a non-tag.
  10628. if (!Tag) return false;
  10629. Diag(BUD->getLocation(), diag::err_using_decl_conflict);
  10630. Diag(Target->getLocation(), diag::note_using_decl_target);
  10631. Diag(Tag->getLocation(), diag::note_using_decl_conflict);
  10632. BUD->setInvalidDecl();
  10633. return true;
  10634. }
  10635. // No conflict between a tag and a non-tag.
  10636. if (!NonTag) return false;
  10637. Diag(BUD->getLocation(), diag::err_using_decl_conflict);
  10638. Diag(Target->getLocation(), diag::note_using_decl_target);
  10639. Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
  10640. BUD->setInvalidDecl();
  10641. return true;
  10642. }
  10643. /// Determine whether a direct base class is a virtual base class.
  10644. static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
  10645. if (!Derived->getNumVBases())
  10646. return false;
  10647. for (auto &B : Derived->bases())
  10648. if (B.getType()->getAsCXXRecordDecl() == Base)
  10649. return B.isVirtual();
  10650. llvm_unreachable("not a direct base class");
  10651. }
  10652. /// Builds a shadow declaration corresponding to a 'using' declaration.
  10653. UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
  10654. NamedDecl *Orig,
  10655. UsingShadowDecl *PrevDecl) {
  10656. // If we resolved to another shadow declaration, just coalesce them.
  10657. NamedDecl *Target = Orig;
  10658. if (isa<UsingShadowDecl>(Target)) {
  10659. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  10660. assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
  10661. }
  10662. NamedDecl *NonTemplateTarget = Target;
  10663. if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
  10664. NonTemplateTarget = TargetTD->getTemplatedDecl();
  10665. UsingShadowDecl *Shadow;
  10666. if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
  10667. UsingDecl *Using = cast<UsingDecl>(BUD);
  10668. bool IsVirtualBase =
  10669. isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
  10670. Using->getQualifier()->getAsRecordDecl());
  10671. Shadow = ConstructorUsingShadowDecl::Create(
  10672. Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
  10673. } else {
  10674. Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
  10675. Target->getDeclName(), BUD, Target);
  10676. }
  10677. BUD->addShadowDecl(Shadow);
  10678. Shadow->setAccess(BUD->getAccess());
  10679. if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
  10680. Shadow->setInvalidDecl();
  10681. Shadow->setPreviousDecl(PrevDecl);
  10682. if (S)
  10683. PushOnScopeChains(Shadow, S);
  10684. else
  10685. CurContext->addDecl(Shadow);
  10686. return Shadow;
  10687. }
  10688. /// Hides a using shadow declaration. This is required by the current
  10689. /// using-decl implementation when a resolvable using declaration in a
  10690. /// class is followed by a declaration which would hide or override
  10691. /// one or more of the using decl's targets; for example:
  10692. ///
  10693. /// struct Base { void foo(int); };
  10694. /// struct Derived : Base {
  10695. /// using Base::foo;
  10696. /// void foo(int);
  10697. /// };
  10698. ///
  10699. /// The governing language is C++03 [namespace.udecl]p12:
  10700. ///
  10701. /// When a using-declaration brings names from a base class into a
  10702. /// derived class scope, member functions in the derived class
  10703. /// override and/or hide member functions with the same name and
  10704. /// parameter types in a base class (rather than conflicting).
  10705. ///
  10706. /// There are two ways to implement this:
  10707. /// (1) optimistically create shadow decls when they're not hidden
  10708. /// by existing declarations, or
  10709. /// (2) don't create any shadow decls (or at least don't make them
  10710. /// visible) until we've fully parsed/instantiated the class.
  10711. /// The problem with (1) is that we might have to retroactively remove
  10712. /// a shadow decl, which requires several O(n) operations because the
  10713. /// decl structures are (very reasonably) not designed for removal.
  10714. /// (2) avoids this but is very fiddly and phase-dependent.
  10715. void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
  10716. if (Shadow->getDeclName().getNameKind() ==
  10717. DeclarationName::CXXConversionFunctionName)
  10718. cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
  10719. // Remove it from the DeclContext...
  10720. Shadow->getDeclContext()->removeDecl(Shadow);
  10721. // ...and the scope, if applicable...
  10722. if (S) {
  10723. S->RemoveDecl(Shadow);
  10724. IdResolver.RemoveDecl(Shadow);
  10725. }
  10726. // ...and the using decl.
  10727. Shadow->getIntroducer()->removeShadowDecl(Shadow);
  10728. // TODO: complain somehow if Shadow was used. It shouldn't
  10729. // be possible for this to happen, because...?
  10730. }
  10731. /// Find the base specifier for a base class with the given type.
  10732. static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
  10733. QualType DesiredBase,
  10734. bool &AnyDependentBases) {
  10735. // Check whether the named type is a direct base class.
  10736. CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
  10737. .getUnqualifiedType();
  10738. for (auto &Base : Derived->bases()) {
  10739. CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
  10740. if (CanonicalDesiredBase == BaseType)
  10741. return &Base;
  10742. if (BaseType->isDependentType())
  10743. AnyDependentBases = true;
  10744. }
  10745. return nullptr;
  10746. }
  10747. namespace {
  10748. class UsingValidatorCCC final : public CorrectionCandidateCallback {
  10749. public:
  10750. UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
  10751. NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
  10752. : HasTypenameKeyword(HasTypenameKeyword),
  10753. IsInstantiation(IsInstantiation), OldNNS(NNS),
  10754. RequireMemberOf(RequireMemberOf) {}
  10755. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  10756. NamedDecl *ND = Candidate.getCorrectionDecl();
  10757. // Keywords are not valid here.
  10758. if (!ND || isa<NamespaceDecl>(ND))
  10759. return false;
  10760. // Completely unqualified names are invalid for a 'using' declaration.
  10761. if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
  10762. return false;
  10763. // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
  10764. // reject.
  10765. if (RequireMemberOf) {
  10766. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  10767. if (FoundRecord && FoundRecord->isInjectedClassName()) {
  10768. // No-one ever wants a using-declaration to name an injected-class-name
  10769. // of a base class, unless they're declaring an inheriting constructor.
  10770. ASTContext &Ctx = ND->getASTContext();
  10771. if (!Ctx.getLangOpts().CPlusPlus11)
  10772. return false;
  10773. QualType FoundType = Ctx.getRecordType(FoundRecord);
  10774. // Check that the injected-class-name is named as a member of its own
  10775. // type; we don't want to suggest 'using Derived::Base;', since that
  10776. // means something else.
  10777. NestedNameSpecifier *Specifier =
  10778. Candidate.WillReplaceSpecifier()
  10779. ? Candidate.getCorrectionSpecifier()
  10780. : OldNNS;
  10781. if (!Specifier->getAsType() ||
  10782. !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
  10783. return false;
  10784. // Check that this inheriting constructor declaration actually names a
  10785. // direct base class of the current class.
  10786. bool AnyDependentBases = false;
  10787. if (!findDirectBaseWithType(RequireMemberOf,
  10788. Ctx.getRecordType(FoundRecord),
  10789. AnyDependentBases) &&
  10790. !AnyDependentBases)
  10791. return false;
  10792. } else {
  10793. auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
  10794. if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
  10795. return false;
  10796. // FIXME: Check that the base class member is accessible?
  10797. }
  10798. } else {
  10799. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  10800. if (FoundRecord && FoundRecord->isInjectedClassName())
  10801. return false;
  10802. }
  10803. if (isa<TypeDecl>(ND))
  10804. return HasTypenameKeyword || !IsInstantiation;
  10805. return !HasTypenameKeyword;
  10806. }
  10807. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  10808. return std::make_unique<UsingValidatorCCC>(*this);
  10809. }
  10810. private:
  10811. bool HasTypenameKeyword;
  10812. bool IsInstantiation;
  10813. NestedNameSpecifier *OldNNS;
  10814. CXXRecordDecl *RequireMemberOf;
  10815. };
  10816. } // end anonymous namespace
  10817. /// Remove decls we can't actually see from a lookup being used to declare
  10818. /// shadow using decls.
  10819. ///
  10820. /// \param S - The scope of the potential shadow decl
  10821. /// \param Previous - The lookup of a potential shadow decl's name.
  10822. void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
  10823. // It is really dumb that we have to do this.
  10824. LookupResult::Filter F = Previous.makeFilter();
  10825. while (F.hasNext()) {
  10826. NamedDecl *D = F.next();
  10827. if (!isDeclInScope(D, CurContext, S))
  10828. F.erase();
  10829. // If we found a local extern declaration that's not ordinarily visible,
  10830. // and this declaration is being added to a non-block scope, ignore it.
  10831. // We're only checking for scope conflicts here, not also for violations
  10832. // of the linkage rules.
  10833. else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
  10834. !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
  10835. F.erase();
  10836. }
  10837. F.done();
  10838. }
  10839. /// Builds a using declaration.
  10840. ///
  10841. /// \param IsInstantiation - Whether this call arises from an
  10842. /// instantiation of an unresolved using declaration. We treat
  10843. /// the lookup differently for these declarations.
  10844. NamedDecl *Sema::BuildUsingDeclaration(
  10845. Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
  10846. bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
  10847. DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
  10848. const ParsedAttributesView &AttrList, bool IsInstantiation,
  10849. bool IsUsingIfExists) {
  10850. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  10851. SourceLocation IdentLoc = NameInfo.getLoc();
  10852. assert(IdentLoc.isValid() && "Invalid TargetName location.");
  10853. // FIXME: We ignore attributes for now.
  10854. // For an inheriting constructor declaration, the name of the using
  10855. // declaration is the name of a constructor in this class, not in the
  10856. // base class.
  10857. DeclarationNameInfo UsingName = NameInfo;
  10858. if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
  10859. if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
  10860. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  10861. Context.getCanonicalType(Context.getRecordType(RD))));
  10862. // Do the redeclaration lookup in the current scope.
  10863. LookupResult Previous(*this, UsingName, LookupUsingDeclName,
  10864. ForVisibleRedeclaration);
  10865. Previous.setHideTags(false);
  10866. if (S) {
  10867. LookupName(Previous, S);
  10868. FilterUsingLookup(S, Previous);
  10869. } else {
  10870. assert(IsInstantiation && "no scope in non-instantiation");
  10871. if (CurContext->isRecord())
  10872. LookupQualifiedName(Previous, CurContext);
  10873. else {
  10874. // No redeclaration check is needed here; in non-member contexts we
  10875. // diagnosed all possible conflicts with other using-declarations when
  10876. // building the template:
  10877. //
  10878. // For a dependent non-type using declaration, the only valid case is
  10879. // if we instantiate to a single enumerator. We check for conflicts
  10880. // between shadow declarations we introduce, and we check in the template
  10881. // definition for conflicts between a non-type using declaration and any
  10882. // other declaration, which together covers all cases.
  10883. //
  10884. // A dependent typename using declaration will never successfully
  10885. // instantiate, since it will always name a class member, so we reject
  10886. // that in the template definition.
  10887. }
  10888. }
  10889. // Check for invalid redeclarations.
  10890. if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
  10891. SS, IdentLoc, Previous))
  10892. return nullptr;
  10893. // 'using_if_exists' doesn't make sense on an inherited constructor.
  10894. if (IsUsingIfExists && UsingName.getName().getNameKind() ==
  10895. DeclarationName::CXXConstructorName) {
  10896. Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
  10897. return nullptr;
  10898. }
  10899. DeclContext *LookupContext = computeDeclContext(SS);
  10900. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  10901. if (!LookupContext || EllipsisLoc.isValid()) {
  10902. NamedDecl *D;
  10903. // Dependent scope, or an unexpanded pack
  10904. if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
  10905. SS, NameInfo, IdentLoc))
  10906. return nullptr;
  10907. if (HasTypenameKeyword) {
  10908. // FIXME: not all declaration name kinds are legal here
  10909. D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
  10910. UsingLoc, TypenameLoc,
  10911. QualifierLoc,
  10912. IdentLoc, NameInfo.getName(),
  10913. EllipsisLoc);
  10914. } else {
  10915. D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
  10916. QualifierLoc, NameInfo, EllipsisLoc);
  10917. }
  10918. D->setAccess(AS);
  10919. CurContext->addDecl(D);
  10920. ProcessDeclAttributeList(S, D, AttrList);
  10921. return D;
  10922. }
  10923. auto Build = [&](bool Invalid) {
  10924. UsingDecl *UD =
  10925. UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
  10926. UsingName, HasTypenameKeyword);
  10927. UD->setAccess(AS);
  10928. CurContext->addDecl(UD);
  10929. ProcessDeclAttributeList(S, UD, AttrList);
  10930. UD->setInvalidDecl(Invalid);
  10931. return UD;
  10932. };
  10933. auto BuildInvalid = [&]{ return Build(true); };
  10934. auto BuildValid = [&]{ return Build(false); };
  10935. if (RequireCompleteDeclContext(SS, LookupContext))
  10936. return BuildInvalid();
  10937. // Look up the target name.
  10938. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  10939. // Unlike most lookups, we don't always want to hide tag
  10940. // declarations: tag names are visible through the using declaration
  10941. // even if hidden by ordinary names, *except* in a dependent context
  10942. // where they may be used by two-phase lookup.
  10943. if (!IsInstantiation)
  10944. R.setHideTags(false);
  10945. // For the purposes of this lookup, we have a base object type
  10946. // equal to that of the current context.
  10947. if (CurContext->isRecord()) {
  10948. R.setBaseObjectType(
  10949. Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
  10950. }
  10951. LookupQualifiedName(R, LookupContext);
  10952. // Validate the context, now we have a lookup
  10953. if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
  10954. IdentLoc, &R))
  10955. return nullptr;
  10956. if (R.empty() && IsUsingIfExists)
  10957. R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
  10958. UsingName.getName()),
  10959. AS_public);
  10960. // Try to correct typos if possible. If constructor name lookup finds no
  10961. // results, that means the named class has no explicit constructors, and we
  10962. // suppressed declaring implicit ones (probably because it's dependent or
  10963. // invalid).
  10964. if (R.empty() &&
  10965. NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
  10966. // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
  10967. // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
  10968. // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
  10969. auto *II = NameInfo.getName().getAsIdentifierInfo();
  10970. if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
  10971. CurContext->isStdNamespace() &&
  10972. isa<TranslationUnitDecl>(LookupContext) &&
  10973. getSourceManager().isInSystemHeader(UsingLoc))
  10974. return nullptr;
  10975. UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
  10976. dyn_cast<CXXRecordDecl>(CurContext));
  10977. if (TypoCorrection Corrected =
  10978. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
  10979. CTK_ErrorRecovery)) {
  10980. // We reject candidates where DroppedSpecifier == true, hence the
  10981. // literal '0' below.
  10982. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  10983. << NameInfo.getName() << LookupContext << 0
  10984. << SS.getRange());
  10985. // If we picked a correction with no attached Decl we can't do anything
  10986. // useful with it, bail out.
  10987. NamedDecl *ND = Corrected.getCorrectionDecl();
  10988. if (!ND)
  10989. return BuildInvalid();
  10990. // If we corrected to an inheriting constructor, handle it as one.
  10991. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  10992. if (RD && RD->isInjectedClassName()) {
  10993. // The parent of the injected class name is the class itself.
  10994. RD = cast<CXXRecordDecl>(RD->getParent());
  10995. // Fix up the information we'll use to build the using declaration.
  10996. if (Corrected.WillReplaceSpecifier()) {
  10997. NestedNameSpecifierLocBuilder Builder;
  10998. Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  10999. QualifierLoc.getSourceRange());
  11000. QualifierLoc = Builder.getWithLocInContext(Context);
  11001. }
  11002. // In this case, the name we introduce is the name of a derived class
  11003. // constructor.
  11004. auto *CurClass = cast<CXXRecordDecl>(CurContext);
  11005. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  11006. Context.getCanonicalType(Context.getRecordType(CurClass))));
  11007. UsingName.setNamedTypeInfo(nullptr);
  11008. for (auto *Ctor : LookupConstructors(RD))
  11009. R.addDecl(Ctor);
  11010. R.resolveKind();
  11011. } else {
  11012. // FIXME: Pick up all the declarations if we found an overloaded
  11013. // function.
  11014. UsingName.setName(ND->getDeclName());
  11015. R.addDecl(ND);
  11016. }
  11017. } else {
  11018. Diag(IdentLoc, diag::err_no_member)
  11019. << NameInfo.getName() << LookupContext << SS.getRange();
  11020. return BuildInvalid();
  11021. }
  11022. }
  11023. if (R.isAmbiguous())
  11024. return BuildInvalid();
  11025. if (HasTypenameKeyword) {
  11026. // If we asked for a typename and got a non-type decl, error out.
  11027. if (!R.getAsSingle<TypeDecl>() &&
  11028. !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
  11029. Diag(IdentLoc, diag::err_using_typename_non_type);
  11030. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  11031. Diag((*I)->getUnderlyingDecl()->getLocation(),
  11032. diag::note_using_decl_target);
  11033. return BuildInvalid();
  11034. }
  11035. } else {
  11036. // If we asked for a non-typename and we got a type, error out,
  11037. // but only if this is an instantiation of an unresolved using
  11038. // decl. Otherwise just silently find the type name.
  11039. if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
  11040. Diag(IdentLoc, diag::err_using_dependent_value_is_type);
  11041. Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
  11042. return BuildInvalid();
  11043. }
  11044. }
  11045. // C++14 [namespace.udecl]p6:
  11046. // A using-declaration shall not name a namespace.
  11047. if (R.getAsSingle<NamespaceDecl>()) {
  11048. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
  11049. << SS.getRange();
  11050. return BuildInvalid();
  11051. }
  11052. UsingDecl *UD = BuildValid();
  11053. // Some additional rules apply to inheriting constructors.
  11054. if (UsingName.getName().getNameKind() ==
  11055. DeclarationName::CXXConstructorName) {
  11056. // Suppress access diagnostics; the access check is instead performed at the
  11057. // point of use for an inheriting constructor.
  11058. R.suppressDiagnostics();
  11059. if (CheckInheritingConstructorUsingDecl(UD))
  11060. return UD;
  11061. }
  11062. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  11063. UsingShadowDecl *PrevDecl = nullptr;
  11064. if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
  11065. BuildUsingShadowDecl(S, UD, *I, PrevDecl);
  11066. }
  11067. return UD;
  11068. }
  11069. NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
  11070. SourceLocation UsingLoc,
  11071. SourceLocation EnumLoc,
  11072. SourceLocation NameLoc,
  11073. TypeSourceInfo *EnumType,
  11074. EnumDecl *ED) {
  11075. bool Invalid = false;
  11076. if (CurContext->getRedeclContext()->isRecord()) {
  11077. /// In class scope, check if this is a duplicate, for better a diagnostic.
  11078. DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
  11079. LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
  11080. ForVisibleRedeclaration);
  11081. LookupName(Previous, S);
  11082. for (NamedDecl *D : Previous)
  11083. if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
  11084. if (UED->getEnumDecl() == ED) {
  11085. Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
  11086. << SourceRange(EnumLoc, NameLoc);
  11087. Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
  11088. Invalid = true;
  11089. break;
  11090. }
  11091. }
  11092. if (RequireCompleteEnumDecl(ED, NameLoc))
  11093. Invalid = true;
  11094. UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
  11095. EnumLoc, NameLoc, EnumType);
  11096. UD->setAccess(AS);
  11097. CurContext->addDecl(UD);
  11098. if (Invalid) {
  11099. UD->setInvalidDecl();
  11100. return UD;
  11101. }
  11102. // Create the shadow decls for each enumerator
  11103. for (EnumConstantDecl *EC : ED->enumerators()) {
  11104. UsingShadowDecl *PrevDecl = nullptr;
  11105. DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
  11106. LookupResult Previous(*this, DNI, LookupOrdinaryName,
  11107. ForVisibleRedeclaration);
  11108. LookupName(Previous, S);
  11109. FilterUsingLookup(S, Previous);
  11110. if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
  11111. BuildUsingShadowDecl(S, UD, EC, PrevDecl);
  11112. }
  11113. return UD;
  11114. }
  11115. NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
  11116. ArrayRef<NamedDecl *> Expansions) {
  11117. assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
  11118. isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
  11119. isa<UsingPackDecl>(InstantiatedFrom));
  11120. auto *UPD =
  11121. UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
  11122. UPD->setAccess(InstantiatedFrom->getAccess());
  11123. CurContext->addDecl(UPD);
  11124. return UPD;
  11125. }
  11126. /// Additional checks for a using declaration referring to a constructor name.
  11127. bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
  11128. assert(!UD->hasTypename() && "expecting a constructor name");
  11129. const Type *SourceType = UD->getQualifier()->getAsType();
  11130. assert(SourceType &&
  11131. "Using decl naming constructor doesn't have type in scope spec.");
  11132. CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
  11133. // Check whether the named type is a direct base class.
  11134. bool AnyDependentBases = false;
  11135. auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
  11136. AnyDependentBases);
  11137. if (!Base && !AnyDependentBases) {
  11138. Diag(UD->getUsingLoc(),
  11139. diag::err_using_decl_constructor_not_in_direct_base)
  11140. << UD->getNameInfo().getSourceRange()
  11141. << QualType(SourceType, 0) << TargetClass;
  11142. UD->setInvalidDecl();
  11143. return true;
  11144. }
  11145. if (Base)
  11146. Base->setInheritConstructors();
  11147. return false;
  11148. }
  11149. /// Checks that the given using declaration is not an invalid
  11150. /// redeclaration. Note that this is checking only for the using decl
  11151. /// itself, not for any ill-formedness among the UsingShadowDecls.
  11152. bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
  11153. bool HasTypenameKeyword,
  11154. const CXXScopeSpec &SS,
  11155. SourceLocation NameLoc,
  11156. const LookupResult &Prev) {
  11157. NestedNameSpecifier *Qual = SS.getScopeRep();
  11158. // C++03 [namespace.udecl]p8:
  11159. // C++0x [namespace.udecl]p10:
  11160. // A using-declaration is a declaration and can therefore be used
  11161. // repeatedly where (and only where) multiple declarations are
  11162. // allowed.
  11163. //
  11164. // That's in non-member contexts.
  11165. if (!CurContext->getRedeclContext()->isRecord()) {
  11166. // A dependent qualifier outside a class can only ever resolve to an
  11167. // enumeration type. Therefore it conflicts with any other non-type
  11168. // declaration in the same scope.
  11169. // FIXME: How should we check for dependent type-type conflicts at block
  11170. // scope?
  11171. if (Qual->isDependent() && !HasTypenameKeyword) {
  11172. for (auto *D : Prev) {
  11173. if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
  11174. bool OldCouldBeEnumerator =
  11175. isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
  11176. Diag(NameLoc,
  11177. OldCouldBeEnumerator ? diag::err_redefinition
  11178. : diag::err_redefinition_different_kind)
  11179. << Prev.getLookupName();
  11180. Diag(D->getLocation(), diag::note_previous_definition);
  11181. return true;
  11182. }
  11183. }
  11184. }
  11185. return false;
  11186. }
  11187. const NestedNameSpecifier *CNNS =
  11188. Context.getCanonicalNestedNameSpecifier(Qual);
  11189. for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
  11190. NamedDecl *D = *I;
  11191. bool DTypename;
  11192. NestedNameSpecifier *DQual;
  11193. if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
  11194. DTypename = UD->hasTypename();
  11195. DQual = UD->getQualifier();
  11196. } else if (UnresolvedUsingValueDecl *UD
  11197. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  11198. DTypename = false;
  11199. DQual = UD->getQualifier();
  11200. } else if (UnresolvedUsingTypenameDecl *UD
  11201. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  11202. DTypename = true;
  11203. DQual = UD->getQualifier();
  11204. } else continue;
  11205. // using decls differ if one says 'typename' and the other doesn't.
  11206. // FIXME: non-dependent using decls?
  11207. if (HasTypenameKeyword != DTypename) continue;
  11208. // using decls differ if they name different scopes (but note that
  11209. // template instantiation can cause this check to trigger when it
  11210. // didn't before instantiation).
  11211. if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
  11212. continue;
  11213. Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
  11214. Diag(D->getLocation(), diag::note_using_decl) << 1;
  11215. return true;
  11216. }
  11217. return false;
  11218. }
  11219. /// Checks that the given nested-name qualifier used in a using decl
  11220. /// in the current context is appropriately related to the current
  11221. /// scope. If an error is found, diagnoses it and returns true.
  11222. /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
  11223. /// result of that lookup. UD is likewise nullptr, except when we have an
  11224. /// already-populated UsingDecl whose shadow decls contain the same information
  11225. /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
  11226. bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
  11227. const CXXScopeSpec &SS,
  11228. const DeclarationNameInfo &NameInfo,
  11229. SourceLocation NameLoc,
  11230. const LookupResult *R, const UsingDecl *UD) {
  11231. DeclContext *NamedContext = computeDeclContext(SS);
  11232. assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
  11233. "resolvable context must have exactly one set of decls");
  11234. // C++ 20 permits using an enumerator that does not have a class-hierarchy
  11235. // relationship.
  11236. bool Cxx20Enumerator = false;
  11237. if (NamedContext) {
  11238. EnumConstantDecl *EC = nullptr;
  11239. if (R)
  11240. EC = R->getAsSingle<EnumConstantDecl>();
  11241. else if (UD && UD->shadow_size() == 1)
  11242. EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
  11243. if (EC)
  11244. Cxx20Enumerator = getLangOpts().CPlusPlus20;
  11245. if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
  11246. // C++14 [namespace.udecl]p7:
  11247. // A using-declaration shall not name a scoped enumerator.
  11248. // C++20 p1099 permits enumerators.
  11249. if (EC && R && ED->isScoped())
  11250. Diag(SS.getBeginLoc(),
  11251. getLangOpts().CPlusPlus20
  11252. ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
  11253. : diag::ext_using_decl_scoped_enumerator)
  11254. << SS.getRange();
  11255. // We want to consider the scope of the enumerator
  11256. NamedContext = ED->getDeclContext();
  11257. }
  11258. }
  11259. if (!CurContext->isRecord()) {
  11260. // C++03 [namespace.udecl]p3:
  11261. // C++0x [namespace.udecl]p8:
  11262. // A using-declaration for a class member shall be a member-declaration.
  11263. // C++20 [namespace.udecl]p7
  11264. // ... other than an enumerator ...
  11265. // If we weren't able to compute a valid scope, it might validly be a
  11266. // dependent class or enumeration scope. If we have a 'typename' keyword,
  11267. // the scope must resolve to a class type.
  11268. if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
  11269. : !HasTypename)
  11270. return false; // OK
  11271. Diag(NameLoc,
  11272. Cxx20Enumerator
  11273. ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
  11274. : diag::err_using_decl_can_not_refer_to_class_member)
  11275. << SS.getRange();
  11276. if (Cxx20Enumerator)
  11277. return false; // OK
  11278. auto *RD = NamedContext
  11279. ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
  11280. : nullptr;
  11281. if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
  11282. // See if there's a helpful fixit
  11283. if (!R) {
  11284. // We will have already diagnosed the problem on the template
  11285. // definition, Maybe we should do so again?
  11286. } else if (R->getAsSingle<TypeDecl>()) {
  11287. if (getLangOpts().CPlusPlus11) {
  11288. // Convert 'using X::Y;' to 'using Y = X::Y;'.
  11289. Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
  11290. << 0 // alias declaration
  11291. << FixItHint::CreateInsertion(SS.getBeginLoc(),
  11292. NameInfo.getName().getAsString() +
  11293. " = ");
  11294. } else {
  11295. // Convert 'using X::Y;' to 'typedef X::Y Y;'.
  11296. SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
  11297. Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
  11298. << 1 // typedef declaration
  11299. << FixItHint::CreateReplacement(UsingLoc, "typedef")
  11300. << FixItHint::CreateInsertion(
  11301. InsertLoc, " " + NameInfo.getName().getAsString());
  11302. }
  11303. } else if (R->getAsSingle<VarDecl>()) {
  11304. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  11305. // repeating the type of the static data member here.
  11306. FixItHint FixIt;
  11307. if (getLangOpts().CPlusPlus11) {
  11308. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  11309. FixIt = FixItHint::CreateReplacement(
  11310. UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
  11311. }
  11312. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  11313. << 2 // reference declaration
  11314. << FixIt;
  11315. } else if (R->getAsSingle<EnumConstantDecl>()) {
  11316. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  11317. // repeating the type of the enumeration here, and we can't do so if
  11318. // the type is anonymous.
  11319. FixItHint FixIt;
  11320. if (getLangOpts().CPlusPlus11) {
  11321. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  11322. FixIt = FixItHint::CreateReplacement(
  11323. UsingLoc,
  11324. "constexpr auto " + NameInfo.getName().getAsString() + " = ");
  11325. }
  11326. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  11327. << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
  11328. << FixIt;
  11329. }
  11330. }
  11331. return true; // Fail
  11332. }
  11333. // If the named context is dependent, we can't decide much.
  11334. if (!NamedContext) {
  11335. // FIXME: in C++0x, we can diagnose if we can prove that the
  11336. // nested-name-specifier does not refer to a base class, which is
  11337. // still possible in some cases.
  11338. // Otherwise we have to conservatively report that things might be
  11339. // okay.
  11340. return false;
  11341. }
  11342. // The current scope is a record.
  11343. if (!NamedContext->isRecord()) {
  11344. // Ideally this would point at the last name in the specifier,
  11345. // but we don't have that level of source info.
  11346. Diag(SS.getBeginLoc(),
  11347. Cxx20Enumerator
  11348. ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
  11349. : diag::err_using_decl_nested_name_specifier_is_not_class)
  11350. << SS.getScopeRep() << SS.getRange();
  11351. if (Cxx20Enumerator)
  11352. return false; // OK
  11353. return true;
  11354. }
  11355. if (!NamedContext->isDependentContext() &&
  11356. RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
  11357. return true;
  11358. if (getLangOpts().CPlusPlus11) {
  11359. // C++11 [namespace.udecl]p3:
  11360. // In a using-declaration used as a member-declaration, the
  11361. // nested-name-specifier shall name a base class of the class
  11362. // being defined.
  11363. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
  11364. cast<CXXRecordDecl>(NamedContext))) {
  11365. if (Cxx20Enumerator) {
  11366. Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
  11367. << SS.getRange();
  11368. return false;
  11369. }
  11370. if (CurContext == NamedContext) {
  11371. Diag(SS.getBeginLoc(),
  11372. diag::err_using_decl_nested_name_specifier_is_current_class)
  11373. << SS.getRange();
  11374. return !getLangOpts().CPlusPlus20;
  11375. }
  11376. if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
  11377. Diag(SS.getBeginLoc(),
  11378. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  11379. << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
  11380. << SS.getRange();
  11381. }
  11382. return true;
  11383. }
  11384. return false;
  11385. }
  11386. // C++03 [namespace.udecl]p4:
  11387. // A using-declaration used as a member-declaration shall refer
  11388. // to a member of a base class of the class being defined [etc.].
  11389. // Salient point: SS doesn't have to name a base class as long as
  11390. // lookup only finds members from base classes. Therefore we can
  11391. // diagnose here only if we can prove that can't happen,
  11392. // i.e. if the class hierarchies provably don't intersect.
  11393. // TODO: it would be nice if "definitely valid" results were cached
  11394. // in the UsingDecl and UsingShadowDecl so that these checks didn't
  11395. // need to be repeated.
  11396. llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
  11397. auto Collect = [&Bases](const CXXRecordDecl *Base) {
  11398. Bases.insert(Base);
  11399. return true;
  11400. };
  11401. // Collect all bases. Return false if we find a dependent base.
  11402. if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
  11403. return false;
  11404. // Returns true if the base is dependent or is one of the accumulated base
  11405. // classes.
  11406. auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
  11407. return !Bases.count(Base);
  11408. };
  11409. // Return false if the class has a dependent base or if it or one
  11410. // of its bases is present in the base set of the current context.
  11411. if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
  11412. !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
  11413. return false;
  11414. Diag(SS.getRange().getBegin(),
  11415. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  11416. << SS.getScopeRep()
  11417. << cast<CXXRecordDecl>(CurContext)
  11418. << SS.getRange();
  11419. return true;
  11420. }
  11421. Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
  11422. MultiTemplateParamsArg TemplateParamLists,
  11423. SourceLocation UsingLoc, UnqualifiedId &Name,
  11424. const ParsedAttributesView &AttrList,
  11425. TypeResult Type, Decl *DeclFromDeclSpec) {
  11426. // Skip up to the relevant declaration scope.
  11427. while (S->isTemplateParamScope())
  11428. S = S->getParent();
  11429. assert((S->getFlags() & Scope::DeclScope) &&
  11430. "got alias-declaration outside of declaration scope");
  11431. if (Type.isInvalid())
  11432. return nullptr;
  11433. bool Invalid = false;
  11434. DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
  11435. TypeSourceInfo *TInfo = nullptr;
  11436. GetTypeFromParser(Type.get(), &TInfo);
  11437. if (DiagnoseClassNameShadow(CurContext, NameInfo))
  11438. return nullptr;
  11439. if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
  11440. UPPC_DeclarationType)) {
  11441. Invalid = true;
  11442. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  11443. TInfo->getTypeLoc().getBeginLoc());
  11444. }
  11445. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  11446. TemplateParamLists.size()
  11447. ? forRedeclarationInCurContext()
  11448. : ForVisibleRedeclaration);
  11449. LookupName(Previous, S);
  11450. // Warn about shadowing the name of a template parameter.
  11451. if (Previous.isSingleResult() &&
  11452. Previous.getFoundDecl()->isTemplateParameter()) {
  11453. DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
  11454. Previous.clear();
  11455. }
  11456. assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
  11457. "name in alias declaration must be an identifier");
  11458. TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
  11459. Name.StartLocation,
  11460. Name.Identifier, TInfo);
  11461. NewTD->setAccess(AS);
  11462. if (Invalid)
  11463. NewTD->setInvalidDecl();
  11464. ProcessDeclAttributeList(S, NewTD, AttrList);
  11465. AddPragmaAttributes(S, NewTD);
  11466. CheckTypedefForVariablyModifiedType(S, NewTD);
  11467. Invalid |= NewTD->isInvalidDecl();
  11468. bool Redeclaration = false;
  11469. NamedDecl *NewND;
  11470. if (TemplateParamLists.size()) {
  11471. TypeAliasTemplateDecl *OldDecl = nullptr;
  11472. TemplateParameterList *OldTemplateParams = nullptr;
  11473. if (TemplateParamLists.size() != 1) {
  11474. Diag(UsingLoc, diag::err_alias_template_extra_headers)
  11475. << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
  11476. TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
  11477. }
  11478. TemplateParameterList *TemplateParams = TemplateParamLists[0];
  11479. // Check that we can declare a template here.
  11480. if (CheckTemplateDeclScope(S, TemplateParams))
  11481. return nullptr;
  11482. // Only consider previous declarations in the same scope.
  11483. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
  11484. /*ExplicitInstantiationOrSpecialization*/false);
  11485. if (!Previous.empty()) {
  11486. Redeclaration = true;
  11487. OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
  11488. if (!OldDecl && !Invalid) {
  11489. Diag(UsingLoc, diag::err_redefinition_different_kind)
  11490. << Name.Identifier;
  11491. NamedDecl *OldD = Previous.getRepresentativeDecl();
  11492. if (OldD->getLocation().isValid())
  11493. Diag(OldD->getLocation(), diag::note_previous_definition);
  11494. Invalid = true;
  11495. }
  11496. if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
  11497. if (TemplateParameterListsAreEqual(TemplateParams,
  11498. OldDecl->getTemplateParameters(),
  11499. /*Complain=*/true,
  11500. TPL_TemplateMatch))
  11501. OldTemplateParams =
  11502. OldDecl->getMostRecentDecl()->getTemplateParameters();
  11503. else
  11504. Invalid = true;
  11505. TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
  11506. if (!Invalid &&
  11507. !Context.hasSameType(OldTD->getUnderlyingType(),
  11508. NewTD->getUnderlyingType())) {
  11509. // FIXME: The C++0x standard does not clearly say this is ill-formed,
  11510. // but we can't reasonably accept it.
  11511. Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
  11512. << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
  11513. if (OldTD->getLocation().isValid())
  11514. Diag(OldTD->getLocation(), diag::note_previous_definition);
  11515. Invalid = true;
  11516. }
  11517. }
  11518. }
  11519. // Merge any previous default template arguments into our parameters,
  11520. // and check the parameter list.
  11521. if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
  11522. TPC_TypeAliasTemplate))
  11523. return nullptr;
  11524. TypeAliasTemplateDecl *NewDecl =
  11525. TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
  11526. Name.Identifier, TemplateParams,
  11527. NewTD);
  11528. NewTD->setDescribedAliasTemplate(NewDecl);
  11529. NewDecl->setAccess(AS);
  11530. if (Invalid)
  11531. NewDecl->setInvalidDecl();
  11532. else if (OldDecl) {
  11533. NewDecl->setPreviousDecl(OldDecl);
  11534. CheckRedeclarationInModule(NewDecl, OldDecl);
  11535. }
  11536. NewND = NewDecl;
  11537. } else {
  11538. if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
  11539. setTagNameForLinkagePurposes(TD, NewTD);
  11540. handleTagNumbering(TD, S);
  11541. }
  11542. ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
  11543. NewND = NewTD;
  11544. }
  11545. PushOnScopeChains(NewND, S);
  11546. ActOnDocumentableDecl(NewND);
  11547. return NewND;
  11548. }
  11549. Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
  11550. SourceLocation AliasLoc,
  11551. IdentifierInfo *Alias, CXXScopeSpec &SS,
  11552. SourceLocation IdentLoc,
  11553. IdentifierInfo *Ident) {
  11554. // Lookup the namespace name.
  11555. LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
  11556. LookupParsedName(R, S, &SS);
  11557. if (R.isAmbiguous())
  11558. return nullptr;
  11559. if (R.empty()) {
  11560. if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
  11561. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  11562. return nullptr;
  11563. }
  11564. }
  11565. assert(!R.isAmbiguous() && !R.empty());
  11566. NamedDecl *ND = R.getRepresentativeDecl();
  11567. // Check if we have a previous declaration with the same name.
  11568. LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
  11569. ForVisibleRedeclaration);
  11570. LookupName(PrevR, S);
  11571. // Check we're not shadowing a template parameter.
  11572. if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
  11573. DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
  11574. PrevR.clear();
  11575. }
  11576. // Filter out any other lookup result from an enclosing scope.
  11577. FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
  11578. /*AllowInlineNamespace*/false);
  11579. // Find the previous declaration and check that we can redeclare it.
  11580. NamespaceAliasDecl *Prev = nullptr;
  11581. if (PrevR.isSingleResult()) {
  11582. NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
  11583. if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
  11584. // We already have an alias with the same name that points to the same
  11585. // namespace; check that it matches.
  11586. if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
  11587. Prev = AD;
  11588. } else if (isVisible(PrevDecl)) {
  11589. Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
  11590. << Alias;
  11591. Diag(AD->getLocation(), diag::note_previous_namespace_alias)
  11592. << AD->getNamespace();
  11593. return nullptr;
  11594. }
  11595. } else if (isVisible(PrevDecl)) {
  11596. unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
  11597. ? diag::err_redefinition
  11598. : diag::err_redefinition_different_kind;
  11599. Diag(AliasLoc, DiagID) << Alias;
  11600. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  11601. return nullptr;
  11602. }
  11603. }
  11604. // The use of a nested name specifier may trigger deprecation warnings.
  11605. DiagnoseUseOfDecl(ND, IdentLoc);
  11606. NamespaceAliasDecl *AliasDecl =
  11607. NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
  11608. Alias, SS.getWithLocInContext(Context),
  11609. IdentLoc, ND);
  11610. if (Prev)
  11611. AliasDecl->setPreviousDecl(Prev);
  11612. PushOnScopeChains(AliasDecl, S);
  11613. return AliasDecl;
  11614. }
  11615. namespace {
  11616. struct SpecialMemberExceptionSpecInfo
  11617. : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
  11618. SourceLocation Loc;
  11619. Sema::ImplicitExceptionSpecification ExceptSpec;
  11620. SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
  11621. Sema::CXXSpecialMember CSM,
  11622. Sema::InheritedConstructorInfo *ICI,
  11623. SourceLocation Loc)
  11624. : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
  11625. bool visitBase(CXXBaseSpecifier *Base);
  11626. bool visitField(FieldDecl *FD);
  11627. void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  11628. unsigned Quals);
  11629. void visitSubobjectCall(Subobject Subobj,
  11630. Sema::SpecialMemberOverloadResult SMOR);
  11631. };
  11632. }
  11633. bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
  11634. auto *RT = Base->getType()->getAs<RecordType>();
  11635. if (!RT)
  11636. return false;
  11637. auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
  11638. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  11639. if (auto *BaseCtor = SMOR.getMethod()) {
  11640. visitSubobjectCall(Base, BaseCtor);
  11641. return false;
  11642. }
  11643. visitClassSubobject(BaseClass, Base, 0);
  11644. return false;
  11645. }
  11646. bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
  11647. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
  11648. Expr *E = FD->getInClassInitializer();
  11649. if (!E)
  11650. // FIXME: It's a little wasteful to build and throw away a
  11651. // CXXDefaultInitExpr here.
  11652. // FIXME: We should have a single context note pointing at Loc, and
  11653. // this location should be MD->getLocation() instead, since that's
  11654. // the location where we actually use the default init expression.
  11655. E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
  11656. if (E)
  11657. ExceptSpec.CalledExpr(E);
  11658. } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
  11659. ->getAs<RecordType>()) {
  11660. visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
  11661. FD->getType().getCVRQualifiers());
  11662. }
  11663. return false;
  11664. }
  11665. void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
  11666. Subobject Subobj,
  11667. unsigned Quals) {
  11668. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  11669. bool IsMutable = Field && Field->isMutable();
  11670. visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
  11671. }
  11672. void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
  11673. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
  11674. // Note, if lookup fails, it doesn't matter what exception specification we
  11675. // choose because the special member will be deleted.
  11676. if (CXXMethodDecl *MD = SMOR.getMethod())
  11677. ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
  11678. }
  11679. bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
  11680. llvm::APSInt Result;
  11681. ExprResult Converted = CheckConvertedConstantExpression(
  11682. ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
  11683. ExplicitSpec.setExpr(Converted.get());
  11684. if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
  11685. ExplicitSpec.setKind(Result.getBoolValue()
  11686. ? ExplicitSpecKind::ResolvedTrue
  11687. : ExplicitSpecKind::ResolvedFalse);
  11688. return true;
  11689. }
  11690. ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
  11691. return false;
  11692. }
  11693. ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
  11694. ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
  11695. if (!ExplicitExpr->isTypeDependent())
  11696. tryResolveExplicitSpecifier(ES);
  11697. return ES;
  11698. }
  11699. static Sema::ImplicitExceptionSpecification
  11700. ComputeDefaultedSpecialMemberExceptionSpec(
  11701. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  11702. Sema::InheritedConstructorInfo *ICI) {
  11703. ComputingExceptionSpec CES(S, MD, Loc);
  11704. CXXRecordDecl *ClassDecl = MD->getParent();
  11705. // C++ [except.spec]p14:
  11706. // An implicitly declared special member function (Clause 12) shall have an
  11707. // exception-specification. [...]
  11708. SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
  11709. if (ClassDecl->isInvalidDecl())
  11710. return Info.ExceptSpec;
  11711. // FIXME: If this diagnostic fires, we're probably missing a check for
  11712. // attempting to resolve an exception specification before it's known
  11713. // at a higher level.
  11714. if (S.RequireCompleteType(MD->getLocation(),
  11715. S.Context.getRecordType(ClassDecl),
  11716. diag::err_exception_spec_incomplete_type))
  11717. return Info.ExceptSpec;
  11718. // C++1z [except.spec]p7:
  11719. // [Look for exceptions thrown by] a constructor selected [...] to
  11720. // initialize a potentially constructed subobject,
  11721. // C++1z [except.spec]p8:
  11722. // The exception specification for an implicitly-declared destructor, or a
  11723. // destructor without a noexcept-specifier, is potentially-throwing if and
  11724. // only if any of the destructors for any of its potentially constructed
  11725. // subojects is potentially throwing.
  11726. // FIXME: We respect the first rule but ignore the "potentially constructed"
  11727. // in the second rule to resolve a core issue (no number yet) that would have
  11728. // us reject:
  11729. // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
  11730. // struct B : A {};
  11731. // struct C : B { void f(); };
  11732. // ... due to giving B::~B() a non-throwing exception specification.
  11733. Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
  11734. : Info.VisitAllBases);
  11735. return Info.ExceptSpec;
  11736. }
  11737. namespace {
  11738. /// RAII object to register a special member as being currently declared.
  11739. struct DeclaringSpecialMember {
  11740. Sema &S;
  11741. Sema::SpecialMemberDecl D;
  11742. Sema::ContextRAII SavedContext;
  11743. bool WasAlreadyBeingDeclared;
  11744. DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
  11745. : S(S), D(RD, CSM), SavedContext(S, RD) {
  11746. WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
  11747. if (WasAlreadyBeingDeclared)
  11748. // This almost never happens, but if it does, ensure that our cache
  11749. // doesn't contain a stale result.
  11750. S.SpecialMemberCache.clear();
  11751. else {
  11752. // Register a note to be produced if we encounter an error while
  11753. // declaring the special member.
  11754. Sema::CodeSynthesisContext Ctx;
  11755. Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
  11756. // FIXME: We don't have a location to use here. Using the class's
  11757. // location maintains the fiction that we declare all special members
  11758. // with the class, but (1) it's not clear that lying about that helps our
  11759. // users understand what's going on, and (2) there may be outer contexts
  11760. // on the stack (some of which are relevant) and printing them exposes
  11761. // our lies.
  11762. Ctx.PointOfInstantiation = RD->getLocation();
  11763. Ctx.Entity = RD;
  11764. Ctx.SpecialMember = CSM;
  11765. S.pushCodeSynthesisContext(Ctx);
  11766. }
  11767. }
  11768. ~DeclaringSpecialMember() {
  11769. if (!WasAlreadyBeingDeclared) {
  11770. S.SpecialMembersBeingDeclared.erase(D);
  11771. S.popCodeSynthesisContext();
  11772. }
  11773. }
  11774. /// Are we already trying to declare this special member?
  11775. bool isAlreadyBeingDeclared() const {
  11776. return WasAlreadyBeingDeclared;
  11777. }
  11778. };
  11779. }
  11780. void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
  11781. // Look up any existing declarations, but don't trigger declaration of all
  11782. // implicit special members with this name.
  11783. DeclarationName Name = FD->getDeclName();
  11784. LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
  11785. ForExternalRedeclaration);
  11786. for (auto *D : FD->getParent()->lookup(Name))
  11787. if (auto *Acceptable = R.getAcceptableDecl(D))
  11788. R.addDecl(Acceptable);
  11789. R.resolveKind();
  11790. R.suppressDiagnostics();
  11791. CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
  11792. FD->isThisDeclarationADefinition());
  11793. }
  11794. void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
  11795. QualType ResultTy,
  11796. ArrayRef<QualType> Args) {
  11797. // Build an exception specification pointing back at this constructor.
  11798. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
  11799. LangAS AS = getDefaultCXXMethodAddrSpace();
  11800. if (AS != LangAS::Default) {
  11801. EPI.TypeQuals.addAddressSpace(AS);
  11802. }
  11803. auto QT = Context.getFunctionType(ResultTy, Args, EPI);
  11804. SpecialMem->setType(QT);
  11805. // During template instantiation of implicit special member functions we need
  11806. // a reliable TypeSourceInfo for the function prototype in order to allow
  11807. // functions to be substituted.
  11808. if (inTemplateInstantiation() &&
  11809. cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
  11810. TypeSourceInfo *TSI =
  11811. Context.getTrivialTypeSourceInfo(SpecialMem->getType());
  11812. SpecialMem->setTypeSourceInfo(TSI);
  11813. }
  11814. }
  11815. CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
  11816. CXXRecordDecl *ClassDecl) {
  11817. // C++ [class.ctor]p5:
  11818. // A default constructor for a class X is a constructor of class X
  11819. // that can be called without an argument. If there is no
  11820. // user-declared constructor for class X, a default constructor is
  11821. // implicitly declared. An implicitly-declared default constructor
  11822. // is an inline public member of its class.
  11823. assert(ClassDecl->needsImplicitDefaultConstructor() &&
  11824. "Should not build implicit default constructor!");
  11825. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
  11826. if (DSM.isAlreadyBeingDeclared())
  11827. return nullptr;
  11828. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  11829. CXXDefaultConstructor,
  11830. false);
  11831. // Create the actual constructor declaration.
  11832. CanQualType ClassType
  11833. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  11834. SourceLocation ClassLoc = ClassDecl->getLocation();
  11835. DeclarationName Name
  11836. = Context.DeclarationNames.getCXXConstructorName(ClassType);
  11837. DeclarationNameInfo NameInfo(Name, ClassLoc);
  11838. CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
  11839. Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
  11840. /*TInfo=*/nullptr, ExplicitSpecifier(),
  11841. getCurFPFeatures().isFPConstrained(),
  11842. /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  11843. Constexpr ? ConstexprSpecKind::Constexpr
  11844. : ConstexprSpecKind::Unspecified);
  11845. DefaultCon->setAccess(AS_public);
  11846. DefaultCon->setDefaulted();
  11847. setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
  11848. if (getLangOpts().CUDA)
  11849. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
  11850. DefaultCon,
  11851. /* ConstRHS */ false,
  11852. /* Diagnose */ false);
  11853. // We don't need to use SpecialMemberIsTrivial here; triviality for default
  11854. // constructors is easy to compute.
  11855. DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
  11856. // Note that we have declared this constructor.
  11857. ++getASTContext().NumImplicitDefaultConstructorsDeclared;
  11858. Scope *S = getScopeForContext(ClassDecl);
  11859. CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
  11860. if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
  11861. SetDeclDeleted(DefaultCon, ClassLoc);
  11862. if (S)
  11863. PushOnScopeChains(DefaultCon, S, false);
  11864. ClassDecl->addDecl(DefaultCon);
  11865. return DefaultCon;
  11866. }
  11867. void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
  11868. CXXConstructorDecl *Constructor) {
  11869. assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  11870. !Constructor->doesThisDeclarationHaveABody() &&
  11871. !Constructor->isDeleted()) &&
  11872. "DefineImplicitDefaultConstructor - call it for implicit default ctor");
  11873. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  11874. return;
  11875. CXXRecordDecl *ClassDecl = Constructor->getParent();
  11876. assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
  11877. SynthesizedFunctionScope Scope(*this, Constructor);
  11878. // The exception specification is needed because we are defining the
  11879. // function.
  11880. ResolveExceptionSpec(CurrentLocation,
  11881. Constructor->getType()->castAs<FunctionProtoType>());
  11882. MarkVTableUsed(CurrentLocation, ClassDecl);
  11883. // Add a context note for diagnostics produced after this point.
  11884. Scope.addContextNote(CurrentLocation);
  11885. if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
  11886. Constructor->setInvalidDecl();
  11887. return;
  11888. }
  11889. SourceLocation Loc = Constructor->getEndLoc().isValid()
  11890. ? Constructor->getEndLoc()
  11891. : Constructor->getLocation();
  11892. Constructor->setBody(new (Context) CompoundStmt(Loc));
  11893. Constructor->markUsed(Context);
  11894. if (ASTMutationListener *L = getASTMutationListener()) {
  11895. L->CompletedImplicitDefinition(Constructor);
  11896. }
  11897. DiagnoseUninitializedFields(*this, Constructor);
  11898. }
  11899. void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
  11900. // Perform any delayed checks on exception specifications.
  11901. CheckDelayedMemberExceptionSpecs();
  11902. }
  11903. /// Find or create the fake constructor we synthesize to model constructing an
  11904. /// object of a derived class via a constructor of a base class.
  11905. CXXConstructorDecl *
  11906. Sema::findInheritingConstructor(SourceLocation Loc,
  11907. CXXConstructorDecl *BaseCtor,
  11908. ConstructorUsingShadowDecl *Shadow) {
  11909. CXXRecordDecl *Derived = Shadow->getParent();
  11910. SourceLocation UsingLoc = Shadow->getLocation();
  11911. // FIXME: Add a new kind of DeclarationName for an inherited constructor.
  11912. // For now we use the name of the base class constructor as a member of the
  11913. // derived class to indicate a (fake) inherited constructor name.
  11914. DeclarationName Name = BaseCtor->getDeclName();
  11915. // Check to see if we already have a fake constructor for this inherited
  11916. // constructor call.
  11917. for (NamedDecl *Ctor : Derived->lookup(Name))
  11918. if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
  11919. ->getInheritedConstructor()
  11920. .getConstructor(),
  11921. BaseCtor))
  11922. return cast<CXXConstructorDecl>(Ctor);
  11923. DeclarationNameInfo NameInfo(Name, UsingLoc);
  11924. TypeSourceInfo *TInfo =
  11925. Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
  11926. FunctionProtoTypeLoc ProtoLoc =
  11927. TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
  11928. // Check the inherited constructor is valid and find the list of base classes
  11929. // from which it was inherited.
  11930. InheritedConstructorInfo ICI(*this, Loc, Shadow);
  11931. bool Constexpr =
  11932. BaseCtor->isConstexpr() &&
  11933. defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
  11934. false, BaseCtor, &ICI);
  11935. CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
  11936. Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
  11937. BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
  11938. /*isInline=*/true,
  11939. /*isImplicitlyDeclared=*/true,
  11940. Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
  11941. InheritedConstructor(Shadow, BaseCtor),
  11942. BaseCtor->getTrailingRequiresClause());
  11943. if (Shadow->isInvalidDecl())
  11944. DerivedCtor->setInvalidDecl();
  11945. // Build an unevaluated exception specification for this fake constructor.
  11946. const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
  11947. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  11948. EPI.ExceptionSpec.Type = EST_Unevaluated;
  11949. EPI.ExceptionSpec.SourceDecl = DerivedCtor;
  11950. DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
  11951. FPT->getParamTypes(), EPI));
  11952. // Build the parameter declarations.
  11953. SmallVector<ParmVarDecl *, 16> ParamDecls;
  11954. for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
  11955. TypeSourceInfo *TInfo =
  11956. Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
  11957. ParmVarDecl *PD = ParmVarDecl::Create(
  11958. Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
  11959. FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
  11960. PD->setScopeInfo(0, I);
  11961. PD->setImplicit();
  11962. // Ensure attributes are propagated onto parameters (this matters for
  11963. // format, pass_object_size, ...).
  11964. mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
  11965. ParamDecls.push_back(PD);
  11966. ProtoLoc.setParam(I, PD);
  11967. }
  11968. // Set up the new constructor.
  11969. assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
  11970. DerivedCtor->setAccess(BaseCtor->getAccess());
  11971. DerivedCtor->setParams(ParamDecls);
  11972. Derived->addDecl(DerivedCtor);
  11973. if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
  11974. SetDeclDeleted(DerivedCtor, UsingLoc);
  11975. return DerivedCtor;
  11976. }
  11977. void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
  11978. InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
  11979. Ctor->getInheritedConstructor().getShadowDecl());
  11980. ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
  11981. /*Diagnose*/true);
  11982. }
  11983. void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
  11984. CXXConstructorDecl *Constructor) {
  11985. CXXRecordDecl *ClassDecl = Constructor->getParent();
  11986. assert(Constructor->getInheritedConstructor() &&
  11987. !Constructor->doesThisDeclarationHaveABody() &&
  11988. !Constructor->isDeleted());
  11989. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  11990. return;
  11991. // Initializations are performed "as if by a defaulted default constructor",
  11992. // so enter the appropriate scope.
  11993. SynthesizedFunctionScope Scope(*this, Constructor);
  11994. // The exception specification is needed because we are defining the
  11995. // function.
  11996. ResolveExceptionSpec(CurrentLocation,
  11997. Constructor->getType()->castAs<FunctionProtoType>());
  11998. MarkVTableUsed(CurrentLocation, ClassDecl);
  11999. // Add a context note for diagnostics produced after this point.
  12000. Scope.addContextNote(CurrentLocation);
  12001. ConstructorUsingShadowDecl *Shadow =
  12002. Constructor->getInheritedConstructor().getShadowDecl();
  12003. CXXConstructorDecl *InheritedCtor =
  12004. Constructor->getInheritedConstructor().getConstructor();
  12005. // [class.inhctor.init]p1:
  12006. // initialization proceeds as if a defaulted default constructor is used to
  12007. // initialize the D object and each base class subobject from which the
  12008. // constructor was inherited
  12009. InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
  12010. CXXRecordDecl *RD = Shadow->getParent();
  12011. SourceLocation InitLoc = Shadow->getLocation();
  12012. // Build explicit initializers for all base classes from which the
  12013. // constructor was inherited.
  12014. SmallVector<CXXCtorInitializer*, 8> Inits;
  12015. for (bool VBase : {false, true}) {
  12016. for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
  12017. if (B.isVirtual() != VBase)
  12018. continue;
  12019. auto *BaseRD = B.getType()->getAsCXXRecordDecl();
  12020. if (!BaseRD)
  12021. continue;
  12022. auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
  12023. if (!BaseCtor.first)
  12024. continue;
  12025. MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
  12026. ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
  12027. InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
  12028. auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
  12029. Inits.push_back(new (Context) CXXCtorInitializer(
  12030. Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
  12031. SourceLocation()));
  12032. }
  12033. }
  12034. // We now proceed as if for a defaulted default constructor, with the relevant
  12035. // initializers replaced.
  12036. if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
  12037. Constructor->setInvalidDecl();
  12038. return;
  12039. }
  12040. Constructor->setBody(new (Context) CompoundStmt(InitLoc));
  12041. Constructor->markUsed(Context);
  12042. if (ASTMutationListener *L = getASTMutationListener()) {
  12043. L->CompletedImplicitDefinition(Constructor);
  12044. }
  12045. DiagnoseUninitializedFields(*this, Constructor);
  12046. }
  12047. CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
  12048. // C++ [class.dtor]p2:
  12049. // If a class has no user-declared destructor, a destructor is
  12050. // declared implicitly. An implicitly-declared destructor is an
  12051. // inline public member of its class.
  12052. assert(ClassDecl->needsImplicitDestructor());
  12053. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
  12054. if (DSM.isAlreadyBeingDeclared())
  12055. return nullptr;
  12056. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  12057. CXXDestructor,
  12058. false);
  12059. // Create the actual destructor declaration.
  12060. CanQualType ClassType
  12061. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  12062. SourceLocation ClassLoc = ClassDecl->getLocation();
  12063. DeclarationName Name
  12064. = Context.DeclarationNames.getCXXDestructorName(ClassType);
  12065. DeclarationNameInfo NameInfo(Name, ClassLoc);
  12066. CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
  12067. Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
  12068. getCurFPFeatures().isFPConstrained(),
  12069. /*isInline=*/true,
  12070. /*isImplicitlyDeclared=*/true,
  12071. Constexpr ? ConstexprSpecKind::Constexpr
  12072. : ConstexprSpecKind::Unspecified);
  12073. Destructor->setAccess(AS_public);
  12074. Destructor->setDefaulted();
  12075. setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
  12076. if (getLangOpts().CUDA)
  12077. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
  12078. Destructor,
  12079. /* ConstRHS */ false,
  12080. /* Diagnose */ false);
  12081. // We don't need to use SpecialMemberIsTrivial here; triviality for
  12082. // destructors is easy to compute.
  12083. Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
  12084. Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
  12085. ClassDecl->hasTrivialDestructorForCall());
  12086. // Note that we have declared this destructor.
  12087. ++getASTContext().NumImplicitDestructorsDeclared;
  12088. Scope *S = getScopeForContext(ClassDecl);
  12089. CheckImplicitSpecialMemberDeclaration(S, Destructor);
  12090. // We can't check whether an implicit destructor is deleted before we complete
  12091. // the definition of the class, because its validity depends on the alignment
  12092. // of the class. We'll check this from ActOnFields once the class is complete.
  12093. if (ClassDecl->isCompleteDefinition() &&
  12094. ShouldDeleteSpecialMember(Destructor, CXXDestructor))
  12095. SetDeclDeleted(Destructor, ClassLoc);
  12096. // Introduce this destructor into its scope.
  12097. if (S)
  12098. PushOnScopeChains(Destructor, S, false);
  12099. ClassDecl->addDecl(Destructor);
  12100. return Destructor;
  12101. }
  12102. void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
  12103. CXXDestructorDecl *Destructor) {
  12104. assert((Destructor->isDefaulted() &&
  12105. !Destructor->doesThisDeclarationHaveABody() &&
  12106. !Destructor->isDeleted()) &&
  12107. "DefineImplicitDestructor - call it for implicit default dtor");
  12108. if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
  12109. return;
  12110. CXXRecordDecl *ClassDecl = Destructor->getParent();
  12111. assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
  12112. SynthesizedFunctionScope Scope(*this, Destructor);
  12113. // The exception specification is needed because we are defining the
  12114. // function.
  12115. ResolveExceptionSpec(CurrentLocation,
  12116. Destructor->getType()->castAs<FunctionProtoType>());
  12117. MarkVTableUsed(CurrentLocation, ClassDecl);
  12118. // Add a context note for diagnostics produced after this point.
  12119. Scope.addContextNote(CurrentLocation);
  12120. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  12121. Destructor->getParent());
  12122. if (CheckDestructor(Destructor)) {
  12123. Destructor->setInvalidDecl();
  12124. return;
  12125. }
  12126. SourceLocation Loc = Destructor->getEndLoc().isValid()
  12127. ? Destructor->getEndLoc()
  12128. : Destructor->getLocation();
  12129. Destructor->setBody(new (Context) CompoundStmt(Loc));
  12130. Destructor->markUsed(Context);
  12131. if (ASTMutationListener *L = getASTMutationListener()) {
  12132. L->CompletedImplicitDefinition(Destructor);
  12133. }
  12134. }
  12135. void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
  12136. CXXDestructorDecl *Destructor) {
  12137. if (Destructor->isInvalidDecl())
  12138. return;
  12139. CXXRecordDecl *ClassDecl = Destructor->getParent();
  12140. assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  12141. "implicit complete dtors unneeded outside MS ABI");
  12142. assert(ClassDecl->getNumVBases() > 0 &&
  12143. "complete dtor only exists for classes with vbases");
  12144. SynthesizedFunctionScope Scope(*this, Destructor);
  12145. // Add a context note for diagnostics produced after this point.
  12146. Scope.addContextNote(CurrentLocation);
  12147. MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
  12148. }
  12149. /// Perform any semantic analysis which needs to be delayed until all
  12150. /// pending class member declarations have been parsed.
  12151. void Sema::ActOnFinishCXXMemberDecls() {
  12152. // If the context is an invalid C++ class, just suppress these checks.
  12153. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
  12154. if (Record->isInvalidDecl()) {
  12155. DelayedOverridingExceptionSpecChecks.clear();
  12156. DelayedEquivalentExceptionSpecChecks.clear();
  12157. return;
  12158. }
  12159. checkForMultipleExportedDefaultConstructors(*this, Record);
  12160. }
  12161. }
  12162. void Sema::ActOnFinishCXXNonNestedClass() {
  12163. referenceDLLExportedClassMethods();
  12164. if (!DelayedDllExportMemberFunctions.empty()) {
  12165. SmallVector<CXXMethodDecl*, 4> WorkList;
  12166. std::swap(DelayedDllExportMemberFunctions, WorkList);
  12167. for (CXXMethodDecl *M : WorkList) {
  12168. DefineDefaultedFunction(*this, M, M->getLocation());
  12169. // Pass the method to the consumer to get emitted. This is not necessary
  12170. // for explicit instantiation definitions, as they will get emitted
  12171. // anyway.
  12172. if (M->getParent()->getTemplateSpecializationKind() !=
  12173. TSK_ExplicitInstantiationDefinition)
  12174. ActOnFinishInlineFunctionDef(M);
  12175. }
  12176. }
  12177. }
  12178. void Sema::referenceDLLExportedClassMethods() {
  12179. if (!DelayedDllExportClasses.empty()) {
  12180. // Calling ReferenceDllExportedMembers might cause the current function to
  12181. // be called again, so use a local copy of DelayedDllExportClasses.
  12182. SmallVector<CXXRecordDecl *, 4> WorkList;
  12183. std::swap(DelayedDllExportClasses, WorkList);
  12184. for (CXXRecordDecl *Class : WorkList)
  12185. ReferenceDllExportedMembers(*this, Class);
  12186. }
  12187. }
  12188. void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
  12189. assert(getLangOpts().CPlusPlus11 &&
  12190. "adjusting dtor exception specs was introduced in c++11");
  12191. if (Destructor->isDependentContext())
  12192. return;
  12193. // C++11 [class.dtor]p3:
  12194. // A declaration of a destructor that does not have an exception-
  12195. // specification is implicitly considered to have the same exception-
  12196. // specification as an implicit declaration.
  12197. const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
  12198. if (DtorType->hasExceptionSpec())
  12199. return;
  12200. // Replace the destructor's type, building off the existing one. Fortunately,
  12201. // the only thing of interest in the destructor type is its extended info.
  12202. // The return and arguments are fixed.
  12203. FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
  12204. EPI.ExceptionSpec.Type = EST_Unevaluated;
  12205. EPI.ExceptionSpec.SourceDecl = Destructor;
  12206. Destructor->setType(
  12207. Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
  12208. // FIXME: If the destructor has a body that could throw, and the newly created
  12209. // spec doesn't allow exceptions, we should emit a warning, because this
  12210. // change in behavior can break conforming C++03 programs at runtime.
  12211. // However, we don't have a body or an exception specification yet, so it
  12212. // needs to be done somewhere else.
  12213. }
  12214. namespace {
  12215. /// An abstract base class for all helper classes used in building the
  12216. // copy/move operators. These classes serve as factory functions and help us
  12217. // avoid using the same Expr* in the AST twice.
  12218. class ExprBuilder {
  12219. ExprBuilder(const ExprBuilder&) = delete;
  12220. ExprBuilder &operator=(const ExprBuilder&) = delete;
  12221. protected:
  12222. static Expr *assertNotNull(Expr *E) {
  12223. assert(E && "Expression construction must not fail.");
  12224. return E;
  12225. }
  12226. public:
  12227. ExprBuilder() {}
  12228. virtual ~ExprBuilder() {}
  12229. virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
  12230. };
  12231. class RefBuilder: public ExprBuilder {
  12232. VarDecl *Var;
  12233. QualType VarType;
  12234. public:
  12235. Expr *build(Sema &S, SourceLocation Loc) const override {
  12236. return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
  12237. }
  12238. RefBuilder(VarDecl *Var, QualType VarType)
  12239. : Var(Var), VarType(VarType) {}
  12240. };
  12241. class ThisBuilder: public ExprBuilder {
  12242. public:
  12243. Expr *build(Sema &S, SourceLocation Loc) const override {
  12244. return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
  12245. }
  12246. };
  12247. class CastBuilder: public ExprBuilder {
  12248. const ExprBuilder &Builder;
  12249. QualType Type;
  12250. ExprValueKind Kind;
  12251. const CXXCastPath &Path;
  12252. public:
  12253. Expr *build(Sema &S, SourceLocation Loc) const override {
  12254. return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
  12255. CK_UncheckedDerivedToBase, Kind,
  12256. &Path).get());
  12257. }
  12258. CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
  12259. const CXXCastPath &Path)
  12260. : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
  12261. };
  12262. class DerefBuilder: public ExprBuilder {
  12263. const ExprBuilder &Builder;
  12264. public:
  12265. Expr *build(Sema &S, SourceLocation Loc) const override {
  12266. return assertNotNull(
  12267. S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
  12268. }
  12269. DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  12270. };
  12271. class MemberBuilder: public ExprBuilder {
  12272. const ExprBuilder &Builder;
  12273. QualType Type;
  12274. CXXScopeSpec SS;
  12275. bool IsArrow;
  12276. LookupResult &MemberLookup;
  12277. public:
  12278. Expr *build(Sema &S, SourceLocation Loc) const override {
  12279. return assertNotNull(S.BuildMemberReferenceExpr(
  12280. Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
  12281. nullptr, MemberLookup, nullptr, nullptr).get());
  12282. }
  12283. MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
  12284. LookupResult &MemberLookup)
  12285. : Builder(Builder), Type(Type), IsArrow(IsArrow),
  12286. MemberLookup(MemberLookup) {}
  12287. };
  12288. class MoveCastBuilder: public ExprBuilder {
  12289. const ExprBuilder &Builder;
  12290. public:
  12291. Expr *build(Sema &S, SourceLocation Loc) const override {
  12292. return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
  12293. }
  12294. MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  12295. };
  12296. class LvalueConvBuilder: public ExprBuilder {
  12297. const ExprBuilder &Builder;
  12298. public:
  12299. Expr *build(Sema &S, SourceLocation Loc) const override {
  12300. return assertNotNull(
  12301. S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
  12302. }
  12303. LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  12304. };
  12305. class SubscriptBuilder: public ExprBuilder {
  12306. const ExprBuilder &Base;
  12307. const ExprBuilder &Index;
  12308. public:
  12309. Expr *build(Sema &S, SourceLocation Loc) const override {
  12310. return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
  12311. Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
  12312. }
  12313. SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
  12314. : Base(Base), Index(Index) {}
  12315. };
  12316. } // end anonymous namespace
  12317. /// When generating a defaulted copy or move assignment operator, if a field
  12318. /// should be copied with __builtin_memcpy rather than via explicit assignments,
  12319. /// do so. This optimization only applies for arrays of scalars, and for arrays
  12320. /// of class type where the selected copy/move-assignment operator is trivial.
  12321. static StmtResult
  12322. buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
  12323. const ExprBuilder &ToB, const ExprBuilder &FromB) {
  12324. // Compute the size of the memory buffer to be copied.
  12325. QualType SizeType = S.Context.getSizeType();
  12326. llvm::APInt Size(S.Context.getTypeSize(SizeType),
  12327. S.Context.getTypeSizeInChars(T).getQuantity());
  12328. // Take the address of the field references for "from" and "to". We
  12329. // directly construct UnaryOperators here because semantic analysis
  12330. // does not permit us to take the address of an xvalue.
  12331. Expr *From = FromB.build(S, Loc);
  12332. From = UnaryOperator::Create(
  12333. S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
  12334. VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
  12335. Expr *To = ToB.build(S, Loc);
  12336. To = UnaryOperator::Create(
  12337. S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
  12338. VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
  12339. const Type *E = T->getBaseElementTypeUnsafe();
  12340. bool NeedsCollectableMemCpy =
  12341. E->isRecordType() &&
  12342. E->castAs<RecordType>()->getDecl()->hasObjectMember();
  12343. // Create a reference to the __builtin_objc_memmove_collectable function
  12344. StringRef MemCpyName = NeedsCollectableMemCpy ?
  12345. "__builtin_objc_memmove_collectable" :
  12346. "__builtin_memcpy";
  12347. LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
  12348. Sema::LookupOrdinaryName);
  12349. S.LookupName(R, S.TUScope, true);
  12350. FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
  12351. if (!MemCpy)
  12352. // Something went horribly wrong earlier, and we will have complained
  12353. // about it.
  12354. return StmtError();
  12355. ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
  12356. VK_PRValue, Loc, nullptr);
  12357. assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
  12358. Expr *CallArgs[] = {
  12359. To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
  12360. };
  12361. ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
  12362. Loc, CallArgs, Loc);
  12363. assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
  12364. return Call.getAs<Stmt>();
  12365. }
  12366. /// Builds a statement that copies/moves the given entity from \p From to
  12367. /// \c To.
  12368. ///
  12369. /// This routine is used to copy/move the members of a class with an
  12370. /// implicitly-declared copy/move assignment operator. When the entities being
  12371. /// copied are arrays, this routine builds for loops to copy them.
  12372. ///
  12373. /// \param S The Sema object used for type-checking.
  12374. ///
  12375. /// \param Loc The location where the implicit copy/move is being generated.
  12376. ///
  12377. /// \param T The type of the expressions being copied/moved. Both expressions
  12378. /// must have this type.
  12379. ///
  12380. /// \param To The expression we are copying/moving to.
  12381. ///
  12382. /// \param From The expression we are copying/moving from.
  12383. ///
  12384. /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
  12385. /// Otherwise, it's a non-static member subobject.
  12386. ///
  12387. /// \param Copying Whether we're copying or moving.
  12388. ///
  12389. /// \param Depth Internal parameter recording the depth of the recursion.
  12390. ///
  12391. /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
  12392. /// if a memcpy should be used instead.
  12393. static StmtResult
  12394. buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
  12395. const ExprBuilder &To, const ExprBuilder &From,
  12396. bool CopyingBaseSubobject, bool Copying,
  12397. unsigned Depth = 0) {
  12398. // C++11 [class.copy]p28:
  12399. // Each subobject is assigned in the manner appropriate to its type:
  12400. //
  12401. // - if the subobject is of class type, as if by a call to operator= with
  12402. // the subobject as the object expression and the corresponding
  12403. // subobject of x as a single function argument (as if by explicit
  12404. // qualification; that is, ignoring any possible virtual overriding
  12405. // functions in more derived classes);
  12406. //
  12407. // C++03 [class.copy]p13:
  12408. // - if the subobject is of class type, the copy assignment operator for
  12409. // the class is used (as if by explicit qualification; that is,
  12410. // ignoring any possible virtual overriding functions in more derived
  12411. // classes);
  12412. if (const RecordType *RecordTy = T->getAs<RecordType>()) {
  12413. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  12414. // Look for operator=.
  12415. DeclarationName Name
  12416. = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  12417. LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
  12418. S.LookupQualifiedName(OpLookup, ClassDecl, false);
  12419. // Prior to C++11, filter out any result that isn't a copy/move-assignment
  12420. // operator.
  12421. if (!S.getLangOpts().CPlusPlus11) {
  12422. LookupResult::Filter F = OpLookup.makeFilter();
  12423. while (F.hasNext()) {
  12424. NamedDecl *D = F.next();
  12425. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  12426. if (Method->isCopyAssignmentOperator() ||
  12427. (!Copying && Method->isMoveAssignmentOperator()))
  12428. continue;
  12429. F.erase();
  12430. }
  12431. F.done();
  12432. }
  12433. // Suppress the protected check (C++ [class.protected]) for each of the
  12434. // assignment operators we found. This strange dance is required when
  12435. // we're assigning via a base classes's copy-assignment operator. To
  12436. // ensure that we're getting the right base class subobject (without
  12437. // ambiguities), we need to cast "this" to that subobject type; to
  12438. // ensure that we don't go through the virtual call mechanism, we need
  12439. // to qualify the operator= name with the base class (see below). However,
  12440. // this means that if the base class has a protected copy assignment
  12441. // operator, the protected member access check will fail. So, we
  12442. // rewrite "protected" access to "public" access in this case, since we
  12443. // know by construction that we're calling from a derived class.
  12444. if (CopyingBaseSubobject) {
  12445. for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
  12446. L != LEnd; ++L) {
  12447. if (L.getAccess() == AS_protected)
  12448. L.setAccess(AS_public);
  12449. }
  12450. }
  12451. // Create the nested-name-specifier that will be used to qualify the
  12452. // reference to operator=; this is required to suppress the virtual
  12453. // call mechanism.
  12454. CXXScopeSpec SS;
  12455. const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
  12456. SS.MakeTrivial(S.Context,
  12457. NestedNameSpecifier::Create(S.Context, nullptr, false,
  12458. CanonicalT),
  12459. Loc);
  12460. // Create the reference to operator=.
  12461. ExprResult OpEqualRef
  12462. = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
  12463. SS, /*TemplateKWLoc=*/SourceLocation(),
  12464. /*FirstQualifierInScope=*/nullptr,
  12465. OpLookup,
  12466. /*TemplateArgs=*/nullptr, /*S*/nullptr,
  12467. /*SuppressQualifierCheck=*/true);
  12468. if (OpEqualRef.isInvalid())
  12469. return StmtError();
  12470. // Build the call to the assignment operator.
  12471. Expr *FromInst = From.build(S, Loc);
  12472. ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
  12473. OpEqualRef.getAs<Expr>(),
  12474. Loc, FromInst, Loc);
  12475. if (Call.isInvalid())
  12476. return StmtError();
  12477. // If we built a call to a trivial 'operator=' while copying an array,
  12478. // bail out. We'll replace the whole shebang with a memcpy.
  12479. CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
  12480. if (CE && CE->getMethodDecl()->isTrivial() && Depth)
  12481. return StmtResult((Stmt*)nullptr);
  12482. // Convert to an expression-statement, and clean up any produced
  12483. // temporaries.
  12484. return S.ActOnExprStmt(Call);
  12485. }
  12486. // - if the subobject is of scalar type, the built-in assignment
  12487. // operator is used.
  12488. const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
  12489. if (!ArrayTy) {
  12490. ExprResult Assignment = S.CreateBuiltinBinOp(
  12491. Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
  12492. if (Assignment.isInvalid())
  12493. return StmtError();
  12494. return S.ActOnExprStmt(Assignment);
  12495. }
  12496. // - if the subobject is an array, each element is assigned, in the
  12497. // manner appropriate to the element type;
  12498. // Construct a loop over the array bounds, e.g.,
  12499. //
  12500. // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
  12501. //
  12502. // that will copy each of the array elements.
  12503. QualType SizeType = S.Context.getSizeType();
  12504. // Create the iteration variable.
  12505. IdentifierInfo *IterationVarName = nullptr;
  12506. {
  12507. SmallString<8> Str;
  12508. llvm::raw_svector_ostream OS(Str);
  12509. OS << "__i" << Depth;
  12510. IterationVarName = &S.Context.Idents.get(OS.str());
  12511. }
  12512. VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  12513. IterationVarName, SizeType,
  12514. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  12515. SC_None);
  12516. // Initialize the iteration variable to zero.
  12517. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  12518. IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  12519. // Creates a reference to the iteration variable.
  12520. RefBuilder IterationVarRef(IterationVar, SizeType);
  12521. LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
  12522. // Create the DeclStmt that holds the iteration variable.
  12523. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
  12524. // Subscript the "from" and "to" expressions with the iteration variable.
  12525. SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
  12526. MoveCastBuilder FromIndexMove(FromIndexCopy);
  12527. const ExprBuilder *FromIndex;
  12528. if (Copying)
  12529. FromIndex = &FromIndexCopy;
  12530. else
  12531. FromIndex = &FromIndexMove;
  12532. SubscriptBuilder ToIndex(To, IterationVarRefRVal);
  12533. // Build the copy/move for an individual element of the array.
  12534. StmtResult Copy =
  12535. buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
  12536. ToIndex, *FromIndex, CopyingBaseSubobject,
  12537. Copying, Depth + 1);
  12538. // Bail out if copying fails or if we determined that we should use memcpy.
  12539. if (Copy.isInvalid() || !Copy.get())
  12540. return Copy;
  12541. // Create the comparison against the array bound.
  12542. llvm::APInt Upper
  12543. = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
  12544. Expr *Comparison = BinaryOperator::Create(
  12545. S.Context, IterationVarRefRVal.build(S, Loc),
  12546. IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
  12547. S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
  12548. S.CurFPFeatureOverrides());
  12549. // Create the pre-increment of the iteration variable. We can determine
  12550. // whether the increment will overflow based on the value of the array
  12551. // bound.
  12552. Expr *Increment = UnaryOperator::Create(
  12553. S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
  12554. OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
  12555. // Construct the loop that copies all elements of this array.
  12556. return S.ActOnForStmt(
  12557. Loc, Loc, InitStmt,
  12558. S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
  12559. S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
  12560. }
  12561. static StmtResult
  12562. buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
  12563. const ExprBuilder &To, const ExprBuilder &From,
  12564. bool CopyingBaseSubobject, bool Copying) {
  12565. // Maybe we should use a memcpy?
  12566. if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
  12567. T.isTriviallyCopyableType(S.Context))
  12568. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  12569. StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
  12570. CopyingBaseSubobject,
  12571. Copying, 0));
  12572. // If we ended up picking a trivial assignment operator for an array of a
  12573. // non-trivially-copyable class type, just emit a memcpy.
  12574. if (!Result.isInvalid() && !Result.get())
  12575. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  12576. return Result;
  12577. }
  12578. CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
  12579. // Note: The following rules are largely analoguous to the copy
  12580. // constructor rules. Note that virtual bases are not taken into account
  12581. // for determining the argument type of the operator. Note also that
  12582. // operators taking an object instead of a reference are allowed.
  12583. assert(ClassDecl->needsImplicitCopyAssignment());
  12584. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
  12585. if (DSM.isAlreadyBeingDeclared())
  12586. return nullptr;
  12587. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  12588. ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
  12589. LangAS AS = getDefaultCXXMethodAddrSpace();
  12590. if (AS != LangAS::Default)
  12591. ArgType = Context.getAddrSpaceQualType(ArgType, AS);
  12592. QualType RetType = Context.getLValueReferenceType(ArgType);
  12593. bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
  12594. if (Const)
  12595. ArgType = ArgType.withConst();
  12596. ArgType = Context.getLValueReferenceType(ArgType);
  12597. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  12598. CXXCopyAssignment,
  12599. Const);
  12600. // An implicitly-declared copy assignment operator is an inline public
  12601. // member of its class.
  12602. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  12603. SourceLocation ClassLoc = ClassDecl->getLocation();
  12604. DeclarationNameInfo NameInfo(Name, ClassLoc);
  12605. CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
  12606. Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  12607. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  12608. getCurFPFeatures().isFPConstrained(),
  12609. /*isInline=*/true,
  12610. Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
  12611. SourceLocation());
  12612. CopyAssignment->setAccess(AS_public);
  12613. CopyAssignment->setDefaulted();
  12614. CopyAssignment->setImplicit();
  12615. setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
  12616. if (getLangOpts().CUDA)
  12617. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
  12618. CopyAssignment,
  12619. /* ConstRHS */ Const,
  12620. /* Diagnose */ false);
  12621. // Add the parameter to the operator.
  12622. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
  12623. ClassLoc, ClassLoc,
  12624. /*Id=*/nullptr, ArgType,
  12625. /*TInfo=*/nullptr, SC_None,
  12626. nullptr);
  12627. CopyAssignment->setParams(FromParam);
  12628. CopyAssignment->setTrivial(
  12629. ClassDecl->needsOverloadResolutionForCopyAssignment()
  12630. ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
  12631. : ClassDecl->hasTrivialCopyAssignment());
  12632. // Note that we have added this copy-assignment operator.
  12633. ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
  12634. Scope *S = getScopeForContext(ClassDecl);
  12635. CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
  12636. if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
  12637. ClassDecl->setImplicitCopyAssignmentIsDeleted();
  12638. SetDeclDeleted(CopyAssignment, ClassLoc);
  12639. }
  12640. if (S)
  12641. PushOnScopeChains(CopyAssignment, S, false);
  12642. ClassDecl->addDecl(CopyAssignment);
  12643. return CopyAssignment;
  12644. }
  12645. /// Diagnose an implicit copy operation for a class which is odr-used, but
  12646. /// which is deprecated because the class has a user-declared copy constructor,
  12647. /// copy assignment operator, or destructor.
  12648. static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
  12649. assert(CopyOp->isImplicit());
  12650. CXXRecordDecl *RD = CopyOp->getParent();
  12651. CXXMethodDecl *UserDeclaredOperation = nullptr;
  12652. if (RD->hasUserDeclaredDestructor()) {
  12653. UserDeclaredOperation = RD->getDestructor();
  12654. } else if (!isa<CXXConstructorDecl>(CopyOp) &&
  12655. RD->hasUserDeclaredCopyConstructor()) {
  12656. // Find any user-declared copy constructor.
  12657. for (auto *I : RD->ctors()) {
  12658. if (I->isCopyConstructor()) {
  12659. UserDeclaredOperation = I;
  12660. break;
  12661. }
  12662. }
  12663. assert(UserDeclaredOperation);
  12664. } else if (isa<CXXConstructorDecl>(CopyOp) &&
  12665. RD->hasUserDeclaredCopyAssignment()) {
  12666. // Find any user-declared move assignment operator.
  12667. for (auto *I : RD->methods()) {
  12668. if (I->isCopyAssignmentOperator()) {
  12669. UserDeclaredOperation = I;
  12670. break;
  12671. }
  12672. }
  12673. assert(UserDeclaredOperation);
  12674. }
  12675. if (UserDeclaredOperation) {
  12676. bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
  12677. bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
  12678. bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
  12679. unsigned DiagID =
  12680. (UDOIsUserProvided && UDOIsDestructor)
  12681. ? diag::warn_deprecated_copy_with_user_provided_dtor
  12682. : (UDOIsUserProvided && !UDOIsDestructor)
  12683. ? diag::warn_deprecated_copy_with_user_provided_copy
  12684. : (!UDOIsUserProvided && UDOIsDestructor)
  12685. ? diag::warn_deprecated_copy_with_dtor
  12686. : diag::warn_deprecated_copy;
  12687. S.Diag(UserDeclaredOperation->getLocation(), DiagID)
  12688. << RD << IsCopyAssignment;
  12689. }
  12690. }
  12691. void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
  12692. CXXMethodDecl *CopyAssignOperator) {
  12693. assert((CopyAssignOperator->isDefaulted() &&
  12694. CopyAssignOperator->isOverloadedOperator() &&
  12695. CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
  12696. !CopyAssignOperator->doesThisDeclarationHaveABody() &&
  12697. !CopyAssignOperator->isDeleted()) &&
  12698. "DefineImplicitCopyAssignment called for wrong function");
  12699. if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
  12700. return;
  12701. CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
  12702. if (ClassDecl->isInvalidDecl()) {
  12703. CopyAssignOperator->setInvalidDecl();
  12704. return;
  12705. }
  12706. SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
  12707. // The exception specification is needed because we are defining the
  12708. // function.
  12709. ResolveExceptionSpec(CurrentLocation,
  12710. CopyAssignOperator->getType()->castAs<FunctionProtoType>());
  12711. // Add a context note for diagnostics produced after this point.
  12712. Scope.addContextNote(CurrentLocation);
  12713. // C++11 [class.copy]p18:
  12714. // The [definition of an implicitly declared copy assignment operator] is
  12715. // deprecated if the class has a user-declared copy constructor or a
  12716. // user-declared destructor.
  12717. if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
  12718. diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
  12719. // C++0x [class.copy]p30:
  12720. // The implicitly-defined or explicitly-defaulted copy assignment operator
  12721. // for a non-union class X performs memberwise copy assignment of its
  12722. // subobjects. The direct base classes of X are assigned first, in the
  12723. // order of their declaration in the base-specifier-list, and then the
  12724. // immediate non-static data members of X are assigned, in the order in
  12725. // which they were declared in the class definition.
  12726. // The statements that form the synthesized function body.
  12727. SmallVector<Stmt*, 8> Statements;
  12728. // The parameter for the "other" object, which we are copying from.
  12729. ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
  12730. Qualifiers OtherQuals = Other->getType().getQualifiers();
  12731. QualType OtherRefType = Other->getType();
  12732. if (const LValueReferenceType *OtherRef
  12733. = OtherRefType->getAs<LValueReferenceType>()) {
  12734. OtherRefType = OtherRef->getPointeeType();
  12735. OtherQuals = OtherRefType.getQualifiers();
  12736. }
  12737. // Our location for everything implicitly-generated.
  12738. SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
  12739. ? CopyAssignOperator->getEndLoc()
  12740. : CopyAssignOperator->getLocation();
  12741. // Builds a DeclRefExpr for the "other" object.
  12742. RefBuilder OtherRef(Other, OtherRefType);
  12743. // Builds the "this" pointer.
  12744. ThisBuilder This;
  12745. // Assign base classes.
  12746. bool Invalid = false;
  12747. for (auto &Base : ClassDecl->bases()) {
  12748. // Form the assignment:
  12749. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
  12750. QualType BaseType = Base.getType().getUnqualifiedType();
  12751. if (!BaseType->isRecordType()) {
  12752. Invalid = true;
  12753. continue;
  12754. }
  12755. CXXCastPath BasePath;
  12756. BasePath.push_back(&Base);
  12757. // Construct the "from" expression, which is an implicit cast to the
  12758. // appropriately-qualified base type.
  12759. CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
  12760. VK_LValue, BasePath);
  12761. // Dereference "this".
  12762. DerefBuilder DerefThis(This);
  12763. CastBuilder To(DerefThis,
  12764. Context.getQualifiedType(
  12765. BaseType, CopyAssignOperator->getMethodQualifiers()),
  12766. VK_LValue, BasePath);
  12767. // Build the copy.
  12768. StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
  12769. To, From,
  12770. /*CopyingBaseSubobject=*/true,
  12771. /*Copying=*/true);
  12772. if (Copy.isInvalid()) {
  12773. CopyAssignOperator->setInvalidDecl();
  12774. return;
  12775. }
  12776. // Success! Record the copy.
  12777. Statements.push_back(Copy.getAs<Expr>());
  12778. }
  12779. // Assign non-static members.
  12780. for (auto *Field : ClassDecl->fields()) {
  12781. // FIXME: We should form some kind of AST representation for the implied
  12782. // memcpy in a union copy operation.
  12783. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  12784. continue;
  12785. if (Field->isInvalidDecl()) {
  12786. Invalid = true;
  12787. continue;
  12788. }
  12789. // Check for members of reference type; we can't copy those.
  12790. if (Field->getType()->isReferenceType()) {
  12791. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  12792. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  12793. Diag(Field->getLocation(), diag::note_declared_at);
  12794. Invalid = true;
  12795. continue;
  12796. }
  12797. // Check for members of const-qualified, non-class type.
  12798. QualType BaseType = Context.getBaseElementType(Field->getType());
  12799. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  12800. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  12801. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  12802. Diag(Field->getLocation(), diag::note_declared_at);
  12803. Invalid = true;
  12804. continue;
  12805. }
  12806. // Suppress assigning zero-width bitfields.
  12807. if (Field->isZeroLengthBitField(Context))
  12808. continue;
  12809. QualType FieldType = Field->getType().getNonReferenceType();
  12810. if (FieldType->isIncompleteArrayType()) {
  12811. assert(ClassDecl->hasFlexibleArrayMember() &&
  12812. "Incomplete array type is not valid");
  12813. continue;
  12814. }
  12815. // Build references to the field in the object we're copying from and to.
  12816. CXXScopeSpec SS; // Intentionally empty
  12817. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  12818. LookupMemberName);
  12819. MemberLookup.addDecl(Field);
  12820. MemberLookup.resolveKind();
  12821. MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
  12822. MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/!LangOpts.HLSL,
  12823. MemberLookup);
  12824. // Build the copy of this field.
  12825. StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
  12826. To, From,
  12827. /*CopyingBaseSubobject=*/false,
  12828. /*Copying=*/true);
  12829. if (Copy.isInvalid()) {
  12830. CopyAssignOperator->setInvalidDecl();
  12831. return;
  12832. }
  12833. // Success! Record the copy.
  12834. Statements.push_back(Copy.getAs<Stmt>());
  12835. }
  12836. if (!Invalid) {
  12837. // Add a "return *this;"
  12838. Expr *ThisExpr = nullptr;
  12839. if (!LangOpts.HLSL) {
  12840. ExprResult ThisObj =
  12841. CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  12842. ThisExpr = ThisObj.get();
  12843. } else {
  12844. ThisExpr = This.build(*this, Loc);
  12845. }
  12846. StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
  12847. if (Return.isInvalid())
  12848. Invalid = true;
  12849. else
  12850. Statements.push_back(Return.getAs<Stmt>());
  12851. }
  12852. if (Invalid) {
  12853. CopyAssignOperator->setInvalidDecl();
  12854. return;
  12855. }
  12856. StmtResult Body;
  12857. {
  12858. CompoundScopeRAII CompoundScope(*this);
  12859. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  12860. /*isStmtExpr=*/false);
  12861. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  12862. }
  12863. CopyAssignOperator->setBody(Body.getAs<Stmt>());
  12864. CopyAssignOperator->markUsed(Context);
  12865. if (ASTMutationListener *L = getASTMutationListener()) {
  12866. L->CompletedImplicitDefinition(CopyAssignOperator);
  12867. }
  12868. }
  12869. CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
  12870. assert(ClassDecl->needsImplicitMoveAssignment());
  12871. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
  12872. if (DSM.isAlreadyBeingDeclared())
  12873. return nullptr;
  12874. // Note: The following rules are largely analoguous to the move
  12875. // constructor rules.
  12876. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  12877. ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
  12878. LangAS AS = getDefaultCXXMethodAddrSpace();
  12879. if (AS != LangAS::Default)
  12880. ArgType = Context.getAddrSpaceQualType(ArgType, AS);
  12881. QualType RetType = Context.getLValueReferenceType(ArgType);
  12882. ArgType = Context.getRValueReferenceType(ArgType);
  12883. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  12884. CXXMoveAssignment,
  12885. false);
  12886. // An implicitly-declared move assignment operator is an inline public
  12887. // member of its class.
  12888. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  12889. SourceLocation ClassLoc = ClassDecl->getLocation();
  12890. DeclarationNameInfo NameInfo(Name, ClassLoc);
  12891. CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
  12892. Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  12893. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  12894. getCurFPFeatures().isFPConstrained(),
  12895. /*isInline=*/true,
  12896. Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
  12897. SourceLocation());
  12898. MoveAssignment->setAccess(AS_public);
  12899. MoveAssignment->setDefaulted();
  12900. MoveAssignment->setImplicit();
  12901. setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
  12902. if (getLangOpts().CUDA)
  12903. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
  12904. MoveAssignment,
  12905. /* ConstRHS */ false,
  12906. /* Diagnose */ false);
  12907. // Add the parameter to the operator.
  12908. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
  12909. ClassLoc, ClassLoc,
  12910. /*Id=*/nullptr, ArgType,
  12911. /*TInfo=*/nullptr, SC_None,
  12912. nullptr);
  12913. MoveAssignment->setParams(FromParam);
  12914. MoveAssignment->setTrivial(
  12915. ClassDecl->needsOverloadResolutionForMoveAssignment()
  12916. ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
  12917. : ClassDecl->hasTrivialMoveAssignment());
  12918. // Note that we have added this copy-assignment operator.
  12919. ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
  12920. Scope *S = getScopeForContext(ClassDecl);
  12921. CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
  12922. if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
  12923. ClassDecl->setImplicitMoveAssignmentIsDeleted();
  12924. SetDeclDeleted(MoveAssignment, ClassLoc);
  12925. }
  12926. if (S)
  12927. PushOnScopeChains(MoveAssignment, S, false);
  12928. ClassDecl->addDecl(MoveAssignment);
  12929. return MoveAssignment;
  12930. }
  12931. /// Check if we're implicitly defining a move assignment operator for a class
  12932. /// with virtual bases. Such a move assignment might move-assign the virtual
  12933. /// base multiple times.
  12934. static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
  12935. SourceLocation CurrentLocation) {
  12936. assert(!Class->isDependentContext() && "should not define dependent move");
  12937. // Only a virtual base could get implicitly move-assigned multiple times.
  12938. // Only a non-trivial move assignment can observe this. We only want to
  12939. // diagnose if we implicitly define an assignment operator that assigns
  12940. // two base classes, both of which move-assign the same virtual base.
  12941. if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
  12942. Class->getNumBases() < 2)
  12943. return;
  12944. llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
  12945. typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
  12946. VBaseMap VBases;
  12947. for (auto &BI : Class->bases()) {
  12948. Worklist.push_back(&BI);
  12949. while (!Worklist.empty()) {
  12950. CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
  12951. CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
  12952. // If the base has no non-trivial move assignment operators,
  12953. // we don't care about moves from it.
  12954. if (!Base->hasNonTrivialMoveAssignment())
  12955. continue;
  12956. // If there's nothing virtual here, skip it.
  12957. if (!BaseSpec->isVirtual() && !Base->getNumVBases())
  12958. continue;
  12959. // If we're not actually going to call a move assignment for this base,
  12960. // or the selected move assignment is trivial, skip it.
  12961. Sema::SpecialMemberOverloadResult SMOR =
  12962. S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
  12963. /*ConstArg*/false, /*VolatileArg*/false,
  12964. /*RValueThis*/true, /*ConstThis*/false,
  12965. /*VolatileThis*/false);
  12966. if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
  12967. !SMOR.getMethod()->isMoveAssignmentOperator())
  12968. continue;
  12969. if (BaseSpec->isVirtual()) {
  12970. // We're going to move-assign this virtual base, and its move
  12971. // assignment operator is not trivial. If this can happen for
  12972. // multiple distinct direct bases of Class, diagnose it. (If it
  12973. // only happens in one base, we'll diagnose it when synthesizing
  12974. // that base class's move assignment operator.)
  12975. CXXBaseSpecifier *&Existing =
  12976. VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
  12977. .first->second;
  12978. if (Existing && Existing != &BI) {
  12979. S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
  12980. << Class << Base;
  12981. S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
  12982. << (Base->getCanonicalDecl() ==
  12983. Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  12984. << Base << Existing->getType() << Existing->getSourceRange();
  12985. S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
  12986. << (Base->getCanonicalDecl() ==
  12987. BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  12988. << Base << BI.getType() << BaseSpec->getSourceRange();
  12989. // Only diagnose each vbase once.
  12990. Existing = nullptr;
  12991. }
  12992. } else {
  12993. // Only walk over bases that have defaulted move assignment operators.
  12994. // We assume that any user-provided move assignment operator handles
  12995. // the multiple-moves-of-vbase case itself somehow.
  12996. if (!SMOR.getMethod()->isDefaulted())
  12997. continue;
  12998. // We're going to move the base classes of Base. Add them to the list.
  12999. llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
  13000. }
  13001. }
  13002. }
  13003. }
  13004. void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
  13005. CXXMethodDecl *MoveAssignOperator) {
  13006. assert((MoveAssignOperator->isDefaulted() &&
  13007. MoveAssignOperator->isOverloadedOperator() &&
  13008. MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
  13009. !MoveAssignOperator->doesThisDeclarationHaveABody() &&
  13010. !MoveAssignOperator->isDeleted()) &&
  13011. "DefineImplicitMoveAssignment called for wrong function");
  13012. if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
  13013. return;
  13014. CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
  13015. if (ClassDecl->isInvalidDecl()) {
  13016. MoveAssignOperator->setInvalidDecl();
  13017. return;
  13018. }
  13019. // C++0x [class.copy]p28:
  13020. // The implicitly-defined or move assignment operator for a non-union class
  13021. // X performs memberwise move assignment of its subobjects. The direct base
  13022. // classes of X are assigned first, in the order of their declaration in the
  13023. // base-specifier-list, and then the immediate non-static data members of X
  13024. // are assigned, in the order in which they were declared in the class
  13025. // definition.
  13026. // Issue a warning if our implicit move assignment operator will move
  13027. // from a virtual base more than once.
  13028. checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
  13029. SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
  13030. // The exception specification is needed because we are defining the
  13031. // function.
  13032. ResolveExceptionSpec(CurrentLocation,
  13033. MoveAssignOperator->getType()->castAs<FunctionProtoType>());
  13034. // Add a context note for diagnostics produced after this point.
  13035. Scope.addContextNote(CurrentLocation);
  13036. // The statements that form the synthesized function body.
  13037. SmallVector<Stmt*, 8> Statements;
  13038. // The parameter for the "other" object, which we are move from.
  13039. ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
  13040. QualType OtherRefType =
  13041. Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
  13042. // Our location for everything implicitly-generated.
  13043. SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
  13044. ? MoveAssignOperator->getEndLoc()
  13045. : MoveAssignOperator->getLocation();
  13046. // Builds a reference to the "other" object.
  13047. RefBuilder OtherRef(Other, OtherRefType);
  13048. // Cast to rvalue.
  13049. MoveCastBuilder MoveOther(OtherRef);
  13050. // Builds the "this" pointer.
  13051. ThisBuilder This;
  13052. // Assign base classes.
  13053. bool Invalid = false;
  13054. for (auto &Base : ClassDecl->bases()) {
  13055. // C++11 [class.copy]p28:
  13056. // It is unspecified whether subobjects representing virtual base classes
  13057. // are assigned more than once by the implicitly-defined copy assignment
  13058. // operator.
  13059. // FIXME: Do not assign to a vbase that will be assigned by some other base
  13060. // class. For a move-assignment, this can result in the vbase being moved
  13061. // multiple times.
  13062. // Form the assignment:
  13063. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
  13064. QualType BaseType = Base.getType().getUnqualifiedType();
  13065. if (!BaseType->isRecordType()) {
  13066. Invalid = true;
  13067. continue;
  13068. }
  13069. CXXCastPath BasePath;
  13070. BasePath.push_back(&Base);
  13071. // Construct the "from" expression, which is an implicit cast to the
  13072. // appropriately-qualified base type.
  13073. CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
  13074. // Dereference "this".
  13075. DerefBuilder DerefThis(This);
  13076. // Implicitly cast "this" to the appropriately-qualified base type.
  13077. CastBuilder To(DerefThis,
  13078. Context.getQualifiedType(
  13079. BaseType, MoveAssignOperator->getMethodQualifiers()),
  13080. VK_LValue, BasePath);
  13081. // Build the move.
  13082. StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
  13083. To, From,
  13084. /*CopyingBaseSubobject=*/true,
  13085. /*Copying=*/false);
  13086. if (Move.isInvalid()) {
  13087. MoveAssignOperator->setInvalidDecl();
  13088. return;
  13089. }
  13090. // Success! Record the move.
  13091. Statements.push_back(Move.getAs<Expr>());
  13092. }
  13093. // Assign non-static members.
  13094. for (auto *Field : ClassDecl->fields()) {
  13095. // FIXME: We should form some kind of AST representation for the implied
  13096. // memcpy in a union copy operation.
  13097. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  13098. continue;
  13099. if (Field->isInvalidDecl()) {
  13100. Invalid = true;
  13101. continue;
  13102. }
  13103. // Check for members of reference type; we can't move those.
  13104. if (Field->getType()->isReferenceType()) {
  13105. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  13106. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  13107. Diag(Field->getLocation(), diag::note_declared_at);
  13108. Invalid = true;
  13109. continue;
  13110. }
  13111. // Check for members of const-qualified, non-class type.
  13112. QualType BaseType = Context.getBaseElementType(Field->getType());
  13113. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  13114. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  13115. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  13116. Diag(Field->getLocation(), diag::note_declared_at);
  13117. Invalid = true;
  13118. continue;
  13119. }
  13120. // Suppress assigning zero-width bitfields.
  13121. if (Field->isZeroLengthBitField(Context))
  13122. continue;
  13123. QualType FieldType = Field->getType().getNonReferenceType();
  13124. if (FieldType->isIncompleteArrayType()) {
  13125. assert(ClassDecl->hasFlexibleArrayMember() &&
  13126. "Incomplete array type is not valid");
  13127. continue;
  13128. }
  13129. // Build references to the field in the object we're copying from and to.
  13130. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  13131. LookupMemberName);
  13132. MemberLookup.addDecl(Field);
  13133. MemberLookup.resolveKind();
  13134. MemberBuilder From(MoveOther, OtherRefType,
  13135. /*IsArrow=*/false, MemberLookup);
  13136. MemberBuilder To(This, getCurrentThisType(),
  13137. /*IsArrow=*/true, MemberLookup);
  13138. assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
  13139. "Member reference with rvalue base must be rvalue except for reference "
  13140. "members, which aren't allowed for move assignment.");
  13141. // Build the move of this field.
  13142. StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
  13143. To, From,
  13144. /*CopyingBaseSubobject=*/false,
  13145. /*Copying=*/false);
  13146. if (Move.isInvalid()) {
  13147. MoveAssignOperator->setInvalidDecl();
  13148. return;
  13149. }
  13150. // Success! Record the copy.
  13151. Statements.push_back(Move.getAs<Stmt>());
  13152. }
  13153. if (!Invalid) {
  13154. // Add a "return *this;"
  13155. ExprResult ThisObj =
  13156. CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  13157. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  13158. if (Return.isInvalid())
  13159. Invalid = true;
  13160. else
  13161. Statements.push_back(Return.getAs<Stmt>());
  13162. }
  13163. if (Invalid) {
  13164. MoveAssignOperator->setInvalidDecl();
  13165. return;
  13166. }
  13167. StmtResult Body;
  13168. {
  13169. CompoundScopeRAII CompoundScope(*this);
  13170. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  13171. /*isStmtExpr=*/false);
  13172. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  13173. }
  13174. MoveAssignOperator->setBody(Body.getAs<Stmt>());
  13175. MoveAssignOperator->markUsed(Context);
  13176. if (ASTMutationListener *L = getASTMutationListener()) {
  13177. L->CompletedImplicitDefinition(MoveAssignOperator);
  13178. }
  13179. }
  13180. CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
  13181. CXXRecordDecl *ClassDecl) {
  13182. // C++ [class.copy]p4:
  13183. // If the class definition does not explicitly declare a copy
  13184. // constructor, one is declared implicitly.
  13185. assert(ClassDecl->needsImplicitCopyConstructor());
  13186. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
  13187. if (DSM.isAlreadyBeingDeclared())
  13188. return nullptr;
  13189. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  13190. QualType ArgType = ClassType;
  13191. ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
  13192. bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
  13193. if (Const)
  13194. ArgType = ArgType.withConst();
  13195. LangAS AS = getDefaultCXXMethodAddrSpace();
  13196. if (AS != LangAS::Default)
  13197. ArgType = Context.getAddrSpaceQualType(ArgType, AS);
  13198. ArgType = Context.getLValueReferenceType(ArgType);
  13199. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  13200. CXXCopyConstructor,
  13201. Const);
  13202. DeclarationName Name
  13203. = Context.DeclarationNames.getCXXConstructorName(
  13204. Context.getCanonicalType(ClassType));
  13205. SourceLocation ClassLoc = ClassDecl->getLocation();
  13206. DeclarationNameInfo NameInfo(Name, ClassLoc);
  13207. // An implicitly-declared copy constructor is an inline public
  13208. // member of its class.
  13209. CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
  13210. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  13211. ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
  13212. /*isInline=*/true,
  13213. /*isImplicitlyDeclared=*/true,
  13214. Constexpr ? ConstexprSpecKind::Constexpr
  13215. : ConstexprSpecKind::Unspecified);
  13216. CopyConstructor->setAccess(AS_public);
  13217. CopyConstructor->setDefaulted();
  13218. setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
  13219. if (getLangOpts().CUDA)
  13220. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
  13221. CopyConstructor,
  13222. /* ConstRHS */ Const,
  13223. /* Diagnose */ false);
  13224. // During template instantiation of special member functions we need a
  13225. // reliable TypeSourceInfo for the parameter types in order to allow functions
  13226. // to be substituted.
  13227. TypeSourceInfo *TSI = nullptr;
  13228. if (inTemplateInstantiation() && ClassDecl->isLambda())
  13229. TSI = Context.getTrivialTypeSourceInfo(ArgType);
  13230. // Add the parameter to the constructor.
  13231. ParmVarDecl *FromParam =
  13232. ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
  13233. /*IdentifierInfo=*/nullptr, ArgType,
  13234. /*TInfo=*/TSI, SC_None, nullptr);
  13235. CopyConstructor->setParams(FromParam);
  13236. CopyConstructor->setTrivial(
  13237. ClassDecl->needsOverloadResolutionForCopyConstructor()
  13238. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
  13239. : ClassDecl->hasTrivialCopyConstructor());
  13240. CopyConstructor->setTrivialForCall(
  13241. ClassDecl->hasAttr<TrivialABIAttr>() ||
  13242. (ClassDecl->needsOverloadResolutionForCopyConstructor()
  13243. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
  13244. TAH_ConsiderTrivialABI)
  13245. : ClassDecl->hasTrivialCopyConstructorForCall()));
  13246. // Note that we have declared this constructor.
  13247. ++getASTContext().NumImplicitCopyConstructorsDeclared;
  13248. Scope *S = getScopeForContext(ClassDecl);
  13249. CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
  13250. if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
  13251. ClassDecl->setImplicitCopyConstructorIsDeleted();
  13252. SetDeclDeleted(CopyConstructor, ClassLoc);
  13253. }
  13254. if (S)
  13255. PushOnScopeChains(CopyConstructor, S, false);
  13256. ClassDecl->addDecl(CopyConstructor);
  13257. return CopyConstructor;
  13258. }
  13259. void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
  13260. CXXConstructorDecl *CopyConstructor) {
  13261. assert((CopyConstructor->isDefaulted() &&
  13262. CopyConstructor->isCopyConstructor() &&
  13263. !CopyConstructor->doesThisDeclarationHaveABody() &&
  13264. !CopyConstructor->isDeleted()) &&
  13265. "DefineImplicitCopyConstructor - call it for implicit copy ctor");
  13266. if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
  13267. return;
  13268. CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
  13269. assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
  13270. SynthesizedFunctionScope Scope(*this, CopyConstructor);
  13271. // The exception specification is needed because we are defining the
  13272. // function.
  13273. ResolveExceptionSpec(CurrentLocation,
  13274. CopyConstructor->getType()->castAs<FunctionProtoType>());
  13275. MarkVTableUsed(CurrentLocation, ClassDecl);
  13276. // Add a context note for diagnostics produced after this point.
  13277. Scope.addContextNote(CurrentLocation);
  13278. // C++11 [class.copy]p7:
  13279. // The [definition of an implicitly declared copy constructor] is
  13280. // deprecated if the class has a user-declared copy assignment operator
  13281. // or a user-declared destructor.
  13282. if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
  13283. diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
  13284. if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
  13285. CopyConstructor->setInvalidDecl();
  13286. } else {
  13287. SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
  13288. ? CopyConstructor->getEndLoc()
  13289. : CopyConstructor->getLocation();
  13290. Sema::CompoundScopeRAII CompoundScope(*this);
  13291. CopyConstructor->setBody(
  13292. ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
  13293. .getAs<Stmt>());
  13294. CopyConstructor->markUsed(Context);
  13295. }
  13296. if (ASTMutationListener *L = getASTMutationListener()) {
  13297. L->CompletedImplicitDefinition(CopyConstructor);
  13298. }
  13299. }
  13300. CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
  13301. CXXRecordDecl *ClassDecl) {
  13302. assert(ClassDecl->needsImplicitMoveConstructor());
  13303. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
  13304. if (DSM.isAlreadyBeingDeclared())
  13305. return nullptr;
  13306. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  13307. QualType ArgType = ClassType;
  13308. ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
  13309. LangAS AS = getDefaultCXXMethodAddrSpace();
  13310. if (AS != LangAS::Default)
  13311. ArgType = Context.getAddrSpaceQualType(ClassType, AS);
  13312. ArgType = Context.getRValueReferenceType(ArgType);
  13313. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  13314. CXXMoveConstructor,
  13315. false);
  13316. DeclarationName Name
  13317. = Context.DeclarationNames.getCXXConstructorName(
  13318. Context.getCanonicalType(ClassType));
  13319. SourceLocation ClassLoc = ClassDecl->getLocation();
  13320. DeclarationNameInfo NameInfo(Name, ClassLoc);
  13321. // C++11 [class.copy]p11:
  13322. // An implicitly-declared copy/move constructor is an inline public
  13323. // member of its class.
  13324. CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
  13325. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  13326. ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
  13327. /*isInline=*/true,
  13328. /*isImplicitlyDeclared=*/true,
  13329. Constexpr ? ConstexprSpecKind::Constexpr
  13330. : ConstexprSpecKind::Unspecified);
  13331. MoveConstructor->setAccess(AS_public);
  13332. MoveConstructor->setDefaulted();
  13333. setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
  13334. if (getLangOpts().CUDA)
  13335. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
  13336. MoveConstructor,
  13337. /* ConstRHS */ false,
  13338. /* Diagnose */ false);
  13339. // Add the parameter to the constructor.
  13340. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
  13341. ClassLoc, ClassLoc,
  13342. /*IdentifierInfo=*/nullptr,
  13343. ArgType, /*TInfo=*/nullptr,
  13344. SC_None, nullptr);
  13345. MoveConstructor->setParams(FromParam);
  13346. MoveConstructor->setTrivial(
  13347. ClassDecl->needsOverloadResolutionForMoveConstructor()
  13348. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
  13349. : ClassDecl->hasTrivialMoveConstructor());
  13350. MoveConstructor->setTrivialForCall(
  13351. ClassDecl->hasAttr<TrivialABIAttr>() ||
  13352. (ClassDecl->needsOverloadResolutionForMoveConstructor()
  13353. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
  13354. TAH_ConsiderTrivialABI)
  13355. : ClassDecl->hasTrivialMoveConstructorForCall()));
  13356. // Note that we have declared this constructor.
  13357. ++getASTContext().NumImplicitMoveConstructorsDeclared;
  13358. Scope *S = getScopeForContext(ClassDecl);
  13359. CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
  13360. if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
  13361. ClassDecl->setImplicitMoveConstructorIsDeleted();
  13362. SetDeclDeleted(MoveConstructor, ClassLoc);
  13363. }
  13364. if (S)
  13365. PushOnScopeChains(MoveConstructor, S, false);
  13366. ClassDecl->addDecl(MoveConstructor);
  13367. return MoveConstructor;
  13368. }
  13369. void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
  13370. CXXConstructorDecl *MoveConstructor) {
  13371. assert((MoveConstructor->isDefaulted() &&
  13372. MoveConstructor->isMoveConstructor() &&
  13373. !MoveConstructor->doesThisDeclarationHaveABody() &&
  13374. !MoveConstructor->isDeleted()) &&
  13375. "DefineImplicitMoveConstructor - call it for implicit move ctor");
  13376. if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
  13377. return;
  13378. CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
  13379. assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
  13380. SynthesizedFunctionScope Scope(*this, MoveConstructor);
  13381. // The exception specification is needed because we are defining the
  13382. // function.
  13383. ResolveExceptionSpec(CurrentLocation,
  13384. MoveConstructor->getType()->castAs<FunctionProtoType>());
  13385. MarkVTableUsed(CurrentLocation, ClassDecl);
  13386. // Add a context note for diagnostics produced after this point.
  13387. Scope.addContextNote(CurrentLocation);
  13388. if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
  13389. MoveConstructor->setInvalidDecl();
  13390. } else {
  13391. SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
  13392. ? MoveConstructor->getEndLoc()
  13393. : MoveConstructor->getLocation();
  13394. Sema::CompoundScopeRAII CompoundScope(*this);
  13395. MoveConstructor->setBody(
  13396. ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
  13397. .getAs<Stmt>());
  13398. MoveConstructor->markUsed(Context);
  13399. }
  13400. if (ASTMutationListener *L = getASTMutationListener()) {
  13401. L->CompletedImplicitDefinition(MoveConstructor);
  13402. }
  13403. }
  13404. bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
  13405. return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
  13406. }
  13407. void Sema::DefineImplicitLambdaToFunctionPointerConversion(
  13408. SourceLocation CurrentLocation,
  13409. CXXConversionDecl *Conv) {
  13410. SynthesizedFunctionScope Scope(*this, Conv);
  13411. assert(!Conv->getReturnType()->isUndeducedType());
  13412. QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
  13413. CallingConv CC =
  13414. ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
  13415. CXXRecordDecl *Lambda = Conv->getParent();
  13416. FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
  13417. FunctionDecl *Invoker =
  13418. CallOp->isStatic() ? CallOp : Lambda->getLambdaStaticInvoker(CC);
  13419. if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
  13420. CallOp = InstantiateFunctionDeclaration(
  13421. CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  13422. if (!CallOp)
  13423. return;
  13424. if (CallOp != Invoker) {
  13425. Invoker = InstantiateFunctionDeclaration(
  13426. Invoker->getDescribedFunctionTemplate(), TemplateArgs,
  13427. CurrentLocation);
  13428. if (!Invoker)
  13429. return;
  13430. }
  13431. }
  13432. if (CallOp->isInvalidDecl())
  13433. return;
  13434. // Mark the call operator referenced (and add to pending instantiations
  13435. // if necessary).
  13436. // For both the conversion and static-invoker template specializations
  13437. // we construct their body's in this function, so no need to add them
  13438. // to the PendingInstantiations.
  13439. MarkFunctionReferenced(CurrentLocation, CallOp);
  13440. if (Invoker != CallOp) {
  13441. // Fill in the __invoke function with a dummy implementation. IR generation
  13442. // will fill in the actual details. Update its type in case it contained
  13443. // an 'auto'.
  13444. Invoker->markUsed(Context);
  13445. Invoker->setReferenced();
  13446. Invoker->setType(Conv->getReturnType()->getPointeeType());
  13447. Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
  13448. }
  13449. // Construct the body of the conversion function { return __invoke; }.
  13450. Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
  13451. Conv->getLocation());
  13452. assert(FunctionRef && "Can't refer to __invoke function?");
  13453. Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
  13454. Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
  13455. Conv->getLocation(), Conv->getLocation()));
  13456. Conv->markUsed(Context);
  13457. Conv->setReferenced();
  13458. if (ASTMutationListener *L = getASTMutationListener()) {
  13459. L->CompletedImplicitDefinition(Conv);
  13460. if (Invoker != CallOp)
  13461. L->CompletedImplicitDefinition(Invoker);
  13462. }
  13463. }
  13464. void Sema::DefineImplicitLambdaToBlockPointerConversion(
  13465. SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
  13466. assert(!Conv->getParent()->isGenericLambda());
  13467. SynthesizedFunctionScope Scope(*this, Conv);
  13468. // Copy-initialize the lambda object as needed to capture it.
  13469. Expr *This = ActOnCXXThis(CurrentLocation).get();
  13470. Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
  13471. ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
  13472. Conv->getLocation(),
  13473. Conv, DerefThis);
  13474. // If we're not under ARC, make sure we still get the _Block_copy/autorelease
  13475. // behavior. Note that only the general conversion function does this
  13476. // (since it's unusable otherwise); in the case where we inline the
  13477. // block literal, it has block literal lifetime semantics.
  13478. if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
  13479. BuildBlock = ImplicitCastExpr::Create(
  13480. Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
  13481. BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
  13482. if (BuildBlock.isInvalid()) {
  13483. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  13484. Conv->setInvalidDecl();
  13485. return;
  13486. }
  13487. // Create the return statement that returns the block from the conversion
  13488. // function.
  13489. StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
  13490. if (Return.isInvalid()) {
  13491. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  13492. Conv->setInvalidDecl();
  13493. return;
  13494. }
  13495. // Set the body of the conversion function.
  13496. Stmt *ReturnS = Return.get();
  13497. Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
  13498. Conv->getLocation(), Conv->getLocation()));
  13499. Conv->markUsed(Context);
  13500. // We're done; notify the mutation listener, if any.
  13501. if (ASTMutationListener *L = getASTMutationListener()) {
  13502. L->CompletedImplicitDefinition(Conv);
  13503. }
  13504. }
  13505. /// Determine whether the given list arguments contains exactly one
  13506. /// "real" (non-default) argument.
  13507. static bool hasOneRealArgument(MultiExprArg Args) {
  13508. switch (Args.size()) {
  13509. case 0:
  13510. return false;
  13511. default:
  13512. if (!Args[1]->isDefaultArgument())
  13513. return false;
  13514. [[fallthrough]];
  13515. case 1:
  13516. return !Args[0]->isDefaultArgument();
  13517. }
  13518. return false;
  13519. }
  13520. ExprResult
  13521. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  13522. NamedDecl *FoundDecl,
  13523. CXXConstructorDecl *Constructor,
  13524. MultiExprArg ExprArgs,
  13525. bool HadMultipleCandidates,
  13526. bool IsListInitialization,
  13527. bool IsStdInitListInitialization,
  13528. bool RequiresZeroInit,
  13529. unsigned ConstructKind,
  13530. SourceRange ParenRange) {
  13531. bool Elidable = false;
  13532. // C++0x [class.copy]p34:
  13533. // When certain criteria are met, an implementation is allowed to
  13534. // omit the copy/move construction of a class object, even if the
  13535. // copy/move constructor and/or destructor for the object have
  13536. // side effects. [...]
  13537. // - when a temporary class object that has not been bound to a
  13538. // reference (12.2) would be copied/moved to a class object
  13539. // with the same cv-unqualified type, the copy/move operation
  13540. // can be omitted by constructing the temporary object
  13541. // directly into the target of the omitted copy/move
  13542. if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
  13543. // FIXME: Converting constructors should also be accepted.
  13544. // But to fix this, the logic that digs down into a CXXConstructExpr
  13545. // to find the source object needs to handle it.
  13546. // Right now it assumes the source object is passed directly as the
  13547. // first argument.
  13548. Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
  13549. Expr *SubExpr = ExprArgs[0];
  13550. // FIXME: Per above, this is also incorrect if we want to accept
  13551. // converting constructors, as isTemporaryObject will
  13552. // reject temporaries with different type from the
  13553. // CXXRecord itself.
  13554. Elidable = SubExpr->isTemporaryObject(
  13555. Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  13556. }
  13557. return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
  13558. FoundDecl, Constructor,
  13559. Elidable, ExprArgs, HadMultipleCandidates,
  13560. IsListInitialization,
  13561. IsStdInitListInitialization, RequiresZeroInit,
  13562. ConstructKind, ParenRange);
  13563. }
  13564. ExprResult
  13565. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  13566. NamedDecl *FoundDecl,
  13567. CXXConstructorDecl *Constructor,
  13568. bool Elidable,
  13569. MultiExprArg ExprArgs,
  13570. bool HadMultipleCandidates,
  13571. bool IsListInitialization,
  13572. bool IsStdInitListInitialization,
  13573. bool RequiresZeroInit,
  13574. unsigned ConstructKind,
  13575. SourceRange ParenRange) {
  13576. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
  13577. Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
  13578. // The only way to get here is if we did overlaod resolution to find the
  13579. // shadow decl, so we don't need to worry about re-checking the trailing
  13580. // requires clause.
  13581. if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
  13582. return ExprError();
  13583. }
  13584. return BuildCXXConstructExpr(
  13585. ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
  13586. HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
  13587. RequiresZeroInit, ConstructKind, ParenRange);
  13588. }
  13589. /// BuildCXXConstructExpr - Creates a complete call to a constructor,
  13590. /// including handling of its default argument expressions.
  13591. ExprResult
  13592. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  13593. CXXConstructorDecl *Constructor,
  13594. bool Elidable,
  13595. MultiExprArg ExprArgs,
  13596. bool HadMultipleCandidates,
  13597. bool IsListInitialization,
  13598. bool IsStdInitListInitialization,
  13599. bool RequiresZeroInit,
  13600. unsigned ConstructKind,
  13601. SourceRange ParenRange) {
  13602. assert(declaresSameEntity(
  13603. Constructor->getParent(),
  13604. DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
  13605. "given constructor for wrong type");
  13606. MarkFunctionReferenced(ConstructLoc, Constructor);
  13607. if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
  13608. return ExprError();
  13609. if (getLangOpts().SYCLIsDevice &&
  13610. !checkSYCLDeviceFunction(ConstructLoc, Constructor))
  13611. return ExprError();
  13612. return CheckForImmediateInvocation(
  13613. CXXConstructExpr::Create(
  13614. Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
  13615. HadMultipleCandidates, IsListInitialization,
  13616. IsStdInitListInitialization, RequiresZeroInit,
  13617. static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
  13618. ParenRange),
  13619. Constructor);
  13620. }
  13621. void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
  13622. if (VD->isInvalidDecl()) return;
  13623. // If initializing the variable failed, don't also diagnose problems with
  13624. // the destructor, they're likely related.
  13625. if (VD->getInit() && VD->getInit()->containsErrors())
  13626. return;
  13627. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
  13628. if (ClassDecl->isInvalidDecl()) return;
  13629. if (ClassDecl->hasIrrelevantDestructor()) return;
  13630. if (ClassDecl->isDependentContext()) return;
  13631. if (VD->isNoDestroy(getASTContext()))
  13632. return;
  13633. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  13634. // If this is an array, we'll require the destructor during initialization, so
  13635. // we can skip over this. We still want to emit exit-time destructor warnings
  13636. // though.
  13637. if (!VD->getType()->isArrayType()) {
  13638. MarkFunctionReferenced(VD->getLocation(), Destructor);
  13639. CheckDestructorAccess(VD->getLocation(), Destructor,
  13640. PDiag(diag::err_access_dtor_var)
  13641. << VD->getDeclName() << VD->getType());
  13642. DiagnoseUseOfDecl(Destructor, VD->getLocation());
  13643. }
  13644. if (Destructor->isTrivial()) return;
  13645. // If the destructor is constexpr, check whether the variable has constant
  13646. // destruction now.
  13647. if (Destructor->isConstexpr()) {
  13648. bool HasConstantInit = false;
  13649. if (VD->getInit() && !VD->getInit()->isValueDependent())
  13650. HasConstantInit = VD->evaluateValue();
  13651. SmallVector<PartialDiagnosticAt, 8> Notes;
  13652. if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
  13653. HasConstantInit) {
  13654. Diag(VD->getLocation(),
  13655. diag::err_constexpr_var_requires_const_destruction) << VD;
  13656. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  13657. Diag(Notes[I].first, Notes[I].second);
  13658. }
  13659. }
  13660. if (!VD->hasGlobalStorage()) return;
  13661. // Emit warning for non-trivial dtor in global scope (a real global,
  13662. // class-static, function-static).
  13663. Diag(VD->getLocation(), diag::warn_exit_time_destructor);
  13664. // TODO: this should be re-enabled for static locals by !CXAAtExit
  13665. if (!VD->isStaticLocal())
  13666. Diag(VD->getLocation(), diag::warn_global_destructor);
  13667. }
  13668. /// Given a constructor and the set of arguments provided for the
  13669. /// constructor, convert the arguments and add any required default arguments
  13670. /// to form a proper call to this constructor.
  13671. ///
  13672. /// \returns true if an error occurred, false otherwise.
  13673. bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
  13674. QualType DeclInitType, MultiExprArg ArgsPtr,
  13675. SourceLocation Loc,
  13676. SmallVectorImpl<Expr *> &ConvertedArgs,
  13677. bool AllowExplicit,
  13678. bool IsListInitialization) {
  13679. // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
  13680. unsigned NumArgs = ArgsPtr.size();
  13681. Expr **Args = ArgsPtr.data();
  13682. const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
  13683. unsigned NumParams = Proto->getNumParams();
  13684. // If too few arguments are available, we'll fill in the rest with defaults.
  13685. if (NumArgs < NumParams)
  13686. ConvertedArgs.reserve(NumParams);
  13687. else
  13688. ConvertedArgs.reserve(NumArgs);
  13689. VariadicCallType CallType =
  13690. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  13691. SmallVector<Expr *, 8> AllArgs;
  13692. bool Invalid = GatherArgumentsForCall(
  13693. Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
  13694. CallType, AllowExplicit, IsListInitialization);
  13695. ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
  13696. DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
  13697. CheckConstructorCall(Constructor, DeclInitType,
  13698. llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
  13699. Loc);
  13700. return Invalid;
  13701. }
  13702. static inline bool
  13703. CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
  13704. const FunctionDecl *FnDecl) {
  13705. const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
  13706. if (isa<NamespaceDecl>(DC)) {
  13707. return SemaRef.Diag(FnDecl->getLocation(),
  13708. diag::err_operator_new_delete_declared_in_namespace)
  13709. << FnDecl->getDeclName();
  13710. }
  13711. if (isa<TranslationUnitDecl>(DC) &&
  13712. FnDecl->getStorageClass() == SC_Static) {
  13713. return SemaRef.Diag(FnDecl->getLocation(),
  13714. diag::err_operator_new_delete_declared_static)
  13715. << FnDecl->getDeclName();
  13716. }
  13717. return false;
  13718. }
  13719. static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
  13720. const PointerType *PtrTy) {
  13721. auto &Ctx = SemaRef.Context;
  13722. Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
  13723. PtrQuals.removeAddressSpace();
  13724. return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
  13725. PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
  13726. }
  13727. static inline bool
  13728. CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
  13729. CanQualType ExpectedResultType,
  13730. CanQualType ExpectedFirstParamType,
  13731. unsigned DependentParamTypeDiag,
  13732. unsigned InvalidParamTypeDiag) {
  13733. QualType ResultType =
  13734. FnDecl->getType()->castAs<FunctionType>()->getReturnType();
  13735. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  13736. // The operator is valid on any address space for OpenCL.
  13737. // Drop address space from actual and expected result types.
  13738. if (const auto *PtrTy = ResultType->getAs<PointerType>())
  13739. ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  13740. if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
  13741. ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
  13742. }
  13743. // Check that the result type is what we expect.
  13744. if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
  13745. // Reject even if the type is dependent; an operator delete function is
  13746. // required to have a non-dependent result type.
  13747. return SemaRef.Diag(
  13748. FnDecl->getLocation(),
  13749. ResultType->isDependentType()
  13750. ? diag::err_operator_new_delete_dependent_result_type
  13751. : diag::err_operator_new_delete_invalid_result_type)
  13752. << FnDecl->getDeclName() << ExpectedResultType;
  13753. }
  13754. // A function template must have at least 2 parameters.
  13755. if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
  13756. return SemaRef.Diag(FnDecl->getLocation(),
  13757. diag::err_operator_new_delete_template_too_few_parameters)
  13758. << FnDecl->getDeclName();
  13759. // The function decl must have at least 1 parameter.
  13760. if (FnDecl->getNumParams() == 0)
  13761. return SemaRef.Diag(FnDecl->getLocation(),
  13762. diag::err_operator_new_delete_too_few_parameters)
  13763. << FnDecl->getDeclName();
  13764. QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
  13765. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  13766. // The operator is valid on any address space for OpenCL.
  13767. // Drop address space from actual and expected first parameter types.
  13768. if (const auto *PtrTy =
  13769. FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
  13770. FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  13771. if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
  13772. ExpectedFirstParamType =
  13773. RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
  13774. }
  13775. // Check that the first parameter type is what we expect.
  13776. if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
  13777. ExpectedFirstParamType) {
  13778. // The first parameter type is not allowed to be dependent. As a tentative
  13779. // DR resolution, we allow a dependent parameter type if it is the right
  13780. // type anyway, to allow destroying operator delete in class templates.
  13781. return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
  13782. ? DependentParamTypeDiag
  13783. : InvalidParamTypeDiag)
  13784. << FnDecl->getDeclName() << ExpectedFirstParamType;
  13785. }
  13786. return false;
  13787. }
  13788. static bool
  13789. CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
  13790. // C++ [basic.stc.dynamic.allocation]p1:
  13791. // A program is ill-formed if an allocation function is declared in a
  13792. // namespace scope other than global scope or declared static in global
  13793. // scope.
  13794. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  13795. return true;
  13796. CanQualType SizeTy =
  13797. SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
  13798. // C++ [basic.stc.dynamic.allocation]p1:
  13799. // The return type shall be void*. The first parameter shall have type
  13800. // std::size_t.
  13801. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
  13802. SizeTy,
  13803. diag::err_operator_new_dependent_param_type,
  13804. diag::err_operator_new_param_type))
  13805. return true;
  13806. // C++ [basic.stc.dynamic.allocation]p1:
  13807. // The first parameter shall not have an associated default argument.
  13808. if (FnDecl->getParamDecl(0)->hasDefaultArg())
  13809. return SemaRef.Diag(FnDecl->getLocation(),
  13810. diag::err_operator_new_default_arg)
  13811. << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
  13812. return false;
  13813. }
  13814. static bool
  13815. CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
  13816. // C++ [basic.stc.dynamic.deallocation]p1:
  13817. // A program is ill-formed if deallocation functions are declared in a
  13818. // namespace scope other than global scope or declared static in global
  13819. // scope.
  13820. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  13821. return true;
  13822. auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
  13823. // C++ P0722:
  13824. // Within a class C, the first parameter of a destroying operator delete
  13825. // shall be of type C *. The first parameter of any other deallocation
  13826. // function shall be of type void *.
  13827. CanQualType ExpectedFirstParamType =
  13828. MD && MD->isDestroyingOperatorDelete()
  13829. ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
  13830. SemaRef.Context.getRecordType(MD->getParent())))
  13831. : SemaRef.Context.VoidPtrTy;
  13832. // C++ [basic.stc.dynamic.deallocation]p2:
  13833. // Each deallocation function shall return void
  13834. if (CheckOperatorNewDeleteTypes(
  13835. SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
  13836. diag::err_operator_delete_dependent_param_type,
  13837. diag::err_operator_delete_param_type))
  13838. return true;
  13839. // C++ P0722:
  13840. // A destroying operator delete shall be a usual deallocation function.
  13841. if (MD && !MD->getParent()->isDependentContext() &&
  13842. MD->isDestroyingOperatorDelete() &&
  13843. !SemaRef.isUsualDeallocationFunction(MD)) {
  13844. SemaRef.Diag(MD->getLocation(),
  13845. diag::err_destroying_operator_delete_not_usual);
  13846. return true;
  13847. }
  13848. return false;
  13849. }
  13850. /// CheckOverloadedOperatorDeclaration - Check whether the declaration
  13851. /// of this overloaded operator is well-formed. If so, returns false;
  13852. /// otherwise, emits appropriate diagnostics and returns true.
  13853. bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
  13854. assert(FnDecl && FnDecl->isOverloadedOperator() &&
  13855. "Expected an overloaded operator declaration");
  13856. OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
  13857. // C++ [over.oper]p5:
  13858. // The allocation and deallocation functions, operator new,
  13859. // operator new[], operator delete and operator delete[], are
  13860. // described completely in 3.7.3. The attributes and restrictions
  13861. // found in the rest of this subclause do not apply to them unless
  13862. // explicitly stated in 3.7.3.
  13863. if (Op == OO_Delete || Op == OO_Array_Delete)
  13864. return CheckOperatorDeleteDeclaration(*this, FnDecl);
  13865. if (Op == OO_New || Op == OO_Array_New)
  13866. return CheckOperatorNewDeclaration(*this, FnDecl);
  13867. // C++ [over.oper]p7:
  13868. // An operator function shall either be a member function or
  13869. // be a non-member function and have at least one parameter
  13870. // whose type is a class, a reference to a class, an enumeration,
  13871. // or a reference to an enumeration.
  13872. // Note: Before C++23, a member function could not be static. The only member
  13873. // function allowed to be static is the call operator function.
  13874. if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
  13875. if (MethodDecl->isStatic()) {
  13876. if (Op == OO_Call || Op == OO_Subscript)
  13877. Diag(FnDecl->getLocation(),
  13878. (LangOpts.CPlusPlus2b
  13879. ? diag::warn_cxx20_compat_operator_overload_static
  13880. : diag::ext_operator_overload_static))
  13881. << FnDecl;
  13882. else
  13883. return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
  13884. << FnDecl;
  13885. }
  13886. } else {
  13887. bool ClassOrEnumParam = false;
  13888. for (auto *Param : FnDecl->parameters()) {
  13889. QualType ParamType = Param->getType().getNonReferenceType();
  13890. if (ParamType->isDependentType() || ParamType->isRecordType() ||
  13891. ParamType->isEnumeralType()) {
  13892. ClassOrEnumParam = true;
  13893. break;
  13894. }
  13895. }
  13896. if (!ClassOrEnumParam)
  13897. return Diag(FnDecl->getLocation(),
  13898. diag::err_operator_overload_needs_class_or_enum)
  13899. << FnDecl->getDeclName();
  13900. }
  13901. // C++ [over.oper]p8:
  13902. // An operator function cannot have default arguments (8.3.6),
  13903. // except where explicitly stated below.
  13904. //
  13905. // Only the function-call operator (C++ [over.call]p1) and the subscript
  13906. // operator (CWG2507) allow default arguments.
  13907. if (Op != OO_Call) {
  13908. ParmVarDecl *FirstDefaultedParam = nullptr;
  13909. for (auto *Param : FnDecl->parameters()) {
  13910. if (Param->hasDefaultArg()) {
  13911. FirstDefaultedParam = Param;
  13912. break;
  13913. }
  13914. }
  13915. if (FirstDefaultedParam) {
  13916. if (Op == OO_Subscript) {
  13917. Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
  13918. ? diag::ext_subscript_overload
  13919. : diag::error_subscript_overload)
  13920. << FnDecl->getDeclName() << 1
  13921. << FirstDefaultedParam->getDefaultArgRange();
  13922. } else {
  13923. return Diag(FirstDefaultedParam->getLocation(),
  13924. diag::err_operator_overload_default_arg)
  13925. << FnDecl->getDeclName()
  13926. << FirstDefaultedParam->getDefaultArgRange();
  13927. }
  13928. }
  13929. }
  13930. static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
  13931. { false, false, false }
  13932. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  13933. , { Unary, Binary, MemberOnly }
  13934. #include "clang/Basic/OperatorKinds.def"
  13935. };
  13936. bool CanBeUnaryOperator = OperatorUses[Op][0];
  13937. bool CanBeBinaryOperator = OperatorUses[Op][1];
  13938. bool MustBeMemberOperator = OperatorUses[Op][2];
  13939. // C++ [over.oper]p8:
  13940. // [...] Operator functions cannot have more or fewer parameters
  13941. // than the number required for the corresponding operator, as
  13942. // described in the rest of this subclause.
  13943. unsigned NumParams = FnDecl->getNumParams()
  13944. + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
  13945. if (Op != OO_Call && Op != OO_Subscript &&
  13946. ((NumParams == 1 && !CanBeUnaryOperator) ||
  13947. (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
  13948. (NumParams > 2))) {
  13949. // We have the wrong number of parameters.
  13950. unsigned ErrorKind;
  13951. if (CanBeUnaryOperator && CanBeBinaryOperator) {
  13952. ErrorKind = 2; // 2 -> unary or binary.
  13953. } else if (CanBeUnaryOperator) {
  13954. ErrorKind = 0; // 0 -> unary
  13955. } else {
  13956. assert(CanBeBinaryOperator &&
  13957. "All non-call overloaded operators are unary or binary!");
  13958. ErrorKind = 1; // 1 -> binary
  13959. }
  13960. return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
  13961. << FnDecl->getDeclName() << NumParams << ErrorKind;
  13962. }
  13963. if (Op == OO_Subscript && NumParams != 2) {
  13964. Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
  13965. ? diag::ext_subscript_overload
  13966. : diag::error_subscript_overload)
  13967. << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
  13968. }
  13969. // Overloaded operators other than operator() and operator[] cannot be
  13970. // variadic.
  13971. if (Op != OO_Call &&
  13972. FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
  13973. return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
  13974. << FnDecl->getDeclName();
  13975. }
  13976. // Some operators must be member functions.
  13977. if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
  13978. return Diag(FnDecl->getLocation(),
  13979. diag::err_operator_overload_must_be_member)
  13980. << FnDecl->getDeclName();
  13981. }
  13982. // C++ [over.inc]p1:
  13983. // The user-defined function called operator++ implements the
  13984. // prefix and postfix ++ operator. If this function is a member
  13985. // function with no parameters, or a non-member function with one
  13986. // parameter of class or enumeration type, it defines the prefix
  13987. // increment operator ++ for objects of that type. If the function
  13988. // is a member function with one parameter (which shall be of type
  13989. // int) or a non-member function with two parameters (the second
  13990. // of which shall be of type int), it defines the postfix
  13991. // increment operator ++ for objects of that type.
  13992. if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
  13993. ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
  13994. QualType ParamType = LastParam->getType();
  13995. if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
  13996. !ParamType->isDependentType())
  13997. return Diag(LastParam->getLocation(),
  13998. diag::err_operator_overload_post_incdec_must_be_int)
  13999. << LastParam->getType() << (Op == OO_MinusMinus);
  14000. }
  14001. return false;
  14002. }
  14003. static bool
  14004. checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
  14005. FunctionTemplateDecl *TpDecl) {
  14006. TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
  14007. // Must have one or two template parameters.
  14008. if (TemplateParams->size() == 1) {
  14009. NonTypeTemplateParmDecl *PmDecl =
  14010. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
  14011. // The template parameter must be a char parameter pack.
  14012. if (PmDecl && PmDecl->isTemplateParameterPack() &&
  14013. SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
  14014. return false;
  14015. // C++20 [over.literal]p5:
  14016. // A string literal operator template is a literal operator template
  14017. // whose template-parameter-list comprises a single non-type
  14018. // template-parameter of class type.
  14019. //
  14020. // As a DR resolution, we also allow placeholders for deduced class
  14021. // template specializations.
  14022. if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
  14023. !PmDecl->isTemplateParameterPack() &&
  14024. (PmDecl->getType()->isRecordType() ||
  14025. PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
  14026. return false;
  14027. } else if (TemplateParams->size() == 2) {
  14028. TemplateTypeParmDecl *PmType =
  14029. dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
  14030. NonTypeTemplateParmDecl *PmArgs =
  14031. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
  14032. // The second template parameter must be a parameter pack with the
  14033. // first template parameter as its type.
  14034. if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
  14035. PmArgs->isTemplateParameterPack()) {
  14036. const TemplateTypeParmType *TArgs =
  14037. PmArgs->getType()->getAs<TemplateTypeParmType>();
  14038. if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
  14039. TArgs->getIndex() == PmType->getIndex()) {
  14040. if (!SemaRef.inTemplateInstantiation())
  14041. SemaRef.Diag(TpDecl->getLocation(),
  14042. diag::ext_string_literal_operator_template);
  14043. return false;
  14044. }
  14045. }
  14046. }
  14047. SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
  14048. diag::err_literal_operator_template)
  14049. << TpDecl->getTemplateParameters()->getSourceRange();
  14050. return true;
  14051. }
  14052. /// CheckLiteralOperatorDeclaration - Check whether the declaration
  14053. /// of this literal operator function is well-formed. If so, returns
  14054. /// false; otherwise, emits appropriate diagnostics and returns true.
  14055. bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
  14056. if (isa<CXXMethodDecl>(FnDecl)) {
  14057. Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
  14058. << FnDecl->getDeclName();
  14059. return true;
  14060. }
  14061. if (FnDecl->isExternC()) {
  14062. Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
  14063. if (const LinkageSpecDecl *LSD =
  14064. FnDecl->getDeclContext()->getExternCContext())
  14065. Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
  14066. return true;
  14067. }
  14068. // This might be the definition of a literal operator template.
  14069. FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
  14070. // This might be a specialization of a literal operator template.
  14071. if (!TpDecl)
  14072. TpDecl = FnDecl->getPrimaryTemplate();
  14073. // template <char...> type operator "" name() and
  14074. // template <class T, T...> type operator "" name() are the only valid
  14075. // template signatures, and the only valid signatures with no parameters.
  14076. //
  14077. // C++20 also allows template <SomeClass T> type operator "" name().
  14078. if (TpDecl) {
  14079. if (FnDecl->param_size() != 0) {
  14080. Diag(FnDecl->getLocation(),
  14081. diag::err_literal_operator_template_with_params);
  14082. return true;
  14083. }
  14084. if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
  14085. return true;
  14086. } else if (FnDecl->param_size() == 1) {
  14087. const ParmVarDecl *Param = FnDecl->getParamDecl(0);
  14088. QualType ParamType = Param->getType().getUnqualifiedType();
  14089. // Only unsigned long long int, long double, any character type, and const
  14090. // char * are allowed as the only parameters.
  14091. if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
  14092. ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
  14093. Context.hasSameType(ParamType, Context.CharTy) ||
  14094. Context.hasSameType(ParamType, Context.WideCharTy) ||
  14095. Context.hasSameType(ParamType, Context.Char8Ty) ||
  14096. Context.hasSameType(ParamType, Context.Char16Ty) ||
  14097. Context.hasSameType(ParamType, Context.Char32Ty)) {
  14098. } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
  14099. QualType InnerType = Ptr->getPointeeType();
  14100. // Pointer parameter must be a const char *.
  14101. if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
  14102. Context.CharTy) &&
  14103. InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
  14104. Diag(Param->getSourceRange().getBegin(),
  14105. diag::err_literal_operator_param)
  14106. << ParamType << "'const char *'" << Param->getSourceRange();
  14107. return true;
  14108. }
  14109. } else if (ParamType->isRealFloatingType()) {
  14110. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  14111. << ParamType << Context.LongDoubleTy << Param->getSourceRange();
  14112. return true;
  14113. } else if (ParamType->isIntegerType()) {
  14114. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  14115. << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
  14116. return true;
  14117. } else {
  14118. Diag(Param->getSourceRange().getBegin(),
  14119. diag::err_literal_operator_invalid_param)
  14120. << ParamType << Param->getSourceRange();
  14121. return true;
  14122. }
  14123. } else if (FnDecl->param_size() == 2) {
  14124. FunctionDecl::param_iterator Param = FnDecl->param_begin();
  14125. // First, verify that the first parameter is correct.
  14126. QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
  14127. // Two parameter function must have a pointer to const as a
  14128. // first parameter; let's strip those qualifiers.
  14129. const PointerType *PT = FirstParamType->getAs<PointerType>();
  14130. if (!PT) {
  14131. Diag((*Param)->getSourceRange().getBegin(),
  14132. diag::err_literal_operator_param)
  14133. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  14134. return true;
  14135. }
  14136. QualType PointeeType = PT->getPointeeType();
  14137. // First parameter must be const
  14138. if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
  14139. Diag((*Param)->getSourceRange().getBegin(),
  14140. diag::err_literal_operator_param)
  14141. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  14142. return true;
  14143. }
  14144. QualType InnerType = PointeeType.getUnqualifiedType();
  14145. // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
  14146. // const char32_t* are allowed as the first parameter to a two-parameter
  14147. // function
  14148. if (!(Context.hasSameType(InnerType, Context.CharTy) ||
  14149. Context.hasSameType(InnerType, Context.WideCharTy) ||
  14150. Context.hasSameType(InnerType, Context.Char8Ty) ||
  14151. Context.hasSameType(InnerType, Context.Char16Ty) ||
  14152. Context.hasSameType(InnerType, Context.Char32Ty))) {
  14153. Diag((*Param)->getSourceRange().getBegin(),
  14154. diag::err_literal_operator_param)
  14155. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  14156. return true;
  14157. }
  14158. // Move on to the second and final parameter.
  14159. ++Param;
  14160. // The second parameter must be a std::size_t.
  14161. QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
  14162. if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
  14163. Diag((*Param)->getSourceRange().getBegin(),
  14164. diag::err_literal_operator_param)
  14165. << SecondParamType << Context.getSizeType()
  14166. << (*Param)->getSourceRange();
  14167. return true;
  14168. }
  14169. } else {
  14170. Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
  14171. return true;
  14172. }
  14173. // Parameters are good.
  14174. // A parameter-declaration-clause containing a default argument is not
  14175. // equivalent to any of the permitted forms.
  14176. for (auto *Param : FnDecl->parameters()) {
  14177. if (Param->hasDefaultArg()) {
  14178. Diag(Param->getDefaultArgRange().getBegin(),
  14179. diag::err_literal_operator_default_argument)
  14180. << Param->getDefaultArgRange();
  14181. break;
  14182. }
  14183. }
  14184. StringRef LiteralName
  14185. = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
  14186. if (LiteralName[0] != '_' &&
  14187. !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
  14188. // C++11 [usrlit.suffix]p1:
  14189. // Literal suffix identifiers that do not start with an underscore
  14190. // are reserved for future standardization.
  14191. Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
  14192. << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
  14193. }
  14194. return false;
  14195. }
  14196. /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
  14197. /// linkage specification, including the language and (if present)
  14198. /// the '{'. ExternLoc is the location of the 'extern', Lang is the
  14199. /// language string literal. LBraceLoc, if valid, provides the location of
  14200. /// the '{' brace. Otherwise, this linkage specification does not
  14201. /// have any braces.
  14202. Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
  14203. Expr *LangStr,
  14204. SourceLocation LBraceLoc) {
  14205. StringLiteral *Lit = cast<StringLiteral>(LangStr);
  14206. if (!Lit->isOrdinary()) {
  14207. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
  14208. << LangStr->getSourceRange();
  14209. return nullptr;
  14210. }
  14211. StringRef Lang = Lit->getString();
  14212. LinkageSpecDecl::LanguageIDs Language;
  14213. if (Lang == "C")
  14214. Language = LinkageSpecDecl::lang_c;
  14215. else if (Lang == "C++")
  14216. Language = LinkageSpecDecl::lang_cxx;
  14217. else {
  14218. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
  14219. << LangStr->getSourceRange();
  14220. return nullptr;
  14221. }
  14222. // FIXME: Add all the various semantics of linkage specifications
  14223. LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
  14224. LangStr->getExprLoc(), Language,
  14225. LBraceLoc.isValid());
  14226. /// C++ [module.unit]p7.2.3
  14227. /// - Otherwise, if the declaration
  14228. /// - ...
  14229. /// - ...
  14230. /// - appears within a linkage-specification,
  14231. /// it is attached to the global module.
  14232. ///
  14233. /// If the declaration is already in global module fragment, we don't
  14234. /// need to attach it again.
  14235. if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
  14236. Module *GlobalModule =
  14237. PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
  14238. /// According to [module.reach]p3.2,
  14239. /// The declaration in global module fragment is reachable if it is not
  14240. /// discarded. And the discarded declaration should be deleted. So it
  14241. /// doesn't matter mark the declaration in global module fragment as
  14242. /// reachable here.
  14243. D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
  14244. D->setLocalOwningModule(GlobalModule);
  14245. }
  14246. CurContext->addDecl(D);
  14247. PushDeclContext(S, D);
  14248. return D;
  14249. }
  14250. /// ActOnFinishLinkageSpecification - Complete the definition of
  14251. /// the C++ linkage specification LinkageSpec. If RBraceLoc is
  14252. /// valid, it's the position of the closing '}' brace in a linkage
  14253. /// specification that uses braces.
  14254. Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
  14255. Decl *LinkageSpec,
  14256. SourceLocation RBraceLoc) {
  14257. if (RBraceLoc.isValid()) {
  14258. LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
  14259. LSDecl->setRBraceLoc(RBraceLoc);
  14260. }
  14261. // If the current module doesn't has Parent, it implies that the
  14262. // LinkageSpec isn't in the module created by itself. So we don't
  14263. // need to pop it.
  14264. if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
  14265. getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
  14266. PopGlobalModuleFragment();
  14267. PopDeclContext();
  14268. return LinkageSpec;
  14269. }
  14270. Decl *Sema::ActOnEmptyDeclaration(Scope *S,
  14271. const ParsedAttributesView &AttrList,
  14272. SourceLocation SemiLoc) {
  14273. Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
  14274. // Attribute declarations appertain to empty declaration so we handle
  14275. // them here.
  14276. ProcessDeclAttributeList(S, ED, AttrList);
  14277. CurContext->addDecl(ED);
  14278. return ED;
  14279. }
  14280. /// Perform semantic analysis for the variable declaration that
  14281. /// occurs within a C++ catch clause, returning the newly-created
  14282. /// variable.
  14283. VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
  14284. TypeSourceInfo *TInfo,
  14285. SourceLocation StartLoc,
  14286. SourceLocation Loc,
  14287. IdentifierInfo *Name) {
  14288. bool Invalid = false;
  14289. QualType ExDeclType = TInfo->getType();
  14290. // Arrays and functions decay.
  14291. if (ExDeclType->isArrayType())
  14292. ExDeclType = Context.getArrayDecayedType(ExDeclType);
  14293. else if (ExDeclType->isFunctionType())
  14294. ExDeclType = Context.getPointerType(ExDeclType);
  14295. // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
  14296. // The exception-declaration shall not denote a pointer or reference to an
  14297. // incomplete type, other than [cv] void*.
  14298. // N2844 forbids rvalue references.
  14299. if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
  14300. Diag(Loc, diag::err_catch_rvalue_ref);
  14301. Invalid = true;
  14302. }
  14303. if (ExDeclType->isVariablyModifiedType()) {
  14304. Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
  14305. Invalid = true;
  14306. }
  14307. QualType BaseType = ExDeclType;
  14308. int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
  14309. unsigned DK = diag::err_catch_incomplete;
  14310. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  14311. BaseType = Ptr->getPointeeType();
  14312. Mode = 1;
  14313. DK = diag::err_catch_incomplete_ptr;
  14314. } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
  14315. // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
  14316. BaseType = Ref->getPointeeType();
  14317. Mode = 2;
  14318. DK = diag::err_catch_incomplete_ref;
  14319. }
  14320. if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
  14321. !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
  14322. Invalid = true;
  14323. if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
  14324. Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
  14325. Invalid = true;
  14326. }
  14327. if (!Invalid && !ExDeclType->isDependentType() &&
  14328. RequireNonAbstractType(Loc, ExDeclType,
  14329. diag::err_abstract_type_in_decl,
  14330. AbstractVariableType))
  14331. Invalid = true;
  14332. // Only the non-fragile NeXT runtime currently supports C++ catches
  14333. // of ObjC types, and no runtime supports catching ObjC types by value.
  14334. if (!Invalid && getLangOpts().ObjC) {
  14335. QualType T = ExDeclType;
  14336. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  14337. T = RT->getPointeeType();
  14338. if (T->isObjCObjectType()) {
  14339. Diag(Loc, diag::err_objc_object_catch);
  14340. Invalid = true;
  14341. } else if (T->isObjCObjectPointerType()) {
  14342. // FIXME: should this be a test for macosx-fragile specifically?
  14343. if (getLangOpts().ObjCRuntime.isFragile())
  14344. Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
  14345. }
  14346. }
  14347. VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
  14348. ExDeclType, TInfo, SC_None);
  14349. ExDecl->setExceptionVariable(true);
  14350. // In ARC, infer 'retaining' for variables of retainable type.
  14351. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
  14352. Invalid = true;
  14353. if (!Invalid && !ExDeclType->isDependentType()) {
  14354. if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
  14355. // Insulate this from anything else we might currently be parsing.
  14356. EnterExpressionEvaluationContext scope(
  14357. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  14358. // C++ [except.handle]p16:
  14359. // The object declared in an exception-declaration or, if the
  14360. // exception-declaration does not specify a name, a temporary (12.2) is
  14361. // copy-initialized (8.5) from the exception object. [...]
  14362. // The object is destroyed when the handler exits, after the destruction
  14363. // of any automatic objects initialized within the handler.
  14364. //
  14365. // We just pretend to initialize the object with itself, then make sure
  14366. // it can be destroyed later.
  14367. QualType initType = Context.getExceptionObjectType(ExDeclType);
  14368. InitializedEntity entity =
  14369. InitializedEntity::InitializeVariable(ExDecl);
  14370. InitializationKind initKind =
  14371. InitializationKind::CreateCopy(Loc, SourceLocation());
  14372. Expr *opaqueValue =
  14373. new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
  14374. InitializationSequence sequence(*this, entity, initKind, opaqueValue);
  14375. ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
  14376. if (result.isInvalid())
  14377. Invalid = true;
  14378. else {
  14379. // If the constructor used was non-trivial, set this as the
  14380. // "initializer".
  14381. CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
  14382. if (!construct->getConstructor()->isTrivial()) {
  14383. Expr *init = MaybeCreateExprWithCleanups(construct);
  14384. ExDecl->setInit(init);
  14385. }
  14386. // And make sure it's destructable.
  14387. FinalizeVarWithDestructor(ExDecl, recordType);
  14388. }
  14389. }
  14390. }
  14391. if (Invalid)
  14392. ExDecl->setInvalidDecl();
  14393. return ExDecl;
  14394. }
  14395. /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
  14396. /// handler.
  14397. Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
  14398. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14399. bool Invalid = D.isInvalidType();
  14400. // Check for unexpanded parameter packs.
  14401. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  14402. UPPC_ExceptionType)) {
  14403. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  14404. D.getIdentifierLoc());
  14405. Invalid = true;
  14406. }
  14407. IdentifierInfo *II = D.getIdentifier();
  14408. if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
  14409. LookupOrdinaryName,
  14410. ForVisibleRedeclaration)) {
  14411. // The scope should be freshly made just for us. There is just no way
  14412. // it contains any previous declaration, except for function parameters in
  14413. // a function-try-block's catch statement.
  14414. assert(!S->isDeclScope(PrevDecl));
  14415. if (isDeclInScope(PrevDecl, CurContext, S)) {
  14416. Diag(D.getIdentifierLoc(), diag::err_redefinition)
  14417. << D.getIdentifier();
  14418. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  14419. Invalid = true;
  14420. } else if (PrevDecl->isTemplateParameter())
  14421. // Maybe we will complain about the shadowed template parameter.
  14422. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  14423. }
  14424. if (D.getCXXScopeSpec().isSet() && !Invalid) {
  14425. Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
  14426. << D.getCXXScopeSpec().getRange();
  14427. Invalid = true;
  14428. }
  14429. VarDecl *ExDecl = BuildExceptionDeclaration(
  14430. S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
  14431. if (Invalid)
  14432. ExDecl->setInvalidDecl();
  14433. // Add the exception declaration into this scope.
  14434. if (II)
  14435. PushOnScopeChains(ExDecl, S);
  14436. else
  14437. CurContext->addDecl(ExDecl);
  14438. ProcessDeclAttributes(S, ExDecl, D);
  14439. return ExDecl;
  14440. }
  14441. Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  14442. Expr *AssertExpr,
  14443. Expr *AssertMessageExpr,
  14444. SourceLocation RParenLoc) {
  14445. StringLiteral *AssertMessage =
  14446. AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
  14447. if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
  14448. return nullptr;
  14449. return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
  14450. AssertMessage, RParenLoc, false);
  14451. }
  14452. /// Convert \V to a string we can present to the user in a diagnostic
  14453. /// \T is the type of the expression that has been evaluated into \V
  14454. static bool ConvertAPValueToString(const APValue &V, QualType T,
  14455. SmallVectorImpl<char> &Str) {
  14456. if (!V.hasValue())
  14457. return false;
  14458. switch (V.getKind()) {
  14459. case APValue::ValueKind::Int:
  14460. if (T->isBooleanType()) {
  14461. // Bools are reduced to ints during evaluation, but for
  14462. // diagnostic purposes we want to print them as
  14463. // true or false.
  14464. int64_t BoolValue = V.getInt().getExtValue();
  14465. assert((BoolValue == 0 || BoolValue == 1) &&
  14466. "Bool type, but value is not 0 or 1");
  14467. llvm::raw_svector_ostream OS(Str);
  14468. OS << (BoolValue ? "true" : "false");
  14469. } else if (T->isCharType()) {
  14470. // Same is true for chars.
  14471. Str.push_back('\'');
  14472. Str.push_back(V.getInt().getExtValue());
  14473. Str.push_back('\'');
  14474. } else
  14475. V.getInt().toString(Str);
  14476. break;
  14477. case APValue::ValueKind::Float:
  14478. V.getFloat().toString(Str);
  14479. break;
  14480. case APValue::ValueKind::LValue:
  14481. if (V.isNullPointer()) {
  14482. llvm::raw_svector_ostream OS(Str);
  14483. OS << "nullptr";
  14484. } else
  14485. return false;
  14486. break;
  14487. case APValue::ValueKind::ComplexFloat: {
  14488. llvm::raw_svector_ostream OS(Str);
  14489. OS << '(';
  14490. V.getComplexFloatReal().toString(Str);
  14491. OS << " + ";
  14492. V.getComplexFloatImag().toString(Str);
  14493. OS << "i)";
  14494. } break;
  14495. case APValue::ValueKind::ComplexInt: {
  14496. llvm::raw_svector_ostream OS(Str);
  14497. OS << '(';
  14498. V.getComplexIntReal().toString(Str);
  14499. OS << " + ";
  14500. V.getComplexIntImag().toString(Str);
  14501. OS << "i)";
  14502. } break;
  14503. default:
  14504. return false;
  14505. }
  14506. return true;
  14507. }
  14508. /// Some Expression types are not useful to print notes about,
  14509. /// e.g. literals and values that have already been expanded
  14510. /// before such as int-valued template parameters.
  14511. static bool UsefulToPrintExpr(const Expr *E) {
  14512. E = E->IgnoreParenImpCasts();
  14513. // Literals are pretty easy for humans to understand.
  14514. if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
  14515. CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E))
  14516. return false;
  14517. // These have been substituted from template parameters
  14518. // and appear as literals in the static assert error.
  14519. if (isa<SubstNonTypeTemplateParmExpr>(E))
  14520. return false;
  14521. // -5 is also simple to understand.
  14522. if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
  14523. return UsefulToPrintExpr(UnaryOp->getSubExpr());
  14524. // Ignore nested binary operators. This could be a FIXME for improvements
  14525. // to the diagnostics in the future.
  14526. if (isa<BinaryOperator>(E))
  14527. return false;
  14528. return true;
  14529. }
  14530. /// Try to print more useful information about a failed static_assert
  14531. /// with expression \E
  14532. void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
  14533. if (const auto *Op = dyn_cast<BinaryOperator>(E)) {
  14534. const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
  14535. const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
  14536. // Ignore comparisons of boolean expressions with a boolean literal.
  14537. if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
  14538. (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
  14539. return;
  14540. // Don't print obvious expressions.
  14541. if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
  14542. return;
  14543. struct {
  14544. const clang::Expr *Cond;
  14545. Expr::EvalResult Result;
  14546. SmallString<12> ValueString;
  14547. bool Print;
  14548. } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
  14549. {RHS, Expr::EvalResult(), {}, false}};
  14550. for (unsigned I = 0; I < 2; I++) {
  14551. const Expr *Side = DiagSide[I].Cond;
  14552. Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
  14553. DiagSide[I].Print = ConvertAPValueToString(
  14554. DiagSide[I].Result.Val, Side->getType(), DiagSide[I].ValueString);
  14555. }
  14556. if (DiagSide[0].Print && DiagSide[1].Print) {
  14557. Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
  14558. << DiagSide[0].ValueString << Op->getOpcodeStr()
  14559. << DiagSide[1].ValueString << Op->getSourceRange();
  14560. }
  14561. }
  14562. }
  14563. Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  14564. Expr *AssertExpr,
  14565. StringLiteral *AssertMessage,
  14566. SourceLocation RParenLoc,
  14567. bool Failed) {
  14568. assert(AssertExpr != nullptr && "Expected non-null condition");
  14569. if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
  14570. !Failed) {
  14571. // In a static_assert-declaration, the constant-expression shall be a
  14572. // constant expression that can be contextually converted to bool.
  14573. ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
  14574. if (Converted.isInvalid())
  14575. Failed = true;
  14576. ExprResult FullAssertExpr =
  14577. ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
  14578. /*DiscardedValue*/ false,
  14579. /*IsConstexpr*/ true);
  14580. if (FullAssertExpr.isInvalid())
  14581. Failed = true;
  14582. else
  14583. AssertExpr = FullAssertExpr.get();
  14584. llvm::APSInt Cond;
  14585. Expr *BaseExpr = AssertExpr;
  14586. AllowFoldKind FoldKind = NoFold;
  14587. if (!getLangOpts().CPlusPlus) {
  14588. // In C mode, allow folding as an extension for better compatibility with
  14589. // C++ in terms of expressions like static_assert("test") or
  14590. // static_assert(nullptr).
  14591. FoldKind = AllowFold;
  14592. }
  14593. if (!Failed && VerifyIntegerConstantExpression(
  14594. BaseExpr, &Cond,
  14595. diag::err_static_assert_expression_is_not_constant,
  14596. FoldKind).isInvalid())
  14597. Failed = true;
  14598. if (!Failed && !Cond) {
  14599. SmallString<256> MsgBuffer;
  14600. llvm::raw_svector_ostream Msg(MsgBuffer);
  14601. if (AssertMessage) {
  14602. const auto *MsgStr = cast<StringLiteral>(AssertMessage);
  14603. if (MsgStr->isOrdinary())
  14604. Msg << MsgStr->getString();
  14605. else
  14606. MsgStr->printPretty(Msg, nullptr, getPrintingPolicy());
  14607. }
  14608. Expr *InnerCond = nullptr;
  14609. std::string InnerCondDescription;
  14610. std::tie(InnerCond, InnerCondDescription) =
  14611. findFailedBooleanCondition(Converted.get());
  14612. if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
  14613. // Drill down into concept specialization expressions to see why they
  14614. // weren't satisfied.
  14615. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  14616. << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
  14617. ConstraintSatisfaction Satisfaction;
  14618. if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
  14619. DiagnoseUnsatisfiedConstraint(Satisfaction);
  14620. } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
  14621. && !isa<IntegerLiteral>(InnerCond)) {
  14622. Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
  14623. << InnerCondDescription << !AssertMessage
  14624. << Msg.str() << InnerCond->getSourceRange();
  14625. DiagnoseStaticAssertDetails(InnerCond);
  14626. } else {
  14627. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  14628. << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
  14629. }
  14630. Failed = true;
  14631. }
  14632. } else {
  14633. ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
  14634. /*DiscardedValue*/false,
  14635. /*IsConstexpr*/true);
  14636. if (FullAssertExpr.isInvalid())
  14637. Failed = true;
  14638. else
  14639. AssertExpr = FullAssertExpr.get();
  14640. }
  14641. Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
  14642. AssertExpr, AssertMessage, RParenLoc,
  14643. Failed);
  14644. CurContext->addDecl(Decl);
  14645. return Decl;
  14646. }
  14647. /// Perform semantic analysis of the given friend type declaration.
  14648. ///
  14649. /// \returns A friend declaration that.
  14650. FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
  14651. SourceLocation FriendLoc,
  14652. TypeSourceInfo *TSInfo) {
  14653. assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
  14654. QualType T = TSInfo->getType();
  14655. SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
  14656. // C++03 [class.friend]p2:
  14657. // An elaborated-type-specifier shall be used in a friend declaration
  14658. // for a class.*
  14659. //
  14660. // * The class-key of the elaborated-type-specifier is required.
  14661. if (!CodeSynthesisContexts.empty()) {
  14662. // Do not complain about the form of friend template types during any kind
  14663. // of code synthesis. For template instantiation, we will have complained
  14664. // when the template was defined.
  14665. } else {
  14666. if (!T->isElaboratedTypeSpecifier()) {
  14667. // If we evaluated the type to a record type, suggest putting
  14668. // a tag in front.
  14669. if (const RecordType *RT = T->getAs<RecordType>()) {
  14670. RecordDecl *RD = RT->getDecl();
  14671. SmallString<16> InsertionText(" ");
  14672. InsertionText += RD->getKindName();
  14673. Diag(TypeRange.getBegin(),
  14674. getLangOpts().CPlusPlus11 ?
  14675. diag::warn_cxx98_compat_unelaborated_friend_type :
  14676. diag::ext_unelaborated_friend_type)
  14677. << (unsigned) RD->getTagKind()
  14678. << T
  14679. << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
  14680. InsertionText);
  14681. } else {
  14682. Diag(FriendLoc,
  14683. getLangOpts().CPlusPlus11 ?
  14684. diag::warn_cxx98_compat_nonclass_type_friend :
  14685. diag::ext_nonclass_type_friend)
  14686. << T
  14687. << TypeRange;
  14688. }
  14689. } else if (T->getAs<EnumType>()) {
  14690. Diag(FriendLoc,
  14691. getLangOpts().CPlusPlus11 ?
  14692. diag::warn_cxx98_compat_enum_friend :
  14693. diag::ext_enum_friend)
  14694. << T
  14695. << TypeRange;
  14696. }
  14697. // C++11 [class.friend]p3:
  14698. // A friend declaration that does not declare a function shall have one
  14699. // of the following forms:
  14700. // friend elaborated-type-specifier ;
  14701. // friend simple-type-specifier ;
  14702. // friend typename-specifier ;
  14703. if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
  14704. Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
  14705. }
  14706. // If the type specifier in a friend declaration designates a (possibly
  14707. // cv-qualified) class type, that class is declared as a friend; otherwise,
  14708. // the friend declaration is ignored.
  14709. return FriendDecl::Create(Context, CurContext,
  14710. TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
  14711. FriendLoc);
  14712. }
  14713. /// Handle a friend tag declaration where the scope specifier was
  14714. /// templated.
  14715. DeclResult Sema::ActOnTemplatedFriendTag(
  14716. Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
  14717. CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
  14718. const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {
  14719. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  14720. bool IsMemberSpecialization = false;
  14721. bool Invalid = false;
  14722. if (TemplateParameterList *TemplateParams =
  14723. MatchTemplateParametersToScopeSpecifier(
  14724. TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
  14725. IsMemberSpecialization, Invalid)) {
  14726. if (TemplateParams->size() > 0) {
  14727. // This is a declaration of a class template.
  14728. if (Invalid)
  14729. return true;
  14730. return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
  14731. NameLoc, Attr, TemplateParams, AS_public,
  14732. /*ModulePrivateLoc=*/SourceLocation(),
  14733. FriendLoc, TempParamLists.size() - 1,
  14734. TempParamLists.data()).get();
  14735. } else {
  14736. // The "template<>" header is extraneous.
  14737. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  14738. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  14739. IsMemberSpecialization = true;
  14740. }
  14741. }
  14742. if (Invalid) return true;
  14743. bool isAllExplicitSpecializations = true;
  14744. for (unsigned I = TempParamLists.size(); I-- > 0; ) {
  14745. if (TempParamLists[I]->size()) {
  14746. isAllExplicitSpecializations = false;
  14747. break;
  14748. }
  14749. }
  14750. // FIXME: don't ignore attributes.
  14751. // If it's explicit specializations all the way down, just forget
  14752. // about the template header and build an appropriate non-templated
  14753. // friend. TODO: for source fidelity, remember the headers.
  14754. if (isAllExplicitSpecializations) {
  14755. if (SS.isEmpty()) {
  14756. bool Owned = false;
  14757. bool IsDependent = false;
  14758. return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr,
  14759. AS_public,
  14760. /*ModulePrivateLoc=*/SourceLocation(),
  14761. MultiTemplateParamsArg(), Owned, IsDependent,
  14762. /*ScopedEnumKWLoc=*/SourceLocation(),
  14763. /*ScopedEnumUsesClassTag=*/false,
  14764. /*UnderlyingType=*/TypeResult(),
  14765. /*IsTypeSpecifier=*/false,
  14766. /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
  14767. }
  14768. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  14769. ElaboratedTypeKeyword Keyword
  14770. = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  14771. QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
  14772. *Name, NameLoc);
  14773. if (T.isNull())
  14774. return true;
  14775. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  14776. if (isa<DependentNameType>(T)) {
  14777. DependentNameTypeLoc TL =
  14778. TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  14779. TL.setElaboratedKeywordLoc(TagLoc);
  14780. TL.setQualifierLoc(QualifierLoc);
  14781. TL.setNameLoc(NameLoc);
  14782. } else {
  14783. ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
  14784. TL.setElaboratedKeywordLoc(TagLoc);
  14785. TL.setQualifierLoc(QualifierLoc);
  14786. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
  14787. }
  14788. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  14789. TSI, FriendLoc, TempParamLists);
  14790. Friend->setAccess(AS_public);
  14791. CurContext->addDecl(Friend);
  14792. return Friend;
  14793. }
  14794. assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
  14795. // Handle the case of a templated-scope friend class. e.g.
  14796. // template <class T> class A<T>::B;
  14797. // FIXME: we don't support these right now.
  14798. Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
  14799. << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
  14800. ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  14801. QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
  14802. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  14803. DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  14804. TL.setElaboratedKeywordLoc(TagLoc);
  14805. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  14806. TL.setNameLoc(NameLoc);
  14807. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  14808. TSI, FriendLoc, TempParamLists);
  14809. Friend->setAccess(AS_public);
  14810. Friend->setUnsupportedFriend(true);
  14811. CurContext->addDecl(Friend);
  14812. return Friend;
  14813. }
  14814. /// Handle a friend type declaration. This works in tandem with
  14815. /// ActOnTag.
  14816. ///
  14817. /// Notes on friend class templates:
  14818. ///
  14819. /// We generally treat friend class declarations as if they were
  14820. /// declaring a class. So, for example, the elaborated type specifier
  14821. /// in a friend declaration is required to obey the restrictions of a
  14822. /// class-head (i.e. no typedefs in the scope chain), template
  14823. /// parameters are required to match up with simple template-ids, &c.
  14824. /// However, unlike when declaring a template specialization, it's
  14825. /// okay to refer to a template specialization without an empty
  14826. /// template parameter declaration, e.g.
  14827. /// friend class A<T>::B<unsigned>;
  14828. /// We permit this as a special case; if there are any template
  14829. /// parameters present at all, require proper matching, i.e.
  14830. /// template <> template \<class T> friend class A<int>::B;
  14831. Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
  14832. MultiTemplateParamsArg TempParams) {
  14833. SourceLocation Loc = DS.getBeginLoc();
  14834. assert(DS.isFriendSpecified());
  14835. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  14836. // C++ [class.friend]p3:
  14837. // A friend declaration that does not declare a function shall have one of
  14838. // the following forms:
  14839. // friend elaborated-type-specifier ;
  14840. // friend simple-type-specifier ;
  14841. // friend typename-specifier ;
  14842. //
  14843. // Any declaration with a type qualifier does not have that form. (It's
  14844. // legal to specify a qualified type as a friend, you just can't write the
  14845. // keywords.)
  14846. if (DS.getTypeQualifiers()) {
  14847. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  14848. Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
  14849. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  14850. Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
  14851. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  14852. Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
  14853. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  14854. Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
  14855. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  14856. Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
  14857. }
  14858. // Try to convert the decl specifier to a type. This works for
  14859. // friend templates because ActOnTag never produces a ClassTemplateDecl
  14860. // for a TUK_Friend.
  14861. Declarator TheDeclarator(DS, ParsedAttributesView::none(),
  14862. DeclaratorContext::Member);
  14863. TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
  14864. QualType T = TSI->getType();
  14865. if (TheDeclarator.isInvalidType())
  14866. return nullptr;
  14867. if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
  14868. return nullptr;
  14869. // This is definitely an error in C++98. It's probably meant to
  14870. // be forbidden in C++0x, too, but the specification is just
  14871. // poorly written.
  14872. //
  14873. // The problem is with declarations like the following:
  14874. // template <T> friend A<T>::foo;
  14875. // where deciding whether a class C is a friend or not now hinges
  14876. // on whether there exists an instantiation of A that causes
  14877. // 'foo' to equal C. There are restrictions on class-heads
  14878. // (which we declare (by fiat) elaborated friend declarations to
  14879. // be) that makes this tractable.
  14880. //
  14881. // FIXME: handle "template <> friend class A<T>;", which
  14882. // is possibly well-formed? Who even knows?
  14883. if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
  14884. Diag(Loc, diag::err_tagless_friend_type_template)
  14885. << DS.getSourceRange();
  14886. return nullptr;
  14887. }
  14888. // C++98 [class.friend]p1: A friend of a class is a function
  14889. // or class that is not a member of the class . . .
  14890. // This is fixed in DR77, which just barely didn't make the C++03
  14891. // deadline. It's also a very silly restriction that seriously
  14892. // affects inner classes and which nobody else seems to implement;
  14893. // thus we never diagnose it, not even in -pedantic.
  14894. //
  14895. // But note that we could warn about it: it's always useless to
  14896. // friend one of your own members (it's not, however, worthless to
  14897. // friend a member of an arbitrary specialization of your template).
  14898. Decl *D;
  14899. if (!TempParams.empty())
  14900. D = FriendTemplateDecl::Create(Context, CurContext, Loc,
  14901. TempParams,
  14902. TSI,
  14903. DS.getFriendSpecLoc());
  14904. else
  14905. D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
  14906. if (!D)
  14907. return nullptr;
  14908. D->setAccess(AS_public);
  14909. CurContext->addDecl(D);
  14910. return D;
  14911. }
  14912. NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
  14913. MultiTemplateParamsArg TemplateParams) {
  14914. const DeclSpec &DS = D.getDeclSpec();
  14915. assert(DS.isFriendSpecified());
  14916. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  14917. SourceLocation Loc = D.getIdentifierLoc();
  14918. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14919. // C++ [class.friend]p1
  14920. // A friend of a class is a function or class....
  14921. // Note that this sees through typedefs, which is intended.
  14922. // It *doesn't* see through dependent types, which is correct
  14923. // according to [temp.arg.type]p3:
  14924. // If a declaration acquires a function type through a
  14925. // type dependent on a template-parameter and this causes
  14926. // a declaration that does not use the syntactic form of a
  14927. // function declarator to have a function type, the program
  14928. // is ill-formed.
  14929. if (!TInfo->getType()->isFunctionType()) {
  14930. Diag(Loc, diag::err_unexpected_friend);
  14931. // It might be worthwhile to try to recover by creating an
  14932. // appropriate declaration.
  14933. return nullptr;
  14934. }
  14935. // C++ [namespace.memdef]p3
  14936. // - If a friend declaration in a non-local class first declares a
  14937. // class or function, the friend class or function is a member
  14938. // of the innermost enclosing namespace.
  14939. // - The name of the friend is not found by simple name lookup
  14940. // until a matching declaration is provided in that namespace
  14941. // scope (either before or after the class declaration granting
  14942. // friendship).
  14943. // - If a friend function is called, its name may be found by the
  14944. // name lookup that considers functions from namespaces and
  14945. // classes associated with the types of the function arguments.
  14946. // - When looking for a prior declaration of a class or a function
  14947. // declared as a friend, scopes outside the innermost enclosing
  14948. // namespace scope are not considered.
  14949. CXXScopeSpec &SS = D.getCXXScopeSpec();
  14950. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  14951. assert(NameInfo.getName());
  14952. // Check for unexpanded parameter packs.
  14953. if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
  14954. DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
  14955. DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
  14956. return nullptr;
  14957. // The context we found the declaration in, or in which we should
  14958. // create the declaration.
  14959. DeclContext *DC;
  14960. Scope *DCScope = S;
  14961. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  14962. ForExternalRedeclaration);
  14963. // There are five cases here.
  14964. // - There's no scope specifier and we're in a local class. Only look
  14965. // for functions declared in the immediately-enclosing block scope.
  14966. // We recover from invalid scope qualifiers as if they just weren't there.
  14967. FunctionDecl *FunctionContainingLocalClass = nullptr;
  14968. if ((SS.isInvalid() || !SS.isSet()) &&
  14969. (FunctionContainingLocalClass =
  14970. cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
  14971. // C++11 [class.friend]p11:
  14972. // If a friend declaration appears in a local class and the name
  14973. // specified is an unqualified name, a prior declaration is
  14974. // looked up without considering scopes that are outside the
  14975. // innermost enclosing non-class scope. For a friend function
  14976. // declaration, if there is no prior declaration, the program is
  14977. // ill-formed.
  14978. // Find the innermost enclosing non-class scope. This is the block
  14979. // scope containing the local class definition (or for a nested class,
  14980. // the outer local class).
  14981. DCScope = S->getFnParent();
  14982. // Look up the function name in the scope.
  14983. Previous.clear(LookupLocalFriendName);
  14984. LookupName(Previous, S, /*AllowBuiltinCreation*/false);
  14985. if (!Previous.empty()) {
  14986. // All possible previous declarations must have the same context:
  14987. // either they were declared at block scope or they are members of
  14988. // one of the enclosing local classes.
  14989. DC = Previous.getRepresentativeDecl()->getDeclContext();
  14990. } else {
  14991. // This is ill-formed, but provide the context that we would have
  14992. // declared the function in, if we were permitted to, for error recovery.
  14993. DC = FunctionContainingLocalClass;
  14994. }
  14995. adjustContextForLocalExternDecl(DC);
  14996. // C++ [class.friend]p6:
  14997. // A function can be defined in a friend declaration of a class if and
  14998. // only if the class is a non-local class (9.8), the function name is
  14999. // unqualified, and the function has namespace scope.
  15000. if (D.isFunctionDefinition()) {
  15001. Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
  15002. }
  15003. // - There's no scope specifier, in which case we just go to the
  15004. // appropriate scope and look for a function or function template
  15005. // there as appropriate.
  15006. } else if (SS.isInvalid() || !SS.isSet()) {
  15007. // C++11 [namespace.memdef]p3:
  15008. // If the name in a friend declaration is neither qualified nor
  15009. // a template-id and the declaration is a function or an
  15010. // elaborated-type-specifier, the lookup to determine whether
  15011. // the entity has been previously declared shall not consider
  15012. // any scopes outside the innermost enclosing namespace.
  15013. bool isTemplateId =
  15014. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
  15015. // Find the appropriate context according to the above.
  15016. DC = CurContext;
  15017. // Skip class contexts. If someone can cite chapter and verse
  15018. // for this behavior, that would be nice --- it's what GCC and
  15019. // EDG do, and it seems like a reasonable intent, but the spec
  15020. // really only says that checks for unqualified existing
  15021. // declarations should stop at the nearest enclosing namespace,
  15022. // not that they should only consider the nearest enclosing
  15023. // namespace.
  15024. while (DC->isRecord())
  15025. DC = DC->getParent();
  15026. DeclContext *LookupDC = DC->getNonTransparentContext();
  15027. while (true) {
  15028. LookupQualifiedName(Previous, LookupDC);
  15029. if (!Previous.empty()) {
  15030. DC = LookupDC;
  15031. break;
  15032. }
  15033. if (isTemplateId) {
  15034. if (isa<TranslationUnitDecl>(LookupDC)) break;
  15035. } else {
  15036. if (LookupDC->isFileContext()) break;
  15037. }
  15038. LookupDC = LookupDC->getParent();
  15039. }
  15040. DCScope = getScopeForDeclContext(S, DC);
  15041. // - There's a non-dependent scope specifier, in which case we
  15042. // compute it and do a previous lookup there for a function
  15043. // or function template.
  15044. } else if (!SS.getScopeRep()->isDependent()) {
  15045. DC = computeDeclContext(SS);
  15046. if (!DC) return nullptr;
  15047. if (RequireCompleteDeclContext(SS, DC)) return nullptr;
  15048. LookupQualifiedName(Previous, DC);
  15049. // C++ [class.friend]p1: A friend of a class is a function or
  15050. // class that is not a member of the class . . .
  15051. if (DC->Equals(CurContext))
  15052. Diag(DS.getFriendSpecLoc(),
  15053. getLangOpts().CPlusPlus11 ?
  15054. diag::warn_cxx98_compat_friend_is_member :
  15055. diag::err_friend_is_member);
  15056. if (D.isFunctionDefinition()) {
  15057. // C++ [class.friend]p6:
  15058. // A function can be defined in a friend declaration of a class if and
  15059. // only if the class is a non-local class (9.8), the function name is
  15060. // unqualified, and the function has namespace scope.
  15061. //
  15062. // FIXME: We should only do this if the scope specifier names the
  15063. // innermost enclosing namespace; otherwise the fixit changes the
  15064. // meaning of the code.
  15065. SemaDiagnosticBuilder DB
  15066. = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
  15067. DB << SS.getScopeRep();
  15068. if (DC->isFileContext())
  15069. DB << FixItHint::CreateRemoval(SS.getRange());
  15070. SS.clear();
  15071. }
  15072. // - There's a scope specifier that does not match any template
  15073. // parameter lists, in which case we use some arbitrary context,
  15074. // create a method or method template, and wait for instantiation.
  15075. // - There's a scope specifier that does match some template
  15076. // parameter lists, which we don't handle right now.
  15077. } else {
  15078. if (D.isFunctionDefinition()) {
  15079. // C++ [class.friend]p6:
  15080. // A function can be defined in a friend declaration of a class if and
  15081. // only if the class is a non-local class (9.8), the function name is
  15082. // unqualified, and the function has namespace scope.
  15083. Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
  15084. << SS.getScopeRep();
  15085. }
  15086. DC = CurContext;
  15087. assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
  15088. }
  15089. if (!DC->isRecord()) {
  15090. int DiagArg = -1;
  15091. switch (D.getName().getKind()) {
  15092. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  15093. case UnqualifiedIdKind::IK_ConstructorName:
  15094. DiagArg = 0;
  15095. break;
  15096. case UnqualifiedIdKind::IK_DestructorName:
  15097. DiagArg = 1;
  15098. break;
  15099. case UnqualifiedIdKind::IK_ConversionFunctionId:
  15100. DiagArg = 2;
  15101. break;
  15102. case UnqualifiedIdKind::IK_DeductionGuideName:
  15103. DiagArg = 3;
  15104. break;
  15105. case UnqualifiedIdKind::IK_Identifier:
  15106. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  15107. case UnqualifiedIdKind::IK_LiteralOperatorId:
  15108. case UnqualifiedIdKind::IK_OperatorFunctionId:
  15109. case UnqualifiedIdKind::IK_TemplateId:
  15110. break;
  15111. }
  15112. // This implies that it has to be an operator or function.
  15113. if (DiagArg >= 0) {
  15114. Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
  15115. return nullptr;
  15116. }
  15117. }
  15118. // FIXME: This is an egregious hack to cope with cases where the scope stack
  15119. // does not contain the declaration context, i.e., in an out-of-line
  15120. // definition of a class.
  15121. Scope FakeDCScope(S, Scope::DeclScope, Diags);
  15122. if (!DCScope) {
  15123. FakeDCScope.setEntity(DC);
  15124. DCScope = &FakeDCScope;
  15125. }
  15126. bool AddToScope = true;
  15127. NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
  15128. TemplateParams, AddToScope);
  15129. if (!ND) return nullptr;
  15130. assert(ND->getLexicalDeclContext() == CurContext);
  15131. // If we performed typo correction, we might have added a scope specifier
  15132. // and changed the decl context.
  15133. DC = ND->getDeclContext();
  15134. // Add the function declaration to the appropriate lookup tables,
  15135. // adjusting the redeclarations list as necessary. We don't
  15136. // want to do this yet if the friending class is dependent.
  15137. //
  15138. // Also update the scope-based lookup if the target context's
  15139. // lookup context is in lexical scope.
  15140. if (!CurContext->isDependentContext()) {
  15141. DC = DC->getRedeclContext();
  15142. DC->makeDeclVisibleInContext(ND);
  15143. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  15144. PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
  15145. }
  15146. FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
  15147. D.getIdentifierLoc(), ND,
  15148. DS.getFriendSpecLoc());
  15149. FrD->setAccess(AS_public);
  15150. CurContext->addDecl(FrD);
  15151. if (ND->isInvalidDecl()) {
  15152. FrD->setInvalidDecl();
  15153. } else {
  15154. if (DC->isRecord()) CheckFriendAccess(ND);
  15155. FunctionDecl *FD;
  15156. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  15157. FD = FTD->getTemplatedDecl();
  15158. else
  15159. FD = cast<FunctionDecl>(ND);
  15160. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
  15161. // default argument expression, that declaration shall be a definition
  15162. // and shall be the only declaration of the function or function
  15163. // template in the translation unit.
  15164. if (functionDeclHasDefaultArgument(FD)) {
  15165. // We can't look at FD->getPreviousDecl() because it may not have been set
  15166. // if we're in a dependent context. If the function is known to be a
  15167. // redeclaration, we will have narrowed Previous down to the right decl.
  15168. if (D.isRedeclaration()) {
  15169. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  15170. Diag(Previous.getRepresentativeDecl()->getLocation(),
  15171. diag::note_previous_declaration);
  15172. } else if (!D.isFunctionDefinition())
  15173. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
  15174. }
  15175. // Mark templated-scope function declarations as unsupported.
  15176. if (FD->getNumTemplateParameterLists() && SS.isValid()) {
  15177. Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
  15178. << SS.getScopeRep() << SS.getRange()
  15179. << cast<CXXRecordDecl>(CurContext);
  15180. FrD->setUnsupportedFriend(true);
  15181. }
  15182. }
  15183. warnOnReservedIdentifier(ND);
  15184. return ND;
  15185. }
  15186. void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
  15187. AdjustDeclIfTemplate(Dcl);
  15188. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
  15189. if (!Fn) {
  15190. Diag(DelLoc, diag::err_deleted_non_function);
  15191. return;
  15192. }
  15193. // Deleted function does not have a body.
  15194. Fn->setWillHaveBody(false);
  15195. if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
  15196. // Don't consider the implicit declaration we generate for explicit
  15197. // specializations. FIXME: Do not generate these implicit declarations.
  15198. if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
  15199. Prev->getPreviousDecl()) &&
  15200. !Prev->isDefined()) {
  15201. Diag(DelLoc, diag::err_deleted_decl_not_first);
  15202. Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
  15203. Prev->isImplicit() ? diag::note_previous_implicit_declaration
  15204. : diag::note_previous_declaration);
  15205. // We can't recover from this; the declaration might have already
  15206. // been used.
  15207. Fn->setInvalidDecl();
  15208. return;
  15209. }
  15210. // To maintain the invariant that functions are only deleted on their first
  15211. // declaration, mark the implicitly-instantiated declaration of the
  15212. // explicitly-specialized function as deleted instead of marking the
  15213. // instantiated redeclaration.
  15214. Fn = Fn->getCanonicalDecl();
  15215. }
  15216. // dllimport/dllexport cannot be deleted.
  15217. if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
  15218. Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
  15219. Fn->setInvalidDecl();
  15220. }
  15221. // C++11 [basic.start.main]p3:
  15222. // A program that defines main as deleted [...] is ill-formed.
  15223. if (Fn->isMain())
  15224. Diag(DelLoc, diag::err_deleted_main);
  15225. // C++11 [dcl.fct.def.delete]p4:
  15226. // A deleted function is implicitly inline.
  15227. Fn->setImplicitlyInline();
  15228. Fn->setDeletedAsWritten();
  15229. }
  15230. void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
  15231. if (!Dcl || Dcl->isInvalidDecl())
  15232. return;
  15233. auto *FD = dyn_cast<FunctionDecl>(Dcl);
  15234. if (!FD) {
  15235. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
  15236. if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
  15237. Diag(DefaultLoc, diag::err_defaulted_comparison_template);
  15238. return;
  15239. }
  15240. }
  15241. Diag(DefaultLoc, diag::err_default_special_members)
  15242. << getLangOpts().CPlusPlus20;
  15243. return;
  15244. }
  15245. // Reject if this can't possibly be a defaultable function.
  15246. DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
  15247. if (!DefKind &&
  15248. // A dependent function that doesn't locally look defaultable can
  15249. // still instantiate to a defaultable function if it's a constructor
  15250. // or assignment operator.
  15251. (!FD->isDependentContext() ||
  15252. (!isa<CXXConstructorDecl>(FD) &&
  15253. FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
  15254. Diag(DefaultLoc, diag::err_default_special_members)
  15255. << getLangOpts().CPlusPlus20;
  15256. return;
  15257. }
  15258. // Issue compatibility warning. We already warned if the operator is
  15259. // 'operator<=>' when parsing the '<=>' token.
  15260. if (DefKind.isComparison() &&
  15261. DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
  15262. Diag(DefaultLoc, getLangOpts().CPlusPlus20
  15263. ? diag::warn_cxx17_compat_defaulted_comparison
  15264. : diag::ext_defaulted_comparison);
  15265. }
  15266. FD->setDefaulted();
  15267. FD->setExplicitlyDefaulted();
  15268. FD->setDefaultLoc(DefaultLoc);
  15269. // Defer checking functions that are defaulted in a dependent context.
  15270. if (FD->isDependentContext())
  15271. return;
  15272. // Unset that we will have a body for this function. We might not,
  15273. // if it turns out to be trivial, and we don't need this marking now
  15274. // that we've marked it as defaulted.
  15275. FD->setWillHaveBody(false);
  15276. if (DefKind.isComparison()) {
  15277. // If this comparison's defaulting occurs within the definition of its
  15278. // lexical class context, we have to do the checking when complete.
  15279. if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
  15280. if (!RD->isCompleteDefinition())
  15281. return;
  15282. }
  15283. // If this member fn was defaulted on its first declaration, we will have
  15284. // already performed the checking in CheckCompletedCXXClass. Such a
  15285. // declaration doesn't trigger an implicit definition.
  15286. if (isa<CXXMethodDecl>(FD)) {
  15287. const FunctionDecl *Primary = FD;
  15288. if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
  15289. // Ask the template instantiation pattern that actually had the
  15290. // '= default' on it.
  15291. Primary = Pattern;
  15292. if (Primary->getCanonicalDecl()->isDefaulted())
  15293. return;
  15294. }
  15295. if (DefKind.isComparison()) {
  15296. if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
  15297. FD->setInvalidDecl();
  15298. else
  15299. DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
  15300. } else {
  15301. auto *MD = cast<CXXMethodDecl>(FD);
  15302. if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember(),
  15303. DefaultLoc))
  15304. MD->setInvalidDecl();
  15305. else
  15306. DefineDefaultedFunction(*this, MD, DefaultLoc);
  15307. }
  15308. }
  15309. static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
  15310. for (Stmt *SubStmt : S->children()) {
  15311. if (!SubStmt)
  15312. continue;
  15313. if (isa<ReturnStmt>(SubStmt))
  15314. Self.Diag(SubStmt->getBeginLoc(),
  15315. diag::err_return_in_constructor_handler);
  15316. if (!isa<Expr>(SubStmt))
  15317. SearchForReturnInStmt(Self, SubStmt);
  15318. }
  15319. }
  15320. void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
  15321. for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
  15322. CXXCatchStmt *Handler = TryBlock->getHandler(I);
  15323. SearchForReturnInStmt(*this, Handler);
  15324. }
  15325. }
  15326. void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
  15327. FnBodyKind BodyKind) {
  15328. switch (BodyKind) {
  15329. case FnBodyKind::Delete:
  15330. SetDeclDeleted(D, Loc);
  15331. break;
  15332. case FnBodyKind::Default:
  15333. SetDeclDefaulted(D, Loc);
  15334. break;
  15335. case FnBodyKind::Other:
  15336. llvm_unreachable(
  15337. "Parsed function body should be '= delete;' or '= default;'");
  15338. }
  15339. }
  15340. bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  15341. const CXXMethodDecl *Old) {
  15342. const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
  15343. const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
  15344. if (OldFT->hasExtParameterInfos()) {
  15345. for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
  15346. // A parameter of the overriding method should be annotated with noescape
  15347. // if the corresponding parameter of the overridden method is annotated.
  15348. if (OldFT->getExtParameterInfo(I).isNoEscape() &&
  15349. !NewFT->getExtParameterInfo(I).isNoEscape()) {
  15350. Diag(New->getParamDecl(I)->getLocation(),
  15351. diag::warn_overriding_method_missing_noescape);
  15352. Diag(Old->getParamDecl(I)->getLocation(),
  15353. diag::note_overridden_marked_noescape);
  15354. }
  15355. }
  15356. // Virtual overrides must have the same code_seg.
  15357. const auto *OldCSA = Old->getAttr<CodeSegAttr>();
  15358. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  15359. if ((NewCSA || OldCSA) &&
  15360. (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
  15361. Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
  15362. Diag(Old->getLocation(), diag::note_previous_declaration);
  15363. return true;
  15364. }
  15365. CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
  15366. // If the calling conventions match, everything is fine
  15367. if (NewCC == OldCC)
  15368. return false;
  15369. // If the calling conventions mismatch because the new function is static,
  15370. // suppress the calling convention mismatch error; the error about static
  15371. // function override (err_static_overrides_virtual from
  15372. // Sema::CheckFunctionDeclaration) is more clear.
  15373. if (New->getStorageClass() == SC_Static)
  15374. return false;
  15375. Diag(New->getLocation(),
  15376. diag::err_conflicting_overriding_cc_attributes)
  15377. << New->getDeclName() << New->getType() << Old->getType();
  15378. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  15379. return true;
  15380. }
  15381. bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
  15382. const CXXMethodDecl *Old) {
  15383. QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
  15384. QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
  15385. if (Context.hasSameType(NewTy, OldTy) ||
  15386. NewTy->isDependentType() || OldTy->isDependentType())
  15387. return false;
  15388. // Check if the return types are covariant
  15389. QualType NewClassTy, OldClassTy;
  15390. /// Both types must be pointers or references to classes.
  15391. if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
  15392. if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
  15393. NewClassTy = NewPT->getPointeeType();
  15394. OldClassTy = OldPT->getPointeeType();
  15395. }
  15396. } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
  15397. if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
  15398. if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
  15399. NewClassTy = NewRT->getPointeeType();
  15400. OldClassTy = OldRT->getPointeeType();
  15401. }
  15402. }
  15403. }
  15404. // The return types aren't either both pointers or references to a class type.
  15405. if (NewClassTy.isNull()) {
  15406. Diag(New->getLocation(),
  15407. diag::err_different_return_type_for_overriding_virtual_function)
  15408. << New->getDeclName() << NewTy << OldTy
  15409. << New->getReturnTypeSourceRange();
  15410. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  15411. << Old->getReturnTypeSourceRange();
  15412. return true;
  15413. }
  15414. if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
  15415. // C++14 [class.virtual]p8:
  15416. // If the class type in the covariant return type of D::f differs from
  15417. // that of B::f, the class type in the return type of D::f shall be
  15418. // complete at the point of declaration of D::f or shall be the class
  15419. // type D.
  15420. if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
  15421. if (!RT->isBeingDefined() &&
  15422. RequireCompleteType(New->getLocation(), NewClassTy,
  15423. diag::err_covariant_return_incomplete,
  15424. New->getDeclName()))
  15425. return true;
  15426. }
  15427. // Check if the new class derives from the old class.
  15428. if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
  15429. Diag(New->getLocation(), diag::err_covariant_return_not_derived)
  15430. << New->getDeclName() << NewTy << OldTy
  15431. << New->getReturnTypeSourceRange();
  15432. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  15433. << Old->getReturnTypeSourceRange();
  15434. return true;
  15435. }
  15436. // Check if we the conversion from derived to base is valid.
  15437. if (CheckDerivedToBaseConversion(
  15438. NewClassTy, OldClassTy,
  15439. diag::err_covariant_return_inaccessible_base,
  15440. diag::err_covariant_return_ambiguous_derived_to_base_conv,
  15441. New->getLocation(), New->getReturnTypeSourceRange(),
  15442. New->getDeclName(), nullptr)) {
  15443. // FIXME: this note won't trigger for delayed access control
  15444. // diagnostics, and it's impossible to get an undelayed error
  15445. // here from access control during the original parse because
  15446. // the ParsingDeclSpec/ParsingDeclarator are still in scope.
  15447. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  15448. << Old->getReturnTypeSourceRange();
  15449. return true;
  15450. }
  15451. }
  15452. // The qualifiers of the return types must be the same.
  15453. if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
  15454. Diag(New->getLocation(),
  15455. diag::err_covariant_return_type_different_qualifications)
  15456. << New->getDeclName() << NewTy << OldTy
  15457. << New->getReturnTypeSourceRange();
  15458. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  15459. << Old->getReturnTypeSourceRange();
  15460. return true;
  15461. }
  15462. // The new class type must have the same or less qualifiers as the old type.
  15463. if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
  15464. Diag(New->getLocation(),
  15465. diag::err_covariant_return_type_class_type_more_qualified)
  15466. << New->getDeclName() << NewTy << OldTy
  15467. << New->getReturnTypeSourceRange();
  15468. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  15469. << Old->getReturnTypeSourceRange();
  15470. return true;
  15471. }
  15472. return false;
  15473. }
  15474. /// Mark the given method pure.
  15475. ///
  15476. /// \param Method the method to be marked pure.
  15477. ///
  15478. /// \param InitRange the source range that covers the "0" initializer.
  15479. bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
  15480. SourceLocation EndLoc = InitRange.getEnd();
  15481. if (EndLoc.isValid())
  15482. Method->setRangeEnd(EndLoc);
  15483. if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
  15484. Method->setPure();
  15485. return false;
  15486. }
  15487. if (!Method->isInvalidDecl())
  15488. Diag(Method->getLocation(), diag::err_non_virtual_pure)
  15489. << Method->getDeclName() << InitRange;
  15490. return true;
  15491. }
  15492. void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
  15493. if (D->getFriendObjectKind())
  15494. Diag(D->getLocation(), diag::err_pure_friend);
  15495. else if (auto *M = dyn_cast<CXXMethodDecl>(D))
  15496. CheckPureMethod(M, ZeroLoc);
  15497. else
  15498. Diag(D->getLocation(), diag::err_illegal_initializer);
  15499. }
  15500. /// Determine whether the given declaration is a global variable or
  15501. /// static data member.
  15502. static bool isNonlocalVariable(const Decl *D) {
  15503. if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
  15504. return Var->hasGlobalStorage();
  15505. return false;
  15506. }
  15507. /// Invoked when we are about to parse an initializer for the declaration
  15508. /// 'Dcl'.
  15509. ///
  15510. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
  15511. /// static data member of class X, names should be looked up in the scope of
  15512. /// class X. If the declaration had a scope specifier, a scope will have
  15513. /// been created and passed in for this purpose. Otherwise, S will be null.
  15514. void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
  15515. // If there is no declaration, there was an error parsing it.
  15516. if (!D || D->isInvalidDecl())
  15517. return;
  15518. // We will always have a nested name specifier here, but this declaration
  15519. // might not be out of line if the specifier names the current namespace:
  15520. // extern int n;
  15521. // int ::n = 0;
  15522. if (S && D->isOutOfLine())
  15523. EnterDeclaratorContext(S, D->getDeclContext());
  15524. // If we are parsing the initializer for a static data member, push a
  15525. // new expression evaluation context that is associated with this static
  15526. // data member.
  15527. if (isNonlocalVariable(D))
  15528. PushExpressionEvaluationContext(
  15529. ExpressionEvaluationContext::PotentiallyEvaluated, D);
  15530. }
  15531. /// Invoked after we are finished parsing an initializer for the declaration D.
  15532. void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
  15533. // If there is no declaration, there was an error parsing it.
  15534. if (!D || D->isInvalidDecl())
  15535. return;
  15536. if (isNonlocalVariable(D))
  15537. PopExpressionEvaluationContext();
  15538. if (S && D->isOutOfLine())
  15539. ExitDeclaratorContext(S);
  15540. }
  15541. /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
  15542. /// C++ if/switch/while/for statement.
  15543. /// e.g: "if (int x = f()) {...}"
  15544. DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
  15545. // C++ 6.4p2:
  15546. // The declarator shall not specify a function or an array.
  15547. // The type-specifier-seq shall not contain typedef and shall not declare a
  15548. // new class or enumeration.
  15549. assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  15550. "Parser allowed 'typedef' as storage class of condition decl.");
  15551. Decl *Dcl = ActOnDeclarator(S, D);
  15552. if (!Dcl)
  15553. return true;
  15554. if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
  15555. Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
  15556. << D.getSourceRange();
  15557. return true;
  15558. }
  15559. return Dcl;
  15560. }
  15561. void Sema::LoadExternalVTableUses() {
  15562. if (!ExternalSource)
  15563. return;
  15564. SmallVector<ExternalVTableUse, 4> VTables;
  15565. ExternalSource->ReadUsedVTables(VTables);
  15566. SmallVector<VTableUse, 4> NewUses;
  15567. for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
  15568. llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
  15569. = VTablesUsed.find(VTables[I].Record);
  15570. // Even if a definition wasn't required before, it may be required now.
  15571. if (Pos != VTablesUsed.end()) {
  15572. if (!Pos->second && VTables[I].DefinitionRequired)
  15573. Pos->second = true;
  15574. continue;
  15575. }
  15576. VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
  15577. NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
  15578. }
  15579. VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
  15580. }
  15581. void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
  15582. bool DefinitionRequired) {
  15583. // Ignore any vtable uses in unevaluated operands or for classes that do
  15584. // not have a vtable.
  15585. if (!Class->isDynamicClass() || Class->isDependentContext() ||
  15586. CurContext->isDependentContext() || isUnevaluatedContext())
  15587. return;
  15588. // Do not mark as used if compiling for the device outside of the target
  15589. // region.
  15590. if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  15591. !isInOpenMPDeclareTargetContext() &&
  15592. !isInOpenMPTargetExecutionDirective()) {
  15593. if (!DefinitionRequired)
  15594. MarkVirtualMembersReferenced(Loc, Class);
  15595. return;
  15596. }
  15597. // Try to insert this class into the map.
  15598. LoadExternalVTableUses();
  15599. Class = Class->getCanonicalDecl();
  15600. std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
  15601. Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
  15602. if (!Pos.second) {
  15603. // If we already had an entry, check to see if we are promoting this vtable
  15604. // to require a definition. If so, we need to reappend to the VTableUses
  15605. // list, since we may have already processed the first entry.
  15606. if (DefinitionRequired && !Pos.first->second) {
  15607. Pos.first->second = true;
  15608. } else {
  15609. // Otherwise, we can early exit.
  15610. return;
  15611. }
  15612. } else {
  15613. // The Microsoft ABI requires that we perform the destructor body
  15614. // checks (i.e. operator delete() lookup) when the vtable is marked used, as
  15615. // the deleting destructor is emitted with the vtable, not with the
  15616. // destructor definition as in the Itanium ABI.
  15617. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  15618. CXXDestructorDecl *DD = Class->getDestructor();
  15619. if (DD && DD->isVirtual() && !DD->isDeleted()) {
  15620. if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
  15621. // If this is an out-of-line declaration, marking it referenced will
  15622. // not do anything. Manually call CheckDestructor to look up operator
  15623. // delete().
  15624. ContextRAII SavedContext(*this, DD);
  15625. CheckDestructor(DD);
  15626. } else {
  15627. MarkFunctionReferenced(Loc, Class->getDestructor());
  15628. }
  15629. }
  15630. }
  15631. }
  15632. // Local classes need to have their virtual members marked
  15633. // immediately. For all other classes, we mark their virtual members
  15634. // at the end of the translation unit.
  15635. if (Class->isLocalClass())
  15636. MarkVirtualMembersReferenced(Loc, Class);
  15637. else
  15638. VTableUses.push_back(std::make_pair(Class, Loc));
  15639. }
  15640. bool Sema::DefineUsedVTables() {
  15641. LoadExternalVTableUses();
  15642. if (VTableUses.empty())
  15643. return false;
  15644. // Note: The VTableUses vector could grow as a result of marking
  15645. // the members of a class as "used", so we check the size each
  15646. // time through the loop and prefer indices (which are stable) to
  15647. // iterators (which are not).
  15648. bool DefinedAnything = false;
  15649. for (unsigned I = 0; I != VTableUses.size(); ++I) {
  15650. CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
  15651. if (!Class)
  15652. continue;
  15653. TemplateSpecializationKind ClassTSK =
  15654. Class->getTemplateSpecializationKind();
  15655. SourceLocation Loc = VTableUses[I].second;
  15656. bool DefineVTable = true;
  15657. // If this class has a key function, but that key function is
  15658. // defined in another translation unit, we don't need to emit the
  15659. // vtable even though we're using it.
  15660. const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
  15661. if (KeyFunction && !KeyFunction->hasBody()) {
  15662. // The key function is in another translation unit.
  15663. DefineVTable = false;
  15664. TemplateSpecializationKind TSK =
  15665. KeyFunction->getTemplateSpecializationKind();
  15666. assert(TSK != TSK_ExplicitInstantiationDefinition &&
  15667. TSK != TSK_ImplicitInstantiation &&
  15668. "Instantiations don't have key functions");
  15669. (void)TSK;
  15670. } else if (!KeyFunction) {
  15671. // If we have a class with no key function that is the subject
  15672. // of an explicit instantiation declaration, suppress the
  15673. // vtable; it will live with the explicit instantiation
  15674. // definition.
  15675. bool IsExplicitInstantiationDeclaration =
  15676. ClassTSK == TSK_ExplicitInstantiationDeclaration;
  15677. for (auto *R : Class->redecls()) {
  15678. TemplateSpecializationKind TSK
  15679. = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
  15680. if (TSK == TSK_ExplicitInstantiationDeclaration)
  15681. IsExplicitInstantiationDeclaration = true;
  15682. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  15683. IsExplicitInstantiationDeclaration = false;
  15684. break;
  15685. }
  15686. }
  15687. if (IsExplicitInstantiationDeclaration)
  15688. DefineVTable = false;
  15689. }
  15690. // The exception specifications for all virtual members may be needed even
  15691. // if we are not providing an authoritative form of the vtable in this TU.
  15692. // We may choose to emit it available_externally anyway.
  15693. if (!DefineVTable) {
  15694. MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
  15695. continue;
  15696. }
  15697. // Mark all of the virtual members of this class as referenced, so
  15698. // that we can build a vtable. Then, tell the AST consumer that a
  15699. // vtable for this class is required.
  15700. DefinedAnything = true;
  15701. MarkVirtualMembersReferenced(Loc, Class);
  15702. CXXRecordDecl *Canonical = Class->getCanonicalDecl();
  15703. if (VTablesUsed[Canonical])
  15704. Consumer.HandleVTable(Class);
  15705. // Warn if we're emitting a weak vtable. The vtable will be weak if there is
  15706. // no key function or the key function is inlined. Don't warn in C++ ABIs
  15707. // that lack key functions, since the user won't be able to make one.
  15708. if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
  15709. Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
  15710. ClassTSK != TSK_ExplicitInstantiationDefinition) {
  15711. const FunctionDecl *KeyFunctionDef = nullptr;
  15712. if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
  15713. KeyFunctionDef->isInlined()))
  15714. Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
  15715. }
  15716. }
  15717. VTableUses.clear();
  15718. return DefinedAnything;
  15719. }
  15720. void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
  15721. const CXXRecordDecl *RD) {
  15722. for (const auto *I : RD->methods())
  15723. if (I->isVirtual() && !I->isPure())
  15724. ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
  15725. }
  15726. void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
  15727. const CXXRecordDecl *RD,
  15728. bool ConstexprOnly) {
  15729. // Mark all functions which will appear in RD's vtable as used.
  15730. CXXFinalOverriderMap FinalOverriders;
  15731. RD->getFinalOverriders(FinalOverriders);
  15732. for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
  15733. E = FinalOverriders.end();
  15734. I != E; ++I) {
  15735. for (OverridingMethods::const_iterator OI = I->second.begin(),
  15736. OE = I->second.end();
  15737. OI != OE; ++OI) {
  15738. assert(OI->second.size() > 0 && "no final overrider");
  15739. CXXMethodDecl *Overrider = OI->second.front().Method;
  15740. // C++ [basic.def.odr]p2:
  15741. // [...] A virtual member function is used if it is not pure. [...]
  15742. if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
  15743. MarkFunctionReferenced(Loc, Overrider);
  15744. }
  15745. }
  15746. // Only classes that have virtual bases need a VTT.
  15747. if (RD->getNumVBases() == 0)
  15748. return;
  15749. for (const auto &I : RD->bases()) {
  15750. const auto *Base =
  15751. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  15752. if (Base->getNumVBases() == 0)
  15753. continue;
  15754. MarkVirtualMembersReferenced(Loc, Base);
  15755. }
  15756. }
  15757. /// SetIvarInitializers - This routine builds initialization ASTs for the
  15758. /// Objective-C implementation whose ivars need be initialized.
  15759. void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
  15760. if (!getLangOpts().CPlusPlus)
  15761. return;
  15762. if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
  15763. SmallVector<ObjCIvarDecl*, 8> ivars;
  15764. CollectIvarsToConstructOrDestruct(OID, ivars);
  15765. if (ivars.empty())
  15766. return;
  15767. SmallVector<CXXCtorInitializer*, 32> AllToInit;
  15768. for (unsigned i = 0; i < ivars.size(); i++) {
  15769. FieldDecl *Field = ivars[i];
  15770. if (Field->isInvalidDecl())
  15771. continue;
  15772. CXXCtorInitializer *Member;
  15773. InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
  15774. InitializationKind InitKind =
  15775. InitializationKind::CreateDefault(ObjCImplementation->getLocation());
  15776. InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt);
  15777. ExprResult MemberInit =
  15778. InitSeq.Perform(*this, InitEntity, InitKind, std::nullopt);
  15779. MemberInit = MaybeCreateExprWithCleanups(MemberInit);
  15780. // Note, MemberInit could actually come back empty if no initialization
  15781. // is required (e.g., because it would call a trivial default constructor)
  15782. if (!MemberInit.get() || MemberInit.isInvalid())
  15783. continue;
  15784. Member =
  15785. new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
  15786. SourceLocation(),
  15787. MemberInit.getAs<Expr>(),
  15788. SourceLocation());
  15789. AllToInit.push_back(Member);
  15790. // Be sure that the destructor is accessible and is marked as referenced.
  15791. if (const RecordType *RecordTy =
  15792. Context.getBaseElementType(Field->getType())
  15793. ->getAs<RecordType>()) {
  15794. CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  15795. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  15796. MarkFunctionReferenced(Field->getLocation(), Destructor);
  15797. CheckDestructorAccess(Field->getLocation(), Destructor,
  15798. PDiag(diag::err_access_dtor_ivar)
  15799. << Context.getBaseElementType(Field->getType()));
  15800. }
  15801. }
  15802. }
  15803. ObjCImplementation->setIvarInitializers(Context,
  15804. AllToInit.data(), AllToInit.size());
  15805. }
  15806. }
  15807. static
  15808. void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
  15809. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
  15810. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
  15811. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
  15812. Sema &S) {
  15813. if (Ctor->isInvalidDecl())
  15814. return;
  15815. CXXConstructorDecl *Target = Ctor->getTargetConstructor();
  15816. // Target may not be determinable yet, for instance if this is a dependent
  15817. // call in an uninstantiated template.
  15818. if (Target) {
  15819. const FunctionDecl *FNTarget = nullptr;
  15820. (void)Target->hasBody(FNTarget);
  15821. Target = const_cast<CXXConstructorDecl*>(
  15822. cast_or_null<CXXConstructorDecl>(FNTarget));
  15823. }
  15824. CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
  15825. // Avoid dereferencing a null pointer here.
  15826. *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
  15827. if (!Current.insert(Canonical).second)
  15828. return;
  15829. // We know that beyond here, we aren't chaining into a cycle.
  15830. if (!Target || !Target->isDelegatingConstructor() ||
  15831. Target->isInvalidDecl() || Valid.count(TCanonical)) {
  15832. Valid.insert(Current.begin(), Current.end());
  15833. Current.clear();
  15834. // We've hit a cycle.
  15835. } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
  15836. Current.count(TCanonical)) {
  15837. // If we haven't diagnosed this cycle yet, do so now.
  15838. if (!Invalid.count(TCanonical)) {
  15839. S.Diag((*Ctor->init_begin())->getSourceLocation(),
  15840. diag::warn_delegating_ctor_cycle)
  15841. << Ctor;
  15842. // Don't add a note for a function delegating directly to itself.
  15843. if (TCanonical != Canonical)
  15844. S.Diag(Target->getLocation(), diag::note_it_delegates_to);
  15845. CXXConstructorDecl *C = Target;
  15846. while (C->getCanonicalDecl() != Canonical) {
  15847. const FunctionDecl *FNTarget = nullptr;
  15848. (void)C->getTargetConstructor()->hasBody(FNTarget);
  15849. assert(FNTarget && "Ctor cycle through bodiless function");
  15850. C = const_cast<CXXConstructorDecl*>(
  15851. cast<CXXConstructorDecl>(FNTarget));
  15852. S.Diag(C->getLocation(), diag::note_which_delegates_to);
  15853. }
  15854. }
  15855. Invalid.insert(Current.begin(), Current.end());
  15856. Current.clear();
  15857. } else {
  15858. DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
  15859. }
  15860. }
  15861. void Sema::CheckDelegatingCtorCycles() {
  15862. llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
  15863. for (DelegatingCtorDeclsType::iterator
  15864. I = DelegatingCtorDecls.begin(ExternalSource.get()),
  15865. E = DelegatingCtorDecls.end();
  15866. I != E; ++I)
  15867. DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
  15868. for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
  15869. (*CI)->setInvalidDecl();
  15870. }
  15871. namespace {
  15872. /// AST visitor that finds references to the 'this' expression.
  15873. class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
  15874. Sema &S;
  15875. public:
  15876. explicit FindCXXThisExpr(Sema &S) : S(S) { }
  15877. bool VisitCXXThisExpr(CXXThisExpr *E) {
  15878. S.Diag(E->getLocation(), diag::err_this_static_member_func)
  15879. << E->isImplicit();
  15880. return false;
  15881. }
  15882. };
  15883. }
  15884. bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
  15885. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  15886. if (!TSInfo)
  15887. return false;
  15888. TypeLoc TL = TSInfo->getTypeLoc();
  15889. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  15890. if (!ProtoTL)
  15891. return false;
  15892. // C++11 [expr.prim.general]p3:
  15893. // [The expression this] shall not appear before the optional
  15894. // cv-qualifier-seq and it shall not appear within the declaration of a
  15895. // static member function (although its type and value category are defined
  15896. // within a static member function as they are within a non-static member
  15897. // function). [ Note: this is because declaration matching does not occur
  15898. // until the complete declarator is known. - end note ]
  15899. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  15900. FindCXXThisExpr Finder(*this);
  15901. // If the return type came after the cv-qualifier-seq, check it now.
  15902. if (Proto->hasTrailingReturn() &&
  15903. !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
  15904. return true;
  15905. // Check the exception specification.
  15906. if (checkThisInStaticMemberFunctionExceptionSpec(Method))
  15907. return true;
  15908. // Check the trailing requires clause
  15909. if (Expr *E = Method->getTrailingRequiresClause())
  15910. if (!Finder.TraverseStmt(E))
  15911. return true;
  15912. return checkThisInStaticMemberFunctionAttributes(Method);
  15913. }
  15914. bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
  15915. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  15916. if (!TSInfo)
  15917. return false;
  15918. TypeLoc TL = TSInfo->getTypeLoc();
  15919. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  15920. if (!ProtoTL)
  15921. return false;
  15922. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  15923. FindCXXThisExpr Finder(*this);
  15924. switch (Proto->getExceptionSpecType()) {
  15925. case EST_Unparsed:
  15926. case EST_Uninstantiated:
  15927. case EST_Unevaluated:
  15928. case EST_BasicNoexcept:
  15929. case EST_NoThrow:
  15930. case EST_DynamicNone:
  15931. case EST_MSAny:
  15932. case EST_None:
  15933. break;
  15934. case EST_DependentNoexcept:
  15935. case EST_NoexceptFalse:
  15936. case EST_NoexceptTrue:
  15937. if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
  15938. return true;
  15939. [[fallthrough]];
  15940. case EST_Dynamic:
  15941. for (const auto &E : Proto->exceptions()) {
  15942. if (!Finder.TraverseType(E))
  15943. return true;
  15944. }
  15945. break;
  15946. }
  15947. return false;
  15948. }
  15949. bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
  15950. FindCXXThisExpr Finder(*this);
  15951. // Check attributes.
  15952. for (const auto *A : Method->attrs()) {
  15953. // FIXME: This should be emitted by tblgen.
  15954. Expr *Arg = nullptr;
  15955. ArrayRef<Expr *> Args;
  15956. if (const auto *G = dyn_cast<GuardedByAttr>(A))
  15957. Arg = G->getArg();
  15958. else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
  15959. Arg = G->getArg();
  15960. else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
  15961. Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
  15962. else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
  15963. Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
  15964. else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
  15965. Arg = ETLF->getSuccessValue();
  15966. Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
  15967. } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
  15968. Arg = STLF->getSuccessValue();
  15969. Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
  15970. } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
  15971. Arg = LR->getArg();
  15972. else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
  15973. Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
  15974. else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
  15975. Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
  15976. else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
  15977. Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
  15978. else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
  15979. Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
  15980. else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
  15981. Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
  15982. if (Arg && !Finder.TraverseStmt(Arg))
  15983. return true;
  15984. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  15985. if (!Finder.TraverseStmt(Args[I]))
  15986. return true;
  15987. }
  15988. }
  15989. return false;
  15990. }
  15991. void Sema::checkExceptionSpecification(
  15992. bool IsTopLevel, ExceptionSpecificationType EST,
  15993. ArrayRef<ParsedType> DynamicExceptions,
  15994. ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
  15995. SmallVectorImpl<QualType> &Exceptions,
  15996. FunctionProtoType::ExceptionSpecInfo &ESI) {
  15997. Exceptions.clear();
  15998. ESI.Type = EST;
  15999. if (EST == EST_Dynamic) {
  16000. Exceptions.reserve(DynamicExceptions.size());
  16001. for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
  16002. // FIXME: Preserve type source info.
  16003. QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
  16004. if (IsTopLevel) {
  16005. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  16006. collectUnexpandedParameterPacks(ET, Unexpanded);
  16007. if (!Unexpanded.empty()) {
  16008. DiagnoseUnexpandedParameterPacks(
  16009. DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
  16010. Unexpanded);
  16011. continue;
  16012. }
  16013. }
  16014. // Check that the type is valid for an exception spec, and
  16015. // drop it if not.
  16016. if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
  16017. Exceptions.push_back(ET);
  16018. }
  16019. ESI.Exceptions = Exceptions;
  16020. return;
  16021. }
  16022. if (isComputedNoexcept(EST)) {
  16023. assert((NoexceptExpr->isTypeDependent() ||
  16024. NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
  16025. Context.BoolTy) &&
  16026. "Parser should have made sure that the expression is boolean");
  16027. if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
  16028. ESI.Type = EST_BasicNoexcept;
  16029. return;
  16030. }
  16031. ESI.NoexceptExpr = NoexceptExpr;
  16032. return;
  16033. }
  16034. }
  16035. void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
  16036. ExceptionSpecificationType EST,
  16037. SourceRange SpecificationRange,
  16038. ArrayRef<ParsedType> DynamicExceptions,
  16039. ArrayRef<SourceRange> DynamicExceptionRanges,
  16040. Expr *NoexceptExpr) {
  16041. if (!MethodD)
  16042. return;
  16043. // Dig out the method we're referring to.
  16044. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
  16045. MethodD = FunTmpl->getTemplatedDecl();
  16046. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
  16047. if (!Method)
  16048. return;
  16049. // Check the exception specification.
  16050. llvm::SmallVector<QualType, 4> Exceptions;
  16051. FunctionProtoType::ExceptionSpecInfo ESI;
  16052. checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
  16053. DynamicExceptionRanges, NoexceptExpr, Exceptions,
  16054. ESI);
  16055. // Update the exception specification on the function type.
  16056. Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
  16057. if (Method->isStatic())
  16058. checkThisInStaticMemberFunctionExceptionSpec(Method);
  16059. if (Method->isVirtual()) {
  16060. // Check overrides, which we previously had to delay.
  16061. for (const CXXMethodDecl *O : Method->overridden_methods())
  16062. CheckOverridingFunctionExceptionSpec(Method, O);
  16063. }
  16064. }
  16065. /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
  16066. ///
  16067. MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
  16068. SourceLocation DeclStart, Declarator &D,
  16069. Expr *BitWidth,
  16070. InClassInitStyle InitStyle,
  16071. AccessSpecifier AS,
  16072. const ParsedAttr &MSPropertyAttr) {
  16073. IdentifierInfo *II = D.getIdentifier();
  16074. if (!II) {
  16075. Diag(DeclStart, diag::err_anonymous_property);
  16076. return nullptr;
  16077. }
  16078. SourceLocation Loc = D.getIdentifierLoc();
  16079. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  16080. QualType T = TInfo->getType();
  16081. if (getLangOpts().CPlusPlus) {
  16082. CheckExtraCXXDefaultArguments(D);
  16083. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  16084. UPPC_DataMemberType)) {
  16085. D.setInvalidType();
  16086. T = Context.IntTy;
  16087. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  16088. }
  16089. }
  16090. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  16091. if (D.getDeclSpec().isInlineSpecified())
  16092. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  16093. << getLangOpts().CPlusPlus17;
  16094. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  16095. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  16096. diag::err_invalid_thread)
  16097. << DeclSpec::getSpecifierName(TSCS);
  16098. // Check to see if this name was declared as a member previously
  16099. NamedDecl *PrevDecl = nullptr;
  16100. LookupResult Previous(*this, II, Loc, LookupMemberName,
  16101. ForVisibleRedeclaration);
  16102. LookupName(Previous, S);
  16103. switch (Previous.getResultKind()) {
  16104. case LookupResult::Found:
  16105. case LookupResult::FoundUnresolvedValue:
  16106. PrevDecl = Previous.getAsSingle<NamedDecl>();
  16107. break;
  16108. case LookupResult::FoundOverloaded:
  16109. PrevDecl = Previous.getRepresentativeDecl();
  16110. break;
  16111. case LookupResult::NotFound:
  16112. case LookupResult::NotFoundInCurrentInstantiation:
  16113. case LookupResult::Ambiguous:
  16114. break;
  16115. }
  16116. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  16117. // Maybe we will complain about the shadowed template parameter.
  16118. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  16119. // Just pretend that we didn't see the previous declaration.
  16120. PrevDecl = nullptr;
  16121. }
  16122. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  16123. PrevDecl = nullptr;
  16124. SourceLocation TSSL = D.getBeginLoc();
  16125. MSPropertyDecl *NewPD =
  16126. MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
  16127. MSPropertyAttr.getPropertyDataGetter(),
  16128. MSPropertyAttr.getPropertyDataSetter());
  16129. ProcessDeclAttributes(TUScope, NewPD, D);
  16130. NewPD->setAccess(AS);
  16131. if (NewPD->isInvalidDecl())
  16132. Record->setInvalidDecl();
  16133. if (D.getDeclSpec().isModulePrivateSpecified())
  16134. NewPD->setModulePrivate();
  16135. if (NewPD->isInvalidDecl() && PrevDecl) {
  16136. // Don't introduce NewFD into scope; there's already something
  16137. // with the same name in the same scope.
  16138. } else if (II) {
  16139. PushOnScopeChains(NewPD, S);
  16140. } else
  16141. Record->addDecl(NewPD);
  16142. return NewPD;
  16143. }
  16144. void Sema::ActOnStartFunctionDeclarationDeclarator(
  16145. Declarator &Declarator, unsigned TemplateParameterDepth) {
  16146. auto &Info = InventedParameterInfos.emplace_back();
  16147. TemplateParameterList *ExplicitParams = nullptr;
  16148. ArrayRef<TemplateParameterList *> ExplicitLists =
  16149. Declarator.getTemplateParameterLists();
  16150. if (!ExplicitLists.empty()) {
  16151. bool IsMemberSpecialization, IsInvalid;
  16152. ExplicitParams = MatchTemplateParametersToScopeSpecifier(
  16153. Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
  16154. Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
  16155. ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
  16156. /*SuppressDiagnostic=*/true);
  16157. }
  16158. if (ExplicitParams) {
  16159. Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
  16160. llvm::append_range(Info.TemplateParams, *ExplicitParams);
  16161. Info.NumExplicitTemplateParams = ExplicitParams->size();
  16162. } else {
  16163. Info.AutoTemplateParameterDepth = TemplateParameterDepth;
  16164. Info.NumExplicitTemplateParams = 0;
  16165. }
  16166. }
  16167. void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
  16168. auto &FSI = InventedParameterInfos.back();
  16169. if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
  16170. if (FSI.NumExplicitTemplateParams != 0) {
  16171. TemplateParameterList *ExplicitParams =
  16172. Declarator.getTemplateParameterLists().back();
  16173. Declarator.setInventedTemplateParameterList(
  16174. TemplateParameterList::Create(
  16175. Context, ExplicitParams->getTemplateLoc(),
  16176. ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
  16177. ExplicitParams->getRAngleLoc(),
  16178. ExplicitParams->getRequiresClause()));
  16179. } else {
  16180. Declarator.setInventedTemplateParameterList(
  16181. TemplateParameterList::Create(
  16182. Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
  16183. SourceLocation(), /*RequiresClause=*/nullptr));
  16184. }
  16185. }
  16186. InventedParameterInfos.pop_back();
  16187. }