SemaDeclCXX.cpp 595 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741
  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/EvaluatedExprVisitor.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/RecordLayout.h"
  22. #include "clang/AST/RecursiveASTVisitor.h"
  23. #include "clang/AST/StmtVisitor.h"
  24. #include "clang/AST/TypeLoc.h"
  25. #include "clang/AST/TypeOrdering.h"
  26. #include "clang/Basic/PartialDiagnostic.h"
  27. #include "clang/Basic/TargetInfo.h"
  28. #include "clang/Lex/LiteralSupport.h"
  29. #include "clang/Lex/Preprocessor.h"
  30. #include "clang/Sema/CXXFieldCollector.h"
  31. #include "clang/Sema/DeclSpec.h"
  32. #include "clang/Sema/Initialization.h"
  33. #include "clang/Sema/Lookup.h"
  34. #include "clang/Sema/ParsedTemplate.h"
  35. #include "clang/Sema/Scope.h"
  36. #include "clang/Sema/ScopeInfo.h"
  37. #include "clang/Sema/SemaInternal.h"
  38. #include "clang/Sema/Template.h"
  39. #include "llvm/ADT/STLExtras.h"
  40. #include "llvm/ADT/SmallString.h"
  41. #include "llvm/ADT/StringExtras.h"
  42. #include <map>
  43. #include <set>
  44. using namespace clang;
  45. //===----------------------------------------------------------------------===//
  46. // CheckDefaultArgumentVisitor
  47. //===----------------------------------------------------------------------===//
  48. namespace {
  49. /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
  50. /// the default argument of a parameter to determine whether it
  51. /// contains any ill-formed subexpressions. For example, this will
  52. /// diagnose the use of local variables or parameters within the
  53. /// default argument expression.
  54. class CheckDefaultArgumentVisitor
  55. : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
  56. Expr *DefaultArg;
  57. Sema *S;
  58. public:
  59. CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
  60. : DefaultArg(defarg), S(s) {}
  61. bool VisitExpr(Expr *Node);
  62. bool VisitDeclRefExpr(DeclRefExpr *DRE);
  63. bool VisitCXXThisExpr(CXXThisExpr *ThisE);
  64. bool VisitLambdaExpr(LambdaExpr *Lambda);
  65. bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
  66. };
  67. /// VisitExpr - Visit all of the children of this expression.
  68. bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
  69. bool IsInvalid = false;
  70. for (Stmt *SubStmt : Node->children())
  71. IsInvalid |= Visit(SubStmt);
  72. return IsInvalid;
  73. }
  74. /// VisitDeclRefExpr - Visit a reference to a declaration, to
  75. /// determine whether this declaration can be used in the default
  76. /// argument expression.
  77. bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
  78. NamedDecl *Decl = DRE->getDecl();
  79. if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
  80. // C++ [dcl.fct.default]p9
  81. // Default arguments are evaluated each time the function is
  82. // called. The order of evaluation of function arguments is
  83. // unspecified. Consequently, parameters of a function shall not
  84. // be used in default argument expressions, even if they are not
  85. // evaluated. Parameters of a function declared before a default
  86. // argument expression are in scope and can hide namespace and
  87. // class member names.
  88. return S->Diag(DRE->getBeginLoc(),
  89. diag::err_param_default_argument_references_param)
  90. << Param->getDeclName() << DefaultArg->getSourceRange();
  91. } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
  92. // C++ [dcl.fct.default]p7
  93. // Local variables shall not be used in default argument
  94. // expressions.
  95. if (VDecl->isLocalVarDecl())
  96. return S->Diag(DRE->getBeginLoc(),
  97. diag::err_param_default_argument_references_local)
  98. << VDecl->getDeclName() << DefaultArg->getSourceRange();
  99. }
  100. return false;
  101. }
  102. /// VisitCXXThisExpr - Visit a C++ "this" expression.
  103. bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
  104. // C++ [dcl.fct.default]p8:
  105. // The keyword this shall not be used in a default argument of a
  106. // member function.
  107. return S->Diag(ThisE->getBeginLoc(),
  108. diag::err_param_default_argument_references_this)
  109. << ThisE->getSourceRange();
  110. }
  111. bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
  112. bool Invalid = false;
  113. for (PseudoObjectExpr::semantics_iterator
  114. i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
  115. Expr *E = *i;
  116. // Look through bindings.
  117. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  118. E = OVE->getSourceExpr();
  119. assert(E && "pseudo-object binding without source expression?");
  120. }
  121. Invalid |= Visit(E);
  122. }
  123. return Invalid;
  124. }
  125. bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
  126. // C++11 [expr.lambda.prim]p13:
  127. // A lambda-expression appearing in a default argument shall not
  128. // implicitly or explicitly capture any entity.
  129. if (Lambda->capture_begin() == Lambda->capture_end())
  130. return false;
  131. return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
  132. }
  133. }
  134. void
  135. Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
  136. const CXXMethodDecl *Method) {
  137. // If we have an MSAny spec already, don't bother.
  138. if (!Method || ComputedEST == EST_MSAny)
  139. return;
  140. const FunctionProtoType *Proto
  141. = Method->getType()->getAs<FunctionProtoType>();
  142. Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
  143. if (!Proto)
  144. return;
  145. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  146. // If we have a throw-all spec at this point, ignore the function.
  147. if (ComputedEST == EST_None)
  148. return;
  149. if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
  150. EST = EST_BasicNoexcept;
  151. switch (EST) {
  152. case EST_Unparsed:
  153. case EST_Uninstantiated:
  154. case EST_Unevaluated:
  155. llvm_unreachable("should not see unresolved exception specs here");
  156. // If this function can throw any exceptions, make a note of that.
  157. case EST_MSAny:
  158. case EST_None:
  159. // FIXME: Whichever we see last of MSAny and None determines our result.
  160. // We should make a consistent, order-independent choice here.
  161. ClearExceptions();
  162. ComputedEST = EST;
  163. return;
  164. case EST_NoexceptFalse:
  165. ClearExceptions();
  166. ComputedEST = EST_None;
  167. return;
  168. // FIXME: If the call to this decl is using any of its default arguments, we
  169. // need to search them for potentially-throwing calls.
  170. // If this function has a basic noexcept, it doesn't affect the outcome.
  171. case EST_BasicNoexcept:
  172. case EST_NoexceptTrue:
  173. case EST_NoThrow:
  174. return;
  175. // If we're still at noexcept(true) and there's a throw() callee,
  176. // change to that specification.
  177. case EST_DynamicNone:
  178. if (ComputedEST == EST_BasicNoexcept)
  179. ComputedEST = EST_DynamicNone;
  180. return;
  181. case EST_DependentNoexcept:
  182. llvm_unreachable(
  183. "should not generate implicit declarations for dependent cases");
  184. case EST_Dynamic:
  185. break;
  186. }
  187. assert(EST == EST_Dynamic && "EST case not considered earlier.");
  188. assert(ComputedEST != EST_None &&
  189. "Shouldn't collect exceptions when throw-all is guaranteed.");
  190. ComputedEST = EST_Dynamic;
  191. // Record the exceptions in this function's exception specification.
  192. for (const auto &E : Proto->exceptions())
  193. if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
  194. Exceptions.push_back(E);
  195. }
  196. void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
  197. if (!E || ComputedEST == EST_MSAny)
  198. return;
  199. // FIXME:
  200. //
  201. // C++0x [except.spec]p14:
  202. // [An] implicit exception-specification specifies the type-id T if and
  203. // only if T is allowed by the exception-specification of a function directly
  204. // invoked by f's implicit definition; f shall allow all exceptions if any
  205. // function it directly invokes allows all exceptions, and f shall allow no
  206. // exceptions if every function it directly invokes allows no exceptions.
  207. //
  208. // Note in particular that if an implicit exception-specification is generated
  209. // for a function containing a throw-expression, that specification can still
  210. // be noexcept(true).
  211. //
  212. // Note also that 'directly invoked' is not defined in the standard, and there
  213. // is no indication that we should only consider potentially-evaluated calls.
  214. //
  215. // Ultimately we should implement the intent of the standard: the exception
  216. // specification should be the set of exceptions which can be thrown by the
  217. // implicit definition. For now, we assume that any non-nothrow expression can
  218. // throw any exception.
  219. if (Self->canThrow(E))
  220. ComputedEST = EST_None;
  221. }
  222. bool
  223. Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
  224. SourceLocation EqualLoc) {
  225. if (RequireCompleteType(Param->getLocation(), Param->getType(),
  226. diag::err_typecheck_decl_incomplete_type)) {
  227. Param->setInvalidDecl();
  228. return true;
  229. }
  230. // C++ [dcl.fct.default]p5
  231. // A default argument expression is implicitly converted (clause
  232. // 4) to the parameter type. The default argument expression has
  233. // the same semantic constraints as the initializer expression in
  234. // a declaration of a variable of the parameter type, using the
  235. // copy-initialization semantics (8.5).
  236. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  237. Param);
  238. InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
  239. EqualLoc);
  240. InitializationSequence InitSeq(*this, Entity, Kind, Arg);
  241. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
  242. if (Result.isInvalid())
  243. return true;
  244. Arg = Result.getAs<Expr>();
  245. CheckCompletedExpr(Arg, EqualLoc);
  246. Arg = MaybeCreateExprWithCleanups(Arg);
  247. // Okay: add the default argument to the parameter
  248. Param->setDefaultArg(Arg);
  249. // We have already instantiated this parameter; provide each of the
  250. // instantiations with the uninstantiated default argument.
  251. UnparsedDefaultArgInstantiationsMap::iterator InstPos
  252. = UnparsedDefaultArgInstantiations.find(Param);
  253. if (InstPos != UnparsedDefaultArgInstantiations.end()) {
  254. for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
  255. InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
  256. // We're done tracking this parameter's instantiations.
  257. UnparsedDefaultArgInstantiations.erase(InstPos);
  258. }
  259. return false;
  260. }
  261. /// ActOnParamDefaultArgument - Check whether the default argument
  262. /// provided for a function parameter is well-formed. If so, attach it
  263. /// to the parameter declaration.
  264. void
  265. Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
  266. Expr *DefaultArg) {
  267. if (!param || !DefaultArg)
  268. return;
  269. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  270. UnparsedDefaultArgLocs.erase(Param);
  271. // Default arguments are only permitted in C++
  272. if (!getLangOpts().CPlusPlus) {
  273. Diag(EqualLoc, diag::err_param_default_argument)
  274. << DefaultArg->getSourceRange();
  275. Param->setInvalidDecl();
  276. return;
  277. }
  278. // Check for unexpanded parameter packs.
  279. if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
  280. Param->setInvalidDecl();
  281. return;
  282. }
  283. // C++11 [dcl.fct.default]p3
  284. // A default argument expression [...] shall not be specified for a
  285. // parameter pack.
  286. if (Param->isParameterPack()) {
  287. Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
  288. << DefaultArg->getSourceRange();
  289. return;
  290. }
  291. // Check that the default argument is well-formed
  292. CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
  293. if (DefaultArgChecker.Visit(DefaultArg)) {
  294. Param->setInvalidDecl();
  295. return;
  296. }
  297. SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
  298. }
  299. /// ActOnParamUnparsedDefaultArgument - We've seen a default
  300. /// argument for a function parameter, but we can't parse it yet
  301. /// because we're inside a class definition. Note that this default
  302. /// argument will be parsed later.
  303. void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
  304. SourceLocation EqualLoc,
  305. SourceLocation ArgLoc) {
  306. if (!param)
  307. return;
  308. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  309. Param->setUnparsedDefaultArg();
  310. UnparsedDefaultArgLocs[Param] = ArgLoc;
  311. }
  312. /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
  313. /// the default argument for the parameter param failed.
  314. void Sema::ActOnParamDefaultArgumentError(Decl *param,
  315. SourceLocation EqualLoc) {
  316. if (!param)
  317. return;
  318. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  319. Param->setInvalidDecl();
  320. UnparsedDefaultArgLocs.erase(Param);
  321. Param->setDefaultArg(new(Context)
  322. OpaqueValueExpr(EqualLoc,
  323. Param->getType().getNonReferenceType(),
  324. VK_RValue));
  325. }
  326. /// CheckExtraCXXDefaultArguments - Check for any extra default
  327. /// arguments in the declarator, which is not a function declaration
  328. /// or definition and therefore is not permitted to have default
  329. /// arguments. This routine should be invoked for every declarator
  330. /// that is not a function declaration or definition.
  331. void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
  332. // C++ [dcl.fct.default]p3
  333. // A default argument expression shall be specified only in the
  334. // parameter-declaration-clause of a function declaration or in a
  335. // template-parameter (14.1). It shall not be specified for a
  336. // parameter pack. If it is specified in a
  337. // parameter-declaration-clause, it shall not occur within a
  338. // declarator or abstract-declarator of a parameter-declaration.
  339. bool MightBeFunction = D.isFunctionDeclarationContext();
  340. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  341. DeclaratorChunk &chunk = D.getTypeObject(i);
  342. if (chunk.Kind == DeclaratorChunk::Function) {
  343. if (MightBeFunction) {
  344. // This is a function declaration. It can have default arguments, but
  345. // keep looking in case its return type is a function type with default
  346. // arguments.
  347. MightBeFunction = false;
  348. continue;
  349. }
  350. for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
  351. ++argIdx) {
  352. ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
  353. if (Param->hasUnparsedDefaultArg()) {
  354. std::unique_ptr<CachedTokens> Toks =
  355. std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
  356. SourceRange SR;
  357. if (Toks->size() > 1)
  358. SR = SourceRange((*Toks)[1].getLocation(),
  359. Toks->back().getLocation());
  360. else
  361. SR = UnparsedDefaultArgLocs[Param];
  362. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  363. << SR;
  364. } else if (Param->getDefaultArg()) {
  365. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  366. << Param->getDefaultArg()->getSourceRange();
  367. Param->setDefaultArg(nullptr);
  368. }
  369. }
  370. } else if (chunk.Kind != DeclaratorChunk::Paren) {
  371. MightBeFunction = false;
  372. }
  373. }
  374. }
  375. static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
  376. for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
  377. const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
  378. if (!PVD->hasDefaultArg())
  379. return false;
  380. if (!PVD->hasInheritedDefaultArg())
  381. return true;
  382. }
  383. return false;
  384. }
  385. /// MergeCXXFunctionDecl - Merge two declarations of the same C++
  386. /// function, once we already know that they have the same
  387. /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
  388. /// error, false otherwise.
  389. bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
  390. Scope *S) {
  391. bool Invalid = false;
  392. // The declaration context corresponding to the scope is the semantic
  393. // parent, unless this is a local function declaration, in which case
  394. // it is that surrounding function.
  395. DeclContext *ScopeDC = New->isLocalExternDecl()
  396. ? New->getLexicalDeclContext()
  397. : New->getDeclContext();
  398. // Find the previous declaration for the purpose of default arguments.
  399. FunctionDecl *PrevForDefaultArgs = Old;
  400. for (/**/; PrevForDefaultArgs;
  401. // Don't bother looking back past the latest decl if this is a local
  402. // extern declaration; nothing else could work.
  403. PrevForDefaultArgs = New->isLocalExternDecl()
  404. ? nullptr
  405. : PrevForDefaultArgs->getPreviousDecl()) {
  406. // Ignore hidden declarations.
  407. if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
  408. continue;
  409. if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
  410. !New->isCXXClassMember()) {
  411. // Ignore default arguments of old decl if they are not in
  412. // the same scope and this is not an out-of-line definition of
  413. // a member function.
  414. continue;
  415. }
  416. if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
  417. // If only one of these is a local function declaration, then they are
  418. // declared in different scopes, even though isDeclInScope may think
  419. // they're in the same scope. (If both are local, the scope check is
  420. // sufficient, and if neither is local, then they are in the same scope.)
  421. continue;
  422. }
  423. // We found the right previous declaration.
  424. break;
  425. }
  426. // C++ [dcl.fct.default]p4:
  427. // For non-template functions, default arguments can be added in
  428. // later declarations of a function in the same
  429. // scope. Declarations in different scopes have completely
  430. // distinct sets of default arguments. That is, declarations in
  431. // inner scopes do not acquire default arguments from
  432. // declarations in outer scopes, and vice versa. In a given
  433. // function declaration, all parameters subsequent to a
  434. // parameter with a default argument shall have default
  435. // arguments supplied in this or previous declarations. A
  436. // default argument shall not be redefined by a later
  437. // declaration (not even to the same value).
  438. //
  439. // C++ [dcl.fct.default]p6:
  440. // Except for member functions of class templates, the default arguments
  441. // in a member function definition that appears outside of the class
  442. // definition are added to the set of default arguments provided by the
  443. // member function declaration in the class definition.
  444. for (unsigned p = 0, NumParams = PrevForDefaultArgs
  445. ? PrevForDefaultArgs->getNumParams()
  446. : 0;
  447. p < NumParams; ++p) {
  448. ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
  449. ParmVarDecl *NewParam = New->getParamDecl(p);
  450. bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
  451. bool NewParamHasDfl = NewParam->hasDefaultArg();
  452. if (OldParamHasDfl && NewParamHasDfl) {
  453. unsigned DiagDefaultParamID =
  454. diag::err_param_default_argument_redefinition;
  455. // MSVC accepts that default parameters be redefined for member functions
  456. // of template class. The new default parameter's value is ignored.
  457. Invalid = true;
  458. if (getLangOpts().MicrosoftExt) {
  459. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
  460. if (MD && MD->getParent()->getDescribedClassTemplate()) {
  461. // Merge the old default argument into the new parameter.
  462. NewParam->setHasInheritedDefaultArg();
  463. if (OldParam->hasUninstantiatedDefaultArg())
  464. NewParam->setUninstantiatedDefaultArg(
  465. OldParam->getUninstantiatedDefaultArg());
  466. else
  467. NewParam->setDefaultArg(OldParam->getInit());
  468. DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
  469. Invalid = false;
  470. }
  471. }
  472. // FIXME: If we knew where the '=' was, we could easily provide a fix-it
  473. // hint here. Alternatively, we could walk the type-source information
  474. // for NewParam to find the last source location in the type... but it
  475. // isn't worth the effort right now. This is the kind of test case that
  476. // is hard to get right:
  477. // int f(int);
  478. // void g(int (*fp)(int) = f);
  479. // void g(int (*fp)(int) = &f);
  480. Diag(NewParam->getLocation(), DiagDefaultParamID)
  481. << NewParam->getDefaultArgRange();
  482. // Look for the function declaration where the default argument was
  483. // actually written, which may be a declaration prior to Old.
  484. for (auto Older = PrevForDefaultArgs;
  485. OldParam->hasInheritedDefaultArg(); /**/) {
  486. Older = Older->getPreviousDecl();
  487. OldParam = Older->getParamDecl(p);
  488. }
  489. Diag(OldParam->getLocation(), diag::note_previous_definition)
  490. << OldParam->getDefaultArgRange();
  491. } else if (OldParamHasDfl) {
  492. // Merge the old default argument into the new parameter unless the new
  493. // function is a friend declaration in a template class. In the latter
  494. // case the default arguments will be inherited when the friend
  495. // declaration will be instantiated.
  496. if (New->getFriendObjectKind() == Decl::FOK_None ||
  497. !New->getLexicalDeclContext()->isDependentContext()) {
  498. // It's important to use getInit() here; getDefaultArg()
  499. // strips off any top-level ExprWithCleanups.
  500. NewParam->setHasInheritedDefaultArg();
  501. if (OldParam->hasUnparsedDefaultArg())
  502. NewParam->setUnparsedDefaultArg();
  503. else if (OldParam->hasUninstantiatedDefaultArg())
  504. NewParam->setUninstantiatedDefaultArg(
  505. OldParam->getUninstantiatedDefaultArg());
  506. else
  507. NewParam->setDefaultArg(OldParam->getInit());
  508. }
  509. } else if (NewParamHasDfl) {
  510. if (New->getDescribedFunctionTemplate()) {
  511. // Paragraph 4, quoted above, only applies to non-template functions.
  512. Diag(NewParam->getLocation(),
  513. diag::err_param_default_argument_template_redecl)
  514. << NewParam->getDefaultArgRange();
  515. Diag(PrevForDefaultArgs->getLocation(),
  516. diag::note_template_prev_declaration)
  517. << false;
  518. } else if (New->getTemplateSpecializationKind()
  519. != TSK_ImplicitInstantiation &&
  520. New->getTemplateSpecializationKind() != TSK_Undeclared) {
  521. // C++ [temp.expr.spec]p21:
  522. // Default function arguments shall not be specified in a declaration
  523. // or a definition for one of the following explicit specializations:
  524. // - the explicit specialization of a function template;
  525. // - the explicit specialization of a member function template;
  526. // - the explicit specialization of a member function of a class
  527. // template where the class template specialization to which the
  528. // member function specialization belongs is implicitly
  529. // instantiated.
  530. Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
  531. << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
  532. << New->getDeclName()
  533. << NewParam->getDefaultArgRange();
  534. } else if (New->getDeclContext()->isDependentContext()) {
  535. // C++ [dcl.fct.default]p6 (DR217):
  536. // Default arguments for a member function of a class template shall
  537. // be specified on the initial declaration of the member function
  538. // within the class template.
  539. //
  540. // Reading the tea leaves a bit in DR217 and its reference to DR205
  541. // leads me to the conclusion that one cannot add default function
  542. // arguments for an out-of-line definition of a member function of a
  543. // dependent type.
  544. int WhichKind = 2;
  545. if (CXXRecordDecl *Record
  546. = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
  547. if (Record->getDescribedClassTemplate())
  548. WhichKind = 0;
  549. else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
  550. WhichKind = 1;
  551. else
  552. WhichKind = 2;
  553. }
  554. Diag(NewParam->getLocation(),
  555. diag::err_param_default_argument_member_template_redecl)
  556. << WhichKind
  557. << NewParam->getDefaultArgRange();
  558. }
  559. }
  560. }
  561. // DR1344: If a default argument is added outside a class definition and that
  562. // default argument makes the function a special member function, the program
  563. // is ill-formed. This can only happen for constructors.
  564. if (isa<CXXConstructorDecl>(New) &&
  565. New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
  566. CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
  567. OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
  568. if (NewSM != OldSM) {
  569. ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
  570. assert(NewParam->hasDefaultArg());
  571. Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
  572. << NewParam->getDefaultArgRange() << NewSM;
  573. Diag(Old->getLocation(), diag::note_previous_declaration);
  574. }
  575. }
  576. const FunctionDecl *Def;
  577. // C++11 [dcl.constexpr]p1: If any declaration of a function or function
  578. // template has a constexpr specifier then all its declarations shall
  579. // contain the constexpr specifier.
  580. if (New->getConstexprKind() != Old->getConstexprKind()) {
  581. Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
  582. << New << New->getConstexprKind() << Old->getConstexprKind();
  583. Diag(Old->getLocation(), diag::note_previous_declaration);
  584. Invalid = true;
  585. } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
  586. Old->isDefined(Def) &&
  587. // If a friend function is inlined but does not have 'inline'
  588. // specifier, it is a definition. Do not report attribute conflict
  589. // in this case, redefinition will be diagnosed later.
  590. (New->isInlineSpecified() ||
  591. New->getFriendObjectKind() == Decl::FOK_None)) {
  592. // C++11 [dcl.fcn.spec]p4:
  593. // If the definition of a function appears in a translation unit before its
  594. // first declaration as inline, the program is ill-formed.
  595. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  596. Diag(Def->getLocation(), diag::note_previous_definition);
  597. Invalid = true;
  598. }
  599. // C++17 [temp.deduct.guide]p3:
  600. // Two deduction guide declarations in the same translation unit
  601. // for the same class template shall not have equivalent
  602. // parameter-declaration-clauses.
  603. if (isa<CXXDeductionGuideDecl>(New) &&
  604. !New->isFunctionTemplateSpecialization()) {
  605. Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
  606. Diag(Old->getLocation(), diag::note_previous_declaration);
  607. }
  608. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
  609. // argument expression, that declaration shall be a definition and shall be
  610. // the only declaration of the function or function template in the
  611. // translation unit.
  612. if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
  613. functionDeclHasDefaultArgument(Old)) {
  614. Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  615. Diag(Old->getLocation(), diag::note_previous_declaration);
  616. Invalid = true;
  617. }
  618. return Invalid;
  619. }
  620. NamedDecl *
  621. Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
  622. MultiTemplateParamsArg TemplateParamLists) {
  623. assert(D.isDecompositionDeclarator());
  624. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  625. // The syntax only allows a decomposition declarator as a simple-declaration,
  626. // a for-range-declaration, or a condition in Clang, but we parse it in more
  627. // cases than that.
  628. if (!D.mayHaveDecompositionDeclarator()) {
  629. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  630. << Decomp.getSourceRange();
  631. return nullptr;
  632. }
  633. if (!TemplateParamLists.empty()) {
  634. // FIXME: There's no rule against this, but there are also no rules that
  635. // would actually make it usable, so we reject it for now.
  636. Diag(TemplateParamLists.front()->getTemplateLoc(),
  637. diag::err_decomp_decl_template);
  638. return nullptr;
  639. }
  640. Diag(Decomp.getLSquareLoc(),
  641. !getLangOpts().CPlusPlus17
  642. ? diag::ext_decomp_decl
  643. : D.getContext() == DeclaratorContext::ConditionContext
  644. ? diag::ext_decomp_decl_cond
  645. : diag::warn_cxx14_compat_decomp_decl)
  646. << Decomp.getSourceRange();
  647. // The semantic context is always just the current context.
  648. DeclContext *const DC = CurContext;
  649. // C++17 [dcl.dcl]/8:
  650. // The decl-specifier-seq shall contain only the type-specifier auto
  651. // and cv-qualifiers.
  652. // C++2a [dcl.dcl]/8:
  653. // If decl-specifier-seq contains any decl-specifier other than static,
  654. // thread_local, auto, or cv-qualifiers, the program is ill-formed.
  655. auto &DS = D.getDeclSpec();
  656. {
  657. SmallVector<StringRef, 8> BadSpecifiers;
  658. SmallVector<SourceLocation, 8> BadSpecifierLocs;
  659. SmallVector<StringRef, 8> CPlusPlus20Specifiers;
  660. SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
  661. if (auto SCS = DS.getStorageClassSpec()) {
  662. if (SCS == DeclSpec::SCS_static) {
  663. CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
  664. CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
  665. } else {
  666. BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
  667. BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
  668. }
  669. }
  670. if (auto TSCS = DS.getThreadStorageClassSpec()) {
  671. CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
  672. CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
  673. }
  674. if (DS.hasConstexprSpecifier()) {
  675. BadSpecifiers.push_back(
  676. DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
  677. BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
  678. }
  679. if (DS.isInlineSpecified()) {
  680. BadSpecifiers.push_back("inline");
  681. BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
  682. }
  683. if (!BadSpecifiers.empty()) {
  684. auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
  685. Err << (int)BadSpecifiers.size()
  686. << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
  687. // Don't add FixItHints to remove the specifiers; we do still respect
  688. // them when building the underlying variable.
  689. for (auto Loc : BadSpecifierLocs)
  690. Err << SourceRange(Loc, Loc);
  691. } else if (!CPlusPlus20Specifiers.empty()) {
  692. auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
  693. getLangOpts().CPlusPlus2a
  694. ? diag::warn_cxx17_compat_decomp_decl_spec
  695. : diag::ext_decomp_decl_spec);
  696. Warn << (int)CPlusPlus20Specifiers.size()
  697. << llvm::join(CPlusPlus20Specifiers.begin(),
  698. CPlusPlus20Specifiers.end(), " ");
  699. for (auto Loc : CPlusPlus20SpecifierLocs)
  700. Warn << SourceRange(Loc, Loc);
  701. }
  702. // We can't recover from it being declared as a typedef.
  703. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  704. return nullptr;
  705. }
  706. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  707. QualType R = TInfo->getType();
  708. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  709. UPPC_DeclarationType))
  710. D.setInvalidType();
  711. // The syntax only allows a single ref-qualifier prior to the decomposition
  712. // declarator. No other declarator chunks are permitted. Also check the type
  713. // specifier here.
  714. if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
  715. D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
  716. (D.getNumTypeObjects() == 1 &&
  717. D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
  718. Diag(Decomp.getLSquareLoc(),
  719. (D.hasGroupingParens() ||
  720. (D.getNumTypeObjects() &&
  721. D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
  722. ? diag::err_decomp_decl_parens
  723. : diag::err_decomp_decl_type)
  724. << R;
  725. // In most cases, there's no actual problem with an explicitly-specified
  726. // type, but a function type won't work here, and ActOnVariableDeclarator
  727. // shouldn't be called for such a type.
  728. if (R->isFunctionType())
  729. D.setInvalidType();
  730. }
  731. // Build the BindingDecls.
  732. SmallVector<BindingDecl*, 8> Bindings;
  733. // Build the BindingDecls.
  734. for (auto &B : D.getDecompositionDeclarator().bindings()) {
  735. // Check for name conflicts.
  736. DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
  737. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  738. ForVisibleRedeclaration);
  739. LookupName(Previous, S,
  740. /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
  741. // It's not permitted to shadow a template parameter name.
  742. if (Previous.isSingleResult() &&
  743. Previous.getFoundDecl()->isTemplateParameter()) {
  744. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  745. Previous.getFoundDecl());
  746. Previous.clear();
  747. }
  748. bool ConsiderLinkage = DC->isFunctionOrMethod() &&
  749. DS.getStorageClassSpec() == DeclSpec::SCS_extern;
  750. FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
  751. /*AllowInlineNamespace*/false);
  752. if (!Previous.empty()) {
  753. auto *Old = Previous.getRepresentativeDecl();
  754. Diag(B.NameLoc, diag::err_redefinition) << B.Name;
  755. Diag(Old->getLocation(), diag::note_previous_definition);
  756. }
  757. auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
  758. PushOnScopeChains(BD, S, true);
  759. Bindings.push_back(BD);
  760. ParsingInitForAutoVars.insert(BD);
  761. }
  762. // There are no prior lookup results for the variable itself, because it
  763. // is unnamed.
  764. DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
  765. Decomp.getLSquareLoc());
  766. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  767. ForVisibleRedeclaration);
  768. // Build the variable that holds the non-decomposed object.
  769. bool AddToScope = true;
  770. NamedDecl *New =
  771. ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
  772. MultiTemplateParamsArg(), AddToScope, Bindings);
  773. if (AddToScope) {
  774. S->AddDecl(New);
  775. CurContext->addHiddenDecl(New);
  776. }
  777. if (isInOpenMPDeclareTargetContext())
  778. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  779. return New;
  780. }
  781. static bool checkSimpleDecomposition(
  782. Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
  783. QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
  784. llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
  785. if ((int64_t)Bindings.size() != NumElems) {
  786. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  787. << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
  788. << (NumElems < Bindings.size());
  789. return true;
  790. }
  791. unsigned I = 0;
  792. for (auto *B : Bindings) {
  793. SourceLocation Loc = B->getLocation();
  794. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  795. if (E.isInvalid())
  796. return true;
  797. E = GetInit(Loc, E.get(), I++);
  798. if (E.isInvalid())
  799. return true;
  800. B->setBinding(ElemType, E.get());
  801. }
  802. return false;
  803. }
  804. static bool checkArrayLikeDecomposition(Sema &S,
  805. ArrayRef<BindingDecl *> Bindings,
  806. ValueDecl *Src, QualType DecompType,
  807. const llvm::APSInt &NumElems,
  808. QualType ElemType) {
  809. return checkSimpleDecomposition(
  810. S, Bindings, Src, DecompType, NumElems, ElemType,
  811. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  812. ExprResult E = S.ActOnIntegerConstant(Loc, I);
  813. if (E.isInvalid())
  814. return ExprError();
  815. return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
  816. });
  817. }
  818. static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  819. ValueDecl *Src, QualType DecompType,
  820. const ConstantArrayType *CAT) {
  821. return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
  822. llvm::APSInt(CAT->getSize()),
  823. CAT->getElementType());
  824. }
  825. static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  826. ValueDecl *Src, QualType DecompType,
  827. const VectorType *VT) {
  828. return checkArrayLikeDecomposition(
  829. S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
  830. S.Context.getQualifiedType(VT->getElementType(),
  831. DecompType.getQualifiers()));
  832. }
  833. static bool checkComplexDecomposition(Sema &S,
  834. ArrayRef<BindingDecl *> Bindings,
  835. ValueDecl *Src, QualType DecompType,
  836. const ComplexType *CT) {
  837. return checkSimpleDecomposition(
  838. S, Bindings, Src, DecompType, llvm::APSInt::get(2),
  839. S.Context.getQualifiedType(CT->getElementType(),
  840. DecompType.getQualifiers()),
  841. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  842. return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
  843. });
  844. }
  845. static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
  846. TemplateArgumentListInfo &Args) {
  847. SmallString<128> SS;
  848. llvm::raw_svector_ostream OS(SS);
  849. bool First = true;
  850. for (auto &Arg : Args.arguments()) {
  851. if (!First)
  852. OS << ", ";
  853. Arg.getArgument().print(PrintingPolicy, OS);
  854. First = false;
  855. }
  856. return OS.str();
  857. }
  858. static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
  859. SourceLocation Loc, StringRef Trait,
  860. TemplateArgumentListInfo &Args,
  861. unsigned DiagID) {
  862. auto DiagnoseMissing = [&] {
  863. if (DiagID)
  864. S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
  865. Args);
  866. return true;
  867. };
  868. // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
  869. NamespaceDecl *Std = S.getStdNamespace();
  870. if (!Std)
  871. return DiagnoseMissing();
  872. // Look up the trait itself, within namespace std. We can diagnose various
  873. // problems with this lookup even if we've been asked to not diagnose a
  874. // missing specialization, because this can only fail if the user has been
  875. // declaring their own names in namespace std or we don't support the
  876. // standard library implementation in use.
  877. LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
  878. Loc, Sema::LookupOrdinaryName);
  879. if (!S.LookupQualifiedName(Result, Std))
  880. return DiagnoseMissing();
  881. if (Result.isAmbiguous())
  882. return true;
  883. ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
  884. if (!TraitTD) {
  885. Result.suppressDiagnostics();
  886. NamedDecl *Found = *Result.begin();
  887. S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
  888. S.Diag(Found->getLocation(), diag::note_declared_at);
  889. return true;
  890. }
  891. // Build the template-id.
  892. QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
  893. if (TraitTy.isNull())
  894. return true;
  895. if (!S.isCompleteType(Loc, TraitTy)) {
  896. if (DiagID)
  897. S.RequireCompleteType(
  898. Loc, TraitTy, DiagID,
  899. printTemplateArgs(S.Context.getPrintingPolicy(), Args));
  900. return true;
  901. }
  902. CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
  903. assert(RD && "specialization of class template is not a class?");
  904. // Look up the member of the trait type.
  905. S.LookupQualifiedName(TraitMemberLookup, RD);
  906. return TraitMemberLookup.isAmbiguous();
  907. }
  908. static TemplateArgumentLoc
  909. getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
  910. uint64_t I) {
  911. TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
  912. return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
  913. }
  914. static TemplateArgumentLoc
  915. getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
  916. return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
  917. }
  918. namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
  919. static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
  920. llvm::APSInt &Size) {
  921. EnterExpressionEvaluationContext ContextRAII(
  922. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  923. DeclarationName Value = S.PP.getIdentifierInfo("value");
  924. LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
  925. // Form template argument list for tuple_size<T>.
  926. TemplateArgumentListInfo Args(Loc, Loc);
  927. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  928. // If there's no tuple_size specialization, it's not tuple-like.
  929. if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
  930. return IsTupleLike::NotTupleLike;
  931. // If we get this far, we've committed to the tuple interpretation, but
  932. // we can still fail if there actually isn't a usable ::value.
  933. struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
  934. LookupResult &R;
  935. TemplateArgumentListInfo &Args;
  936. ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
  937. : R(R), Args(Args) {}
  938. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
  939. S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
  940. << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
  941. }
  942. } Diagnoser(R, Args);
  943. if (R.empty()) {
  944. Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
  945. return IsTupleLike::Error;
  946. }
  947. ExprResult E =
  948. S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
  949. if (E.isInvalid())
  950. return IsTupleLike::Error;
  951. E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
  952. if (E.isInvalid())
  953. return IsTupleLike::Error;
  954. return IsTupleLike::TupleLike;
  955. }
  956. /// \return std::tuple_element<I, T>::type.
  957. static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
  958. unsigned I, QualType T) {
  959. // Form template argument list for tuple_element<I, T>.
  960. TemplateArgumentListInfo Args(Loc, Loc);
  961. Args.addArgument(
  962. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  963. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  964. DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
  965. LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
  966. if (lookupStdTypeTraitMember(
  967. S, R, Loc, "tuple_element", Args,
  968. diag::err_decomp_decl_std_tuple_element_not_specialized))
  969. return QualType();
  970. auto *TD = R.getAsSingle<TypeDecl>();
  971. if (!TD) {
  972. R.suppressDiagnostics();
  973. S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
  974. << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
  975. if (!R.empty())
  976. S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
  977. return QualType();
  978. }
  979. return S.Context.getTypeDeclType(TD);
  980. }
  981. namespace {
  982. struct BindingDiagnosticTrap {
  983. Sema &S;
  984. DiagnosticErrorTrap Trap;
  985. BindingDecl *BD;
  986. BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
  987. : S(S), Trap(S.Diags), BD(BD) {}
  988. ~BindingDiagnosticTrap() {
  989. if (Trap.hasErrorOccurred())
  990. S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
  991. }
  992. };
  993. }
  994. static bool checkTupleLikeDecomposition(Sema &S,
  995. ArrayRef<BindingDecl *> Bindings,
  996. VarDecl *Src, QualType DecompType,
  997. const llvm::APSInt &TupleSize) {
  998. if ((int64_t)Bindings.size() != TupleSize) {
  999. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  1000. << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
  1001. << (TupleSize < Bindings.size());
  1002. return true;
  1003. }
  1004. if (Bindings.empty())
  1005. return false;
  1006. DeclarationName GetDN = S.PP.getIdentifierInfo("get");
  1007. // [dcl.decomp]p3:
  1008. // The unqualified-id get is looked up in the scope of E by class member
  1009. // access lookup ...
  1010. LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
  1011. bool UseMemberGet = false;
  1012. if (S.isCompleteType(Src->getLocation(), DecompType)) {
  1013. if (auto *RD = DecompType->getAsCXXRecordDecl())
  1014. S.LookupQualifiedName(MemberGet, RD);
  1015. if (MemberGet.isAmbiguous())
  1016. return true;
  1017. // ... and if that finds at least one declaration that is a function
  1018. // template whose first template parameter is a non-type parameter ...
  1019. for (NamedDecl *D : MemberGet) {
  1020. if (FunctionTemplateDecl *FTD =
  1021. dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
  1022. TemplateParameterList *TPL = FTD->getTemplateParameters();
  1023. if (TPL->size() != 0 &&
  1024. isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
  1025. // ... the initializer is e.get<i>().
  1026. UseMemberGet = true;
  1027. break;
  1028. }
  1029. }
  1030. }
  1031. }
  1032. unsigned I = 0;
  1033. for (auto *B : Bindings) {
  1034. BindingDiagnosticTrap Trap(S, B);
  1035. SourceLocation Loc = B->getLocation();
  1036. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1037. if (E.isInvalid())
  1038. return true;
  1039. // e is an lvalue if the type of the entity is an lvalue reference and
  1040. // an xvalue otherwise
  1041. if (!Src->getType()->isLValueReferenceType())
  1042. E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
  1043. E.get(), nullptr, VK_XValue);
  1044. TemplateArgumentListInfo Args(Loc, Loc);
  1045. Args.addArgument(
  1046. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  1047. if (UseMemberGet) {
  1048. // if [lookup of member get] finds at least one declaration, the
  1049. // initializer is e.get<i-1>().
  1050. E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
  1051. CXXScopeSpec(), SourceLocation(), nullptr,
  1052. MemberGet, &Args, nullptr);
  1053. if (E.isInvalid())
  1054. return true;
  1055. E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
  1056. } else {
  1057. // Otherwise, the initializer is get<i-1>(e), where get is looked up
  1058. // in the associated namespaces.
  1059. Expr *Get = UnresolvedLookupExpr::Create(
  1060. S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
  1061. DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
  1062. UnresolvedSetIterator(), UnresolvedSetIterator());
  1063. Expr *Arg = E.get();
  1064. E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
  1065. }
  1066. if (E.isInvalid())
  1067. return true;
  1068. Expr *Init = E.get();
  1069. // Given the type T designated by std::tuple_element<i - 1, E>::type,
  1070. QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
  1071. if (T.isNull())
  1072. return true;
  1073. // each vi is a variable of type "reference to T" initialized with the
  1074. // initializer, where the reference is an lvalue reference if the
  1075. // initializer is an lvalue and an rvalue reference otherwise
  1076. QualType RefType =
  1077. S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
  1078. if (RefType.isNull())
  1079. return true;
  1080. auto *RefVD = VarDecl::Create(
  1081. S.Context, Src->getDeclContext(), Loc, Loc,
  1082. B->getDeclName().getAsIdentifierInfo(), RefType,
  1083. S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
  1084. RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
  1085. RefVD->setTSCSpec(Src->getTSCSpec());
  1086. RefVD->setImplicit();
  1087. if (Src->isInlineSpecified())
  1088. RefVD->setInlineSpecified();
  1089. RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
  1090. InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
  1091. InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
  1092. InitializationSequence Seq(S, Entity, Kind, Init);
  1093. E = Seq.Perform(S, Entity, Kind, Init);
  1094. if (E.isInvalid())
  1095. return true;
  1096. E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
  1097. if (E.isInvalid())
  1098. return true;
  1099. RefVD->setInit(E.get());
  1100. RefVD->checkInitIsICE();
  1101. E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
  1102. DeclarationNameInfo(B->getDeclName(), Loc),
  1103. RefVD);
  1104. if (E.isInvalid())
  1105. return true;
  1106. B->setBinding(T, E.get());
  1107. I++;
  1108. }
  1109. return false;
  1110. }
  1111. /// Find the base class to decompose in a built-in decomposition of a class type.
  1112. /// This base class search is, unfortunately, not quite like any other that we
  1113. /// perform anywhere else in C++.
  1114. static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
  1115. const CXXRecordDecl *RD,
  1116. CXXCastPath &BasePath) {
  1117. auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
  1118. CXXBasePath &Path) {
  1119. return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
  1120. };
  1121. const CXXRecordDecl *ClassWithFields = nullptr;
  1122. AccessSpecifier AS = AS_public;
  1123. if (RD->hasDirectFields())
  1124. // [dcl.decomp]p4:
  1125. // Otherwise, all of E's non-static data members shall be public direct
  1126. // members of E ...
  1127. ClassWithFields = RD;
  1128. else {
  1129. // ... or of ...
  1130. CXXBasePaths Paths;
  1131. Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
  1132. if (!RD->lookupInBases(BaseHasFields, Paths)) {
  1133. // If no classes have fields, just decompose RD itself. (This will work
  1134. // if and only if zero bindings were provided.)
  1135. return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
  1136. }
  1137. CXXBasePath *BestPath = nullptr;
  1138. for (auto &P : Paths) {
  1139. if (!BestPath)
  1140. BestPath = &P;
  1141. else if (!S.Context.hasSameType(P.back().Base->getType(),
  1142. BestPath->back().Base->getType())) {
  1143. // ... the same ...
  1144. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1145. << false << RD << BestPath->back().Base->getType()
  1146. << P.back().Base->getType();
  1147. return DeclAccessPair();
  1148. } else if (P.Access < BestPath->Access) {
  1149. BestPath = &P;
  1150. }
  1151. }
  1152. // ... unambiguous ...
  1153. QualType BaseType = BestPath->back().Base->getType();
  1154. if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
  1155. S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
  1156. << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
  1157. return DeclAccessPair();
  1158. }
  1159. // ... [accessible, implied by other rules] base class of E.
  1160. S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
  1161. *BestPath, diag::err_decomp_decl_inaccessible_base);
  1162. AS = BestPath->Access;
  1163. ClassWithFields = BaseType->getAsCXXRecordDecl();
  1164. S.BuildBasePathArray(Paths, BasePath);
  1165. }
  1166. // The above search did not check whether the selected class itself has base
  1167. // classes with fields, so check that now.
  1168. CXXBasePaths Paths;
  1169. if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
  1170. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1171. << (ClassWithFields == RD) << RD << ClassWithFields
  1172. << Paths.front().back().Base->getType();
  1173. return DeclAccessPair();
  1174. }
  1175. return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
  1176. }
  1177. static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  1178. ValueDecl *Src, QualType DecompType,
  1179. const CXXRecordDecl *OrigRD) {
  1180. if (S.RequireCompleteType(Src->getLocation(), DecompType,
  1181. diag::err_incomplete_type))
  1182. return true;
  1183. CXXCastPath BasePath;
  1184. DeclAccessPair BasePair =
  1185. findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
  1186. const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
  1187. if (!RD)
  1188. return true;
  1189. QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
  1190. DecompType.getQualifiers());
  1191. auto DiagnoseBadNumberOfBindings = [&]() -> bool {
  1192. unsigned NumFields =
  1193. std::count_if(RD->field_begin(), RD->field_end(),
  1194. [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
  1195. assert(Bindings.size() != NumFields);
  1196. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  1197. << DecompType << (unsigned)Bindings.size() << NumFields
  1198. << (NumFields < Bindings.size());
  1199. return true;
  1200. };
  1201. // all of E's non-static data members shall be [...] well-formed
  1202. // when named as e.name in the context of the structured binding,
  1203. // E shall not have an anonymous union member, ...
  1204. unsigned I = 0;
  1205. for (auto *FD : RD->fields()) {
  1206. if (FD->isUnnamedBitfield())
  1207. continue;
  1208. if (FD->isAnonymousStructOrUnion()) {
  1209. S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
  1210. << DecompType << FD->getType()->isUnionType();
  1211. S.Diag(FD->getLocation(), diag::note_declared_at);
  1212. return true;
  1213. }
  1214. // We have a real field to bind.
  1215. if (I >= Bindings.size())
  1216. return DiagnoseBadNumberOfBindings();
  1217. auto *B = Bindings[I++];
  1218. SourceLocation Loc = B->getLocation();
  1219. // The field must be accessible in the context of the structured binding.
  1220. // We already checked that the base class is accessible.
  1221. // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
  1222. // const_cast here.
  1223. S.CheckStructuredBindingMemberAccess(
  1224. Loc, const_cast<CXXRecordDecl *>(OrigRD),
  1225. DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
  1226. BasePair.getAccess(), FD->getAccess())));
  1227. // Initialize the binding to Src.FD.
  1228. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1229. if (E.isInvalid())
  1230. return true;
  1231. E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
  1232. VK_LValue, &BasePath);
  1233. if (E.isInvalid())
  1234. return true;
  1235. E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
  1236. CXXScopeSpec(), FD,
  1237. DeclAccessPair::make(FD, FD->getAccess()),
  1238. DeclarationNameInfo(FD->getDeclName(), Loc));
  1239. if (E.isInvalid())
  1240. return true;
  1241. // If the type of the member is T, the referenced type is cv T, where cv is
  1242. // the cv-qualification of the decomposition expression.
  1243. //
  1244. // FIXME: We resolve a defect here: if the field is mutable, we do not add
  1245. // 'const' to the type of the field.
  1246. Qualifiers Q = DecompType.getQualifiers();
  1247. if (FD->isMutable())
  1248. Q.removeConst();
  1249. B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
  1250. }
  1251. if (I != Bindings.size())
  1252. return DiagnoseBadNumberOfBindings();
  1253. return false;
  1254. }
  1255. void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
  1256. QualType DecompType = DD->getType();
  1257. // If the type of the decomposition is dependent, then so is the type of
  1258. // each binding.
  1259. if (DecompType->isDependentType()) {
  1260. for (auto *B : DD->bindings())
  1261. B->setType(Context.DependentTy);
  1262. return;
  1263. }
  1264. DecompType = DecompType.getNonReferenceType();
  1265. ArrayRef<BindingDecl*> Bindings = DD->bindings();
  1266. // C++1z [dcl.decomp]/2:
  1267. // If E is an array type [...]
  1268. // As an extension, we also support decomposition of built-in complex and
  1269. // vector types.
  1270. if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
  1271. if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
  1272. DD->setInvalidDecl();
  1273. return;
  1274. }
  1275. if (auto *VT = DecompType->getAs<VectorType>()) {
  1276. if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
  1277. DD->setInvalidDecl();
  1278. return;
  1279. }
  1280. if (auto *CT = DecompType->getAs<ComplexType>()) {
  1281. if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
  1282. DD->setInvalidDecl();
  1283. return;
  1284. }
  1285. // C++1z [dcl.decomp]/3:
  1286. // if the expression std::tuple_size<E>::value is a well-formed integral
  1287. // constant expression, [...]
  1288. llvm::APSInt TupleSize(32);
  1289. switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
  1290. case IsTupleLike::Error:
  1291. DD->setInvalidDecl();
  1292. return;
  1293. case IsTupleLike::TupleLike:
  1294. if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
  1295. DD->setInvalidDecl();
  1296. return;
  1297. case IsTupleLike::NotTupleLike:
  1298. break;
  1299. }
  1300. // C++1z [dcl.dcl]/8:
  1301. // [E shall be of array or non-union class type]
  1302. CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
  1303. if (!RD || RD->isUnion()) {
  1304. Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
  1305. << DD << !RD << DecompType;
  1306. DD->setInvalidDecl();
  1307. return;
  1308. }
  1309. // C++1z [dcl.decomp]/4:
  1310. // all of E's non-static data members shall be [...] direct members of
  1311. // E or of the same unambiguous public base class of E, ...
  1312. if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
  1313. DD->setInvalidDecl();
  1314. }
  1315. /// Merge the exception specifications of two variable declarations.
  1316. ///
  1317. /// This is called when there's a redeclaration of a VarDecl. The function
  1318. /// checks if the redeclaration might have an exception specification and
  1319. /// validates compatibility and merges the specs if necessary.
  1320. void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
  1321. // Shortcut if exceptions are disabled.
  1322. if (!getLangOpts().CXXExceptions)
  1323. return;
  1324. assert(Context.hasSameType(New->getType(), Old->getType()) &&
  1325. "Should only be called if types are otherwise the same.");
  1326. QualType NewType = New->getType();
  1327. QualType OldType = Old->getType();
  1328. // We're only interested in pointers and references to functions, as well
  1329. // as pointers to member functions.
  1330. if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
  1331. NewType = R->getPointeeType();
  1332. OldType = OldType->getAs<ReferenceType>()->getPointeeType();
  1333. } else if (const PointerType *P = NewType->getAs<PointerType>()) {
  1334. NewType = P->getPointeeType();
  1335. OldType = OldType->getAs<PointerType>()->getPointeeType();
  1336. } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
  1337. NewType = M->getPointeeType();
  1338. OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
  1339. }
  1340. if (!NewType->isFunctionProtoType())
  1341. return;
  1342. // There's lots of special cases for functions. For function pointers, system
  1343. // libraries are hopefully not as broken so that we don't need these
  1344. // workarounds.
  1345. if (CheckEquivalentExceptionSpec(
  1346. OldType->getAs<FunctionProtoType>(), Old->getLocation(),
  1347. NewType->getAs<FunctionProtoType>(), New->getLocation())) {
  1348. New->setInvalidDecl();
  1349. }
  1350. }
  1351. /// CheckCXXDefaultArguments - Verify that the default arguments for a
  1352. /// function declaration are well-formed according to C++
  1353. /// [dcl.fct.default].
  1354. void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
  1355. unsigned NumParams = FD->getNumParams();
  1356. unsigned p;
  1357. // Find first parameter with a default argument
  1358. for (p = 0; p < NumParams; ++p) {
  1359. ParmVarDecl *Param = FD->getParamDecl(p);
  1360. if (Param->hasDefaultArg())
  1361. break;
  1362. }
  1363. // C++11 [dcl.fct.default]p4:
  1364. // In a given function declaration, each parameter subsequent to a parameter
  1365. // with a default argument shall have a default argument supplied in this or
  1366. // a previous declaration or shall be a function parameter pack. A default
  1367. // argument shall not be redefined by a later declaration (not even to the
  1368. // same value).
  1369. unsigned LastMissingDefaultArg = 0;
  1370. for (; p < NumParams; ++p) {
  1371. ParmVarDecl *Param = FD->getParamDecl(p);
  1372. if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
  1373. if (Param->isInvalidDecl())
  1374. /* We already complained about this parameter. */;
  1375. else if (Param->getIdentifier())
  1376. Diag(Param->getLocation(),
  1377. diag::err_param_default_argument_missing_name)
  1378. << Param->getIdentifier();
  1379. else
  1380. Diag(Param->getLocation(),
  1381. diag::err_param_default_argument_missing);
  1382. LastMissingDefaultArg = p;
  1383. }
  1384. }
  1385. if (LastMissingDefaultArg > 0) {
  1386. // Some default arguments were missing. Clear out all of the
  1387. // default arguments up to (and including) the last missing
  1388. // default argument, so that we leave the function parameters
  1389. // in a semantically valid state.
  1390. for (p = 0; p <= LastMissingDefaultArg; ++p) {
  1391. ParmVarDecl *Param = FD->getParamDecl(p);
  1392. if (Param->hasDefaultArg()) {
  1393. Param->setDefaultArg(nullptr);
  1394. }
  1395. }
  1396. }
  1397. }
  1398. // CheckConstexprParameterTypes - Check whether a function's parameter types
  1399. // are all literal types. If so, return true. If not, produce a suitable
  1400. // diagnostic and return false.
  1401. static bool CheckConstexprParameterTypes(Sema &SemaRef,
  1402. const FunctionDecl *FD) {
  1403. unsigned ArgIndex = 0;
  1404. const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
  1405. for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
  1406. e = FT->param_type_end();
  1407. i != e; ++i, ++ArgIndex) {
  1408. const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
  1409. SourceLocation ParamLoc = PD->getLocation();
  1410. if (!(*i)->isDependentType() &&
  1411. SemaRef.RequireLiteralType(
  1412. ParamLoc, *i, diag::err_constexpr_non_literal_param, ArgIndex + 1,
  1413. PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
  1414. FD->isConsteval()))
  1415. return false;
  1416. }
  1417. return true;
  1418. }
  1419. /// Get diagnostic %select index for tag kind for
  1420. /// record diagnostic message.
  1421. /// WARNING: Indexes apply to particular diagnostics only!
  1422. ///
  1423. /// \returns diagnostic %select index.
  1424. static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
  1425. switch (Tag) {
  1426. case TTK_Struct: return 0;
  1427. case TTK_Interface: return 1;
  1428. case TTK_Class: return 2;
  1429. default: llvm_unreachable("Invalid tag kind for record diagnostic!");
  1430. }
  1431. }
  1432. // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
  1433. // the requirements of a constexpr function definition or a constexpr
  1434. // constructor definition. If so, return true. If not, produce appropriate
  1435. // diagnostics and return false.
  1436. //
  1437. // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
  1438. bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
  1439. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  1440. if (MD && MD->isInstance()) {
  1441. // C++11 [dcl.constexpr]p4:
  1442. // The definition of a constexpr constructor shall satisfy the following
  1443. // constraints:
  1444. // - the class shall not have any virtual base classes;
  1445. //
  1446. // FIXME: This only applies to constructors, not arbitrary member
  1447. // functions.
  1448. const CXXRecordDecl *RD = MD->getParent();
  1449. if (RD->getNumVBases()) {
  1450. Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
  1451. << isa<CXXConstructorDecl>(NewFD)
  1452. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  1453. for (const auto &I : RD->vbases())
  1454. Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
  1455. << I.getSourceRange();
  1456. return false;
  1457. }
  1458. }
  1459. if (!isa<CXXConstructorDecl>(NewFD)) {
  1460. // C++11 [dcl.constexpr]p3:
  1461. // The definition of a constexpr function shall satisfy the following
  1462. // constraints:
  1463. // - it shall not be virtual; (removed in C++20)
  1464. const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
  1465. if (Method && Method->isVirtual()) {
  1466. if (getLangOpts().CPlusPlus2a) {
  1467. Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
  1468. } else {
  1469. Method = Method->getCanonicalDecl();
  1470. Diag(Method->getLocation(), diag::err_constexpr_virtual);
  1471. // If it's not obvious why this function is virtual, find an overridden
  1472. // function which uses the 'virtual' keyword.
  1473. const CXXMethodDecl *WrittenVirtual = Method;
  1474. while (!WrittenVirtual->isVirtualAsWritten())
  1475. WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
  1476. if (WrittenVirtual != Method)
  1477. Diag(WrittenVirtual->getLocation(),
  1478. diag::note_overridden_virtual_function);
  1479. return false;
  1480. }
  1481. }
  1482. // - its return type shall be a literal type;
  1483. QualType RT = NewFD->getReturnType();
  1484. if (!RT->isDependentType() &&
  1485. RequireLiteralType(NewFD->getLocation(), RT,
  1486. diag::err_constexpr_non_literal_return,
  1487. NewFD->isConsteval()))
  1488. return false;
  1489. }
  1490. // - each of its parameter types shall be a literal type;
  1491. if (!CheckConstexprParameterTypes(*this, NewFD))
  1492. return false;
  1493. return true;
  1494. }
  1495. /// Check the given declaration statement is legal within a constexpr function
  1496. /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
  1497. ///
  1498. /// \return true if the body is OK (maybe only as an extension), false if we
  1499. /// have diagnosed a problem.
  1500. static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
  1501. DeclStmt *DS, SourceLocation &Cxx1yLoc) {
  1502. // C++11 [dcl.constexpr]p3 and p4:
  1503. // The definition of a constexpr function(p3) or constructor(p4) [...] shall
  1504. // contain only
  1505. for (const auto *DclIt : DS->decls()) {
  1506. switch (DclIt->getKind()) {
  1507. case Decl::StaticAssert:
  1508. case Decl::Using:
  1509. case Decl::UsingShadow:
  1510. case Decl::UsingDirective:
  1511. case Decl::UnresolvedUsingTypename:
  1512. case Decl::UnresolvedUsingValue:
  1513. // - static_assert-declarations
  1514. // - using-declarations,
  1515. // - using-directives,
  1516. continue;
  1517. case Decl::Typedef:
  1518. case Decl::TypeAlias: {
  1519. // - typedef declarations and alias-declarations that do not define
  1520. // classes or enumerations,
  1521. const auto *TN = cast<TypedefNameDecl>(DclIt);
  1522. if (TN->getUnderlyingType()->isVariablyModifiedType()) {
  1523. // Don't allow variably-modified types in constexpr functions.
  1524. TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
  1525. SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
  1526. << TL.getSourceRange() << TL.getType()
  1527. << isa<CXXConstructorDecl>(Dcl);
  1528. return false;
  1529. }
  1530. continue;
  1531. }
  1532. case Decl::Enum:
  1533. case Decl::CXXRecord:
  1534. // C++1y allows types to be defined, not just declared.
  1535. if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
  1536. SemaRef.Diag(DS->getBeginLoc(),
  1537. SemaRef.getLangOpts().CPlusPlus14
  1538. ? diag::warn_cxx11_compat_constexpr_type_definition
  1539. : diag::ext_constexpr_type_definition)
  1540. << isa<CXXConstructorDecl>(Dcl);
  1541. continue;
  1542. case Decl::EnumConstant:
  1543. case Decl::IndirectField:
  1544. case Decl::ParmVar:
  1545. // These can only appear with other declarations which are banned in
  1546. // C++11 and permitted in C++1y, so ignore them.
  1547. continue;
  1548. case Decl::Var:
  1549. case Decl::Decomposition: {
  1550. // C++1y [dcl.constexpr]p3 allows anything except:
  1551. // a definition of a variable of non-literal type or of static or
  1552. // thread storage duration or for which no initialization is performed.
  1553. const auto *VD = cast<VarDecl>(DclIt);
  1554. if (VD->isThisDeclarationADefinition()) {
  1555. if (VD->isStaticLocal()) {
  1556. SemaRef.Diag(VD->getLocation(),
  1557. diag::err_constexpr_local_var_static)
  1558. << isa<CXXConstructorDecl>(Dcl)
  1559. << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
  1560. return false;
  1561. }
  1562. if (!VD->getType()->isDependentType() &&
  1563. SemaRef.RequireLiteralType(
  1564. VD->getLocation(), VD->getType(),
  1565. diag::err_constexpr_local_var_non_literal_type,
  1566. isa<CXXConstructorDecl>(Dcl)))
  1567. return false;
  1568. if (!VD->getType()->isDependentType() &&
  1569. !VD->hasInit() && !VD->isCXXForRangeDecl()) {
  1570. SemaRef.Diag(VD->getLocation(),
  1571. diag::err_constexpr_local_var_no_init)
  1572. << isa<CXXConstructorDecl>(Dcl);
  1573. return false;
  1574. }
  1575. }
  1576. SemaRef.Diag(VD->getLocation(),
  1577. SemaRef.getLangOpts().CPlusPlus14
  1578. ? diag::warn_cxx11_compat_constexpr_local_var
  1579. : diag::ext_constexpr_local_var)
  1580. << isa<CXXConstructorDecl>(Dcl);
  1581. continue;
  1582. }
  1583. case Decl::NamespaceAlias:
  1584. case Decl::Function:
  1585. // These are disallowed in C++11 and permitted in C++1y. Allow them
  1586. // everywhere as an extension.
  1587. if (!Cxx1yLoc.isValid())
  1588. Cxx1yLoc = DS->getBeginLoc();
  1589. continue;
  1590. default:
  1591. SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1592. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  1593. return false;
  1594. }
  1595. }
  1596. return true;
  1597. }
  1598. /// Check that the given field is initialized within a constexpr constructor.
  1599. ///
  1600. /// \param Dcl The constexpr constructor being checked.
  1601. /// \param Field The field being checked. This may be a member of an anonymous
  1602. /// struct or union nested within the class being checked.
  1603. /// \param Inits All declarations, including anonymous struct/union members and
  1604. /// indirect members, for which any initialization was provided.
  1605. /// \param Diagnosed Set to true if an error is produced.
  1606. static void CheckConstexprCtorInitializer(Sema &SemaRef,
  1607. const FunctionDecl *Dcl,
  1608. FieldDecl *Field,
  1609. llvm::SmallSet<Decl*, 16> &Inits,
  1610. bool &Diagnosed) {
  1611. if (Field->isInvalidDecl())
  1612. return;
  1613. if (Field->isUnnamedBitfield())
  1614. return;
  1615. // Anonymous unions with no variant members and empty anonymous structs do not
  1616. // need to be explicitly initialized. FIXME: Anonymous structs that contain no
  1617. // indirect fields don't need initializing.
  1618. if (Field->isAnonymousStructOrUnion() &&
  1619. (Field->getType()->isUnionType()
  1620. ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
  1621. : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
  1622. return;
  1623. if (!Inits.count(Field)) {
  1624. if (!Diagnosed) {
  1625. SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
  1626. Diagnosed = true;
  1627. }
  1628. SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
  1629. } else if (Field->isAnonymousStructOrUnion()) {
  1630. const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
  1631. for (auto *I : RD->fields())
  1632. // If an anonymous union contains an anonymous struct of which any member
  1633. // is initialized, all members must be initialized.
  1634. if (!RD->isUnion() || Inits.count(I))
  1635. CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
  1636. }
  1637. }
  1638. /// Check the provided statement is allowed in a constexpr function
  1639. /// definition.
  1640. static bool
  1641. CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
  1642. SmallVectorImpl<SourceLocation> &ReturnStmts,
  1643. SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) {
  1644. // - its function-body shall be [...] a compound-statement that contains only
  1645. switch (S->getStmtClass()) {
  1646. case Stmt::NullStmtClass:
  1647. // - null statements,
  1648. return true;
  1649. case Stmt::DeclStmtClass:
  1650. // - static_assert-declarations
  1651. // - using-declarations,
  1652. // - using-directives,
  1653. // - typedef declarations and alias-declarations that do not define
  1654. // classes or enumerations,
  1655. if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
  1656. return false;
  1657. return true;
  1658. case Stmt::ReturnStmtClass:
  1659. // - and exactly one return statement;
  1660. if (isa<CXXConstructorDecl>(Dcl)) {
  1661. // C++1y allows return statements in constexpr constructors.
  1662. if (!Cxx1yLoc.isValid())
  1663. Cxx1yLoc = S->getBeginLoc();
  1664. return true;
  1665. }
  1666. ReturnStmts.push_back(S->getBeginLoc());
  1667. return true;
  1668. case Stmt::CompoundStmtClass: {
  1669. // C++1y allows compound-statements.
  1670. if (!Cxx1yLoc.isValid())
  1671. Cxx1yLoc = S->getBeginLoc();
  1672. CompoundStmt *CompStmt = cast<CompoundStmt>(S);
  1673. for (auto *BodyIt : CompStmt->body()) {
  1674. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
  1675. Cxx1yLoc, Cxx2aLoc))
  1676. return false;
  1677. }
  1678. return true;
  1679. }
  1680. case Stmt::AttributedStmtClass:
  1681. if (!Cxx1yLoc.isValid())
  1682. Cxx1yLoc = S->getBeginLoc();
  1683. return true;
  1684. case Stmt::IfStmtClass: {
  1685. // C++1y allows if-statements.
  1686. if (!Cxx1yLoc.isValid())
  1687. Cxx1yLoc = S->getBeginLoc();
  1688. IfStmt *If = cast<IfStmt>(S);
  1689. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
  1690. Cxx1yLoc, Cxx2aLoc))
  1691. return false;
  1692. if (If->getElse() &&
  1693. !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
  1694. Cxx1yLoc, Cxx2aLoc))
  1695. return false;
  1696. return true;
  1697. }
  1698. case Stmt::WhileStmtClass:
  1699. case Stmt::DoStmtClass:
  1700. case Stmt::ForStmtClass:
  1701. case Stmt::CXXForRangeStmtClass:
  1702. case Stmt::ContinueStmtClass:
  1703. // C++1y allows all of these. We don't allow them as extensions in C++11,
  1704. // because they don't make sense without variable mutation.
  1705. if (!SemaRef.getLangOpts().CPlusPlus14)
  1706. break;
  1707. if (!Cxx1yLoc.isValid())
  1708. Cxx1yLoc = S->getBeginLoc();
  1709. for (Stmt *SubStmt : S->children())
  1710. if (SubStmt &&
  1711. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1712. Cxx1yLoc, Cxx2aLoc))
  1713. return false;
  1714. return true;
  1715. case Stmt::SwitchStmtClass:
  1716. case Stmt::CaseStmtClass:
  1717. case Stmt::DefaultStmtClass:
  1718. case Stmt::BreakStmtClass:
  1719. // C++1y allows switch-statements, and since they don't need variable
  1720. // mutation, we can reasonably allow them in C++11 as an extension.
  1721. if (!Cxx1yLoc.isValid())
  1722. Cxx1yLoc = S->getBeginLoc();
  1723. for (Stmt *SubStmt : S->children())
  1724. if (SubStmt &&
  1725. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1726. Cxx1yLoc, Cxx2aLoc))
  1727. return false;
  1728. return true;
  1729. case Stmt::CXXTryStmtClass:
  1730. if (Cxx2aLoc.isInvalid())
  1731. Cxx2aLoc = S->getBeginLoc();
  1732. for (Stmt *SubStmt : S->children()) {
  1733. if (SubStmt &&
  1734. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1735. Cxx1yLoc, Cxx2aLoc))
  1736. return false;
  1737. }
  1738. return true;
  1739. case Stmt::CXXCatchStmtClass:
  1740. // Do not bother checking the language mode (already covered by the
  1741. // try block check).
  1742. if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
  1743. cast<CXXCatchStmt>(S)->getHandlerBlock(),
  1744. ReturnStmts, Cxx1yLoc, Cxx2aLoc))
  1745. return false;
  1746. return true;
  1747. default:
  1748. if (!isa<Expr>(S))
  1749. break;
  1750. // C++1y allows expression-statements.
  1751. if (!Cxx1yLoc.isValid())
  1752. Cxx1yLoc = S->getBeginLoc();
  1753. return true;
  1754. }
  1755. SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1756. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  1757. return false;
  1758. }
  1759. /// Check the body for the given constexpr function declaration only contains
  1760. /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
  1761. ///
  1762. /// \return true if the body is OK, false if we have diagnosed a problem.
  1763. bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
  1764. SmallVector<SourceLocation, 4> ReturnStmts;
  1765. if (isa<CXXTryStmt>(Body)) {
  1766. // C++11 [dcl.constexpr]p3:
  1767. // The definition of a constexpr function shall satisfy the following
  1768. // constraints: [...]
  1769. // - its function-body shall be = delete, = default, or a
  1770. // compound-statement
  1771. //
  1772. // C++11 [dcl.constexpr]p4:
  1773. // In the definition of a constexpr constructor, [...]
  1774. // - its function-body shall not be a function-try-block;
  1775. //
  1776. // This restriction is lifted in C++2a, as long as inner statements also
  1777. // apply the general constexpr rules.
  1778. Diag(Body->getBeginLoc(),
  1779. !getLangOpts().CPlusPlus2a
  1780. ? diag::ext_constexpr_function_try_block_cxx2a
  1781. : diag::warn_cxx17_compat_constexpr_function_try_block)
  1782. << isa<CXXConstructorDecl>(Dcl);
  1783. }
  1784. // - its function-body shall be [...] a compound-statement that contains only
  1785. // [... list of cases ...]
  1786. //
  1787. // Note that walking the children here is enough to properly check for
  1788. // CompoundStmt and CXXTryStmt body.
  1789. SourceLocation Cxx1yLoc, Cxx2aLoc;
  1790. for (Stmt *SubStmt : Body->children()) {
  1791. if (SubStmt &&
  1792. !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts,
  1793. Cxx1yLoc, Cxx2aLoc))
  1794. return false;
  1795. }
  1796. if (Cxx2aLoc.isValid())
  1797. Diag(Cxx2aLoc,
  1798. getLangOpts().CPlusPlus2a
  1799. ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
  1800. : diag::ext_constexpr_body_invalid_stmt_cxx2a)
  1801. << isa<CXXConstructorDecl>(Dcl);
  1802. if (Cxx1yLoc.isValid())
  1803. Diag(Cxx1yLoc,
  1804. getLangOpts().CPlusPlus14
  1805. ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
  1806. : diag::ext_constexpr_body_invalid_stmt)
  1807. << isa<CXXConstructorDecl>(Dcl);
  1808. if (const CXXConstructorDecl *Constructor
  1809. = dyn_cast<CXXConstructorDecl>(Dcl)) {
  1810. const CXXRecordDecl *RD = Constructor->getParent();
  1811. // DR1359:
  1812. // - every non-variant non-static data member and base class sub-object
  1813. // shall be initialized;
  1814. // DR1460:
  1815. // - if the class is a union having variant members, exactly one of them
  1816. // shall be initialized;
  1817. if (RD->isUnion()) {
  1818. if (Constructor->getNumCtorInitializers() == 0 &&
  1819. RD->hasVariantMembers()) {
  1820. Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
  1821. return false;
  1822. }
  1823. } else if (!Constructor->isDependentContext() &&
  1824. !Constructor->isDelegatingConstructor()) {
  1825. assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
  1826. // Skip detailed checking if we have enough initializers, and we would
  1827. // allow at most one initializer per member.
  1828. bool AnyAnonStructUnionMembers = false;
  1829. unsigned Fields = 0;
  1830. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  1831. E = RD->field_end(); I != E; ++I, ++Fields) {
  1832. if (I->isAnonymousStructOrUnion()) {
  1833. AnyAnonStructUnionMembers = true;
  1834. break;
  1835. }
  1836. }
  1837. // DR1460:
  1838. // - if the class is a union-like class, but is not a union, for each of
  1839. // its anonymous union members having variant members, exactly one of
  1840. // them shall be initialized;
  1841. if (AnyAnonStructUnionMembers ||
  1842. Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
  1843. // Check initialization of non-static data members. Base classes are
  1844. // always initialized so do not need to be checked. Dependent bases
  1845. // might not have initializers in the member initializer list.
  1846. llvm::SmallSet<Decl*, 16> Inits;
  1847. for (const auto *I: Constructor->inits()) {
  1848. if (FieldDecl *FD = I->getMember())
  1849. Inits.insert(FD);
  1850. else if (IndirectFieldDecl *ID = I->getIndirectMember())
  1851. Inits.insert(ID->chain_begin(), ID->chain_end());
  1852. }
  1853. bool Diagnosed = false;
  1854. for (auto *I : RD->fields())
  1855. CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
  1856. if (Diagnosed)
  1857. return false;
  1858. }
  1859. }
  1860. } else {
  1861. if (ReturnStmts.empty()) {
  1862. // C++1y doesn't require constexpr functions to contain a 'return'
  1863. // statement. We still do, unless the return type might be void, because
  1864. // otherwise if there's no return statement, the function cannot
  1865. // be used in a core constant expression.
  1866. bool OK = getLangOpts().CPlusPlus14 &&
  1867. (Dcl->getReturnType()->isVoidType() ||
  1868. Dcl->getReturnType()->isDependentType());
  1869. Diag(Dcl->getLocation(),
  1870. OK ? diag::warn_cxx11_compat_constexpr_body_no_return
  1871. : diag::err_constexpr_body_no_return)
  1872. << Dcl->isConsteval();
  1873. if (!OK)
  1874. return false;
  1875. } else if (ReturnStmts.size() > 1) {
  1876. Diag(ReturnStmts.back(),
  1877. getLangOpts().CPlusPlus14
  1878. ? diag::warn_cxx11_compat_constexpr_body_multiple_return
  1879. : diag::ext_constexpr_body_multiple_return);
  1880. for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
  1881. Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
  1882. }
  1883. }
  1884. // C++11 [dcl.constexpr]p5:
  1885. // if no function argument values exist such that the function invocation
  1886. // substitution would produce a constant expression, the program is
  1887. // ill-formed; no diagnostic required.
  1888. // C++11 [dcl.constexpr]p3:
  1889. // - every constructor call and implicit conversion used in initializing the
  1890. // return value shall be one of those allowed in a constant expression.
  1891. // C++11 [dcl.constexpr]p4:
  1892. // - every constructor involved in initializing non-static data members and
  1893. // base class sub-objects shall be a constexpr constructor.
  1894. SmallVector<PartialDiagnosticAt, 8> Diags;
  1895. if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
  1896. Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
  1897. << isa<CXXConstructorDecl>(Dcl);
  1898. for (size_t I = 0, N = Diags.size(); I != N; ++I)
  1899. Diag(Diags[I].first, Diags[I].second);
  1900. // Don't return false here: we allow this for compatibility in
  1901. // system headers.
  1902. }
  1903. return true;
  1904. }
  1905. /// Get the class that is directly named by the current context. This is the
  1906. /// class for which an unqualified-id in this scope could name a constructor
  1907. /// or destructor.
  1908. ///
  1909. /// If the scope specifier denotes a class, this will be that class.
  1910. /// If the scope specifier is empty, this will be the class whose
  1911. /// member-specification we are currently within. Otherwise, there
  1912. /// is no such class.
  1913. CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
  1914. assert(getLangOpts().CPlusPlus && "No class names in C!");
  1915. if (SS && SS->isInvalid())
  1916. return nullptr;
  1917. if (SS && SS->isNotEmpty()) {
  1918. DeclContext *DC = computeDeclContext(*SS, true);
  1919. return dyn_cast_or_null<CXXRecordDecl>(DC);
  1920. }
  1921. return dyn_cast_or_null<CXXRecordDecl>(CurContext);
  1922. }
  1923. /// isCurrentClassName - Determine whether the identifier II is the
  1924. /// name of the class type currently being defined. In the case of
  1925. /// nested classes, this will only return true if II is the name of
  1926. /// the innermost class.
  1927. bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
  1928. const CXXScopeSpec *SS) {
  1929. CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
  1930. return CurDecl && &II == CurDecl->getIdentifier();
  1931. }
  1932. /// Determine whether the identifier II is a typo for the name of
  1933. /// the class type currently being defined. If so, update it to the identifier
  1934. /// that should have been used.
  1935. bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
  1936. assert(getLangOpts().CPlusPlus && "No class names in C!");
  1937. if (!getLangOpts().SpellChecking)
  1938. return false;
  1939. CXXRecordDecl *CurDecl;
  1940. if (SS && SS->isSet() && !SS->isInvalid()) {
  1941. DeclContext *DC = computeDeclContext(*SS, true);
  1942. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  1943. } else
  1944. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  1945. if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
  1946. 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
  1947. < II->getLength()) {
  1948. II = CurDecl->getIdentifier();
  1949. return true;
  1950. }
  1951. return false;
  1952. }
  1953. /// Determine whether the given class is a base class of the given
  1954. /// class, including looking at dependent bases.
  1955. static bool findCircularInheritance(const CXXRecordDecl *Class,
  1956. const CXXRecordDecl *Current) {
  1957. SmallVector<const CXXRecordDecl*, 8> Queue;
  1958. Class = Class->getCanonicalDecl();
  1959. while (true) {
  1960. for (const auto &I : Current->bases()) {
  1961. CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  1962. if (!Base)
  1963. continue;
  1964. Base = Base->getDefinition();
  1965. if (!Base)
  1966. continue;
  1967. if (Base->getCanonicalDecl() == Class)
  1968. return true;
  1969. Queue.push_back(Base);
  1970. }
  1971. if (Queue.empty())
  1972. return false;
  1973. Current = Queue.pop_back_val();
  1974. }
  1975. return false;
  1976. }
  1977. /// Check the validity of a C++ base class specifier.
  1978. ///
  1979. /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
  1980. /// and returns NULL otherwise.
  1981. CXXBaseSpecifier *
  1982. Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
  1983. SourceRange SpecifierRange,
  1984. bool Virtual, AccessSpecifier Access,
  1985. TypeSourceInfo *TInfo,
  1986. SourceLocation EllipsisLoc) {
  1987. QualType BaseType = TInfo->getType();
  1988. // C++ [class.union]p1:
  1989. // A union shall not have base classes.
  1990. if (Class->isUnion()) {
  1991. Diag(Class->getLocation(), diag::err_base_clause_on_union)
  1992. << SpecifierRange;
  1993. return nullptr;
  1994. }
  1995. if (EllipsisLoc.isValid() &&
  1996. !TInfo->getType()->containsUnexpandedParameterPack()) {
  1997. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  1998. << TInfo->getTypeLoc().getSourceRange();
  1999. EllipsisLoc = SourceLocation();
  2000. }
  2001. SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
  2002. if (BaseType->isDependentType()) {
  2003. // Make sure that we don't have circular inheritance among our dependent
  2004. // bases. For non-dependent bases, the check for completeness below handles
  2005. // this.
  2006. if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
  2007. if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
  2008. ((BaseDecl = BaseDecl->getDefinition()) &&
  2009. findCircularInheritance(Class, BaseDecl))) {
  2010. Diag(BaseLoc, diag::err_circular_inheritance)
  2011. << BaseType << Context.getTypeDeclType(Class);
  2012. if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
  2013. Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  2014. << BaseType;
  2015. return nullptr;
  2016. }
  2017. }
  2018. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2019. Class->getTagKind() == TTK_Class,
  2020. Access, TInfo, EllipsisLoc);
  2021. }
  2022. // Base specifiers must be record types.
  2023. if (!BaseType->isRecordType()) {
  2024. Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
  2025. return nullptr;
  2026. }
  2027. // C++ [class.union]p1:
  2028. // A union shall not be used as a base class.
  2029. if (BaseType->isUnionType()) {
  2030. Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
  2031. return nullptr;
  2032. }
  2033. // For the MS ABI, propagate DLL attributes to base class templates.
  2034. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2035. if (Attr *ClassAttr = getDLLAttr(Class)) {
  2036. if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  2037. BaseType->getAsCXXRecordDecl())) {
  2038. propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
  2039. BaseLoc);
  2040. }
  2041. }
  2042. }
  2043. // C++ [class.derived]p2:
  2044. // The class-name in a base-specifier shall not be an incompletely
  2045. // defined class.
  2046. if (RequireCompleteType(BaseLoc, BaseType,
  2047. diag::err_incomplete_base_class, SpecifierRange)) {
  2048. Class->setInvalidDecl();
  2049. return nullptr;
  2050. }
  2051. // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
  2052. RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
  2053. assert(BaseDecl && "Record type has no declaration");
  2054. BaseDecl = BaseDecl->getDefinition();
  2055. assert(BaseDecl && "Base type is not incomplete, but has no definition");
  2056. CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
  2057. assert(CXXBaseDecl && "Base type is not a C++ type");
  2058. // Microsoft docs say:
  2059. // "If a base-class has a code_seg attribute, derived classes must have the
  2060. // same attribute."
  2061. const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
  2062. const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
  2063. if ((DerivedCSA || BaseCSA) &&
  2064. (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
  2065. Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
  2066. Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
  2067. << CXXBaseDecl;
  2068. return nullptr;
  2069. }
  2070. // A class which contains a flexible array member is not suitable for use as a
  2071. // base class:
  2072. // - If the layout determines that a base comes before another base,
  2073. // the flexible array member would index into the subsequent base.
  2074. // - If the layout determines that base comes before the derived class,
  2075. // the flexible array member would index into the derived class.
  2076. if (CXXBaseDecl->hasFlexibleArrayMember()) {
  2077. Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
  2078. << CXXBaseDecl->getDeclName();
  2079. return nullptr;
  2080. }
  2081. // C++ [class]p3:
  2082. // If a class is marked final and it appears as a base-type-specifier in
  2083. // base-clause, the program is ill-formed.
  2084. if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
  2085. Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
  2086. << CXXBaseDecl->getDeclName()
  2087. << FA->isSpelledAsSealed();
  2088. Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
  2089. << CXXBaseDecl->getDeclName() << FA->getRange();
  2090. return nullptr;
  2091. }
  2092. if (BaseDecl->isInvalidDecl())
  2093. Class->setInvalidDecl();
  2094. // Create the base specifier.
  2095. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2096. Class->getTagKind() == TTK_Class,
  2097. Access, TInfo, EllipsisLoc);
  2098. }
  2099. /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
  2100. /// one entry in the base class list of a class specifier, for
  2101. /// example:
  2102. /// class foo : public bar, virtual private baz {
  2103. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  2104. BaseResult
  2105. Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
  2106. ParsedAttributes &Attributes,
  2107. bool Virtual, AccessSpecifier Access,
  2108. ParsedType basetype, SourceLocation BaseLoc,
  2109. SourceLocation EllipsisLoc) {
  2110. if (!classdecl)
  2111. return true;
  2112. AdjustDeclIfTemplate(classdecl);
  2113. CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
  2114. if (!Class)
  2115. return true;
  2116. // We haven't yet attached the base specifiers.
  2117. Class->setIsParsingBaseSpecifiers();
  2118. // We do not support any C++11 attributes on base-specifiers yet.
  2119. // Diagnose any attributes we see.
  2120. for (const ParsedAttr &AL : Attributes) {
  2121. if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
  2122. continue;
  2123. Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
  2124. ? (unsigned)diag::warn_unknown_attribute_ignored
  2125. : (unsigned)diag::err_base_specifier_attribute)
  2126. << AL.getName();
  2127. }
  2128. TypeSourceInfo *TInfo = nullptr;
  2129. GetTypeFromParser(basetype, &TInfo);
  2130. if (EllipsisLoc.isInvalid() &&
  2131. DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
  2132. UPPC_BaseType))
  2133. return true;
  2134. if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
  2135. Virtual, Access, TInfo,
  2136. EllipsisLoc))
  2137. return BaseSpec;
  2138. else
  2139. Class->setInvalidDecl();
  2140. return true;
  2141. }
  2142. /// Use small set to collect indirect bases. As this is only used
  2143. /// locally, there's no need to abstract the small size parameter.
  2144. typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
  2145. /// Recursively add the bases of Type. Don't add Type itself.
  2146. static void
  2147. NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
  2148. const QualType &Type)
  2149. {
  2150. // Even though the incoming type is a base, it might not be
  2151. // a class -- it could be a template parm, for instance.
  2152. if (auto Rec = Type->getAs<RecordType>()) {
  2153. auto Decl = Rec->getAsCXXRecordDecl();
  2154. // Iterate over its bases.
  2155. for (const auto &BaseSpec : Decl->bases()) {
  2156. QualType Base = Context.getCanonicalType(BaseSpec.getType())
  2157. .getUnqualifiedType();
  2158. if (Set.insert(Base).second)
  2159. // If we've not already seen it, recurse.
  2160. NoteIndirectBases(Context, Set, Base);
  2161. }
  2162. }
  2163. }
  2164. /// Performs the actual work of attaching the given base class
  2165. /// specifiers to a C++ class.
  2166. bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
  2167. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2168. if (Bases.empty())
  2169. return false;
  2170. // Used to keep track of which base types we have already seen, so
  2171. // that we can properly diagnose redundant direct base types. Note
  2172. // that the key is always the unqualified canonical type of the base
  2173. // class.
  2174. std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
  2175. // Used to track indirect bases so we can see if a direct base is
  2176. // ambiguous.
  2177. IndirectBaseSet IndirectBaseTypes;
  2178. // Copy non-redundant base specifiers into permanent storage.
  2179. unsigned NumGoodBases = 0;
  2180. bool Invalid = false;
  2181. for (unsigned idx = 0; idx < Bases.size(); ++idx) {
  2182. QualType NewBaseType
  2183. = Context.getCanonicalType(Bases[idx]->getType());
  2184. NewBaseType = NewBaseType.getLocalUnqualifiedType();
  2185. CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
  2186. if (KnownBase) {
  2187. // C++ [class.mi]p3:
  2188. // A class shall not be specified as a direct base class of a
  2189. // derived class more than once.
  2190. Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
  2191. << KnownBase->getType() << Bases[idx]->getSourceRange();
  2192. // Delete the duplicate base class specifier; we're going to
  2193. // overwrite its pointer later.
  2194. Context.Deallocate(Bases[idx]);
  2195. Invalid = true;
  2196. } else {
  2197. // Okay, add this new base class.
  2198. KnownBase = Bases[idx];
  2199. Bases[NumGoodBases++] = Bases[idx];
  2200. // Note this base's direct & indirect bases, if there could be ambiguity.
  2201. if (Bases.size() > 1)
  2202. NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
  2203. if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
  2204. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  2205. if (Class->isInterface() &&
  2206. (!RD->isInterfaceLike() ||
  2207. KnownBase->getAccessSpecifier() != AS_public)) {
  2208. // The Microsoft extension __interface does not permit bases that
  2209. // are not themselves public interfaces.
  2210. Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
  2211. << getRecordDiagFromTagKind(RD->getTagKind()) << RD
  2212. << RD->getSourceRange();
  2213. Invalid = true;
  2214. }
  2215. if (RD->hasAttr<WeakAttr>())
  2216. Class->addAttr(WeakAttr::CreateImplicit(Context));
  2217. }
  2218. }
  2219. }
  2220. // Attach the remaining base class specifiers to the derived class.
  2221. Class->setBases(Bases.data(), NumGoodBases);
  2222. // Check that the only base classes that are duplicate are virtual.
  2223. for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
  2224. // Check whether this direct base is inaccessible due to ambiguity.
  2225. QualType BaseType = Bases[idx]->getType();
  2226. // Skip all dependent types in templates being used as base specifiers.
  2227. // Checks below assume that the base specifier is a CXXRecord.
  2228. if (BaseType->isDependentType())
  2229. continue;
  2230. CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
  2231. .getUnqualifiedType();
  2232. if (IndirectBaseTypes.count(CanonicalBase)) {
  2233. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2234. /*DetectVirtual=*/true);
  2235. bool found
  2236. = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
  2237. assert(found);
  2238. (void)found;
  2239. if (Paths.isAmbiguous(CanonicalBase))
  2240. Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
  2241. << BaseType << getAmbiguousPathsDisplayString(Paths)
  2242. << Bases[idx]->getSourceRange();
  2243. else
  2244. assert(Bases[idx]->isVirtual());
  2245. }
  2246. // Delete the base class specifier, since its data has been copied
  2247. // into the CXXRecordDecl.
  2248. Context.Deallocate(Bases[idx]);
  2249. }
  2250. return Invalid;
  2251. }
  2252. /// ActOnBaseSpecifiers - Attach the given base specifiers to the
  2253. /// class, after checking whether there are any duplicate base
  2254. /// classes.
  2255. void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
  2256. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2257. if (!ClassDecl || Bases.empty())
  2258. return;
  2259. AdjustDeclIfTemplate(ClassDecl);
  2260. AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
  2261. }
  2262. /// Determine whether the type \p Derived is a C++ class that is
  2263. /// derived from the type \p Base.
  2264. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
  2265. if (!getLangOpts().CPlusPlus)
  2266. return false;
  2267. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2268. if (!DerivedRD)
  2269. return false;
  2270. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2271. if (!BaseRD)
  2272. return false;
  2273. // If either the base or the derived type is invalid, don't try to
  2274. // check whether one is derived from the other.
  2275. if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
  2276. return false;
  2277. // FIXME: In a modules build, do we need the entire path to be visible for us
  2278. // to be able to use the inheritance relationship?
  2279. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2280. return false;
  2281. return DerivedRD->isDerivedFrom(BaseRD);
  2282. }
  2283. /// Determine whether the type \p Derived is a C++ class that is
  2284. /// derived from the type \p Base.
  2285. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
  2286. CXXBasePaths &Paths) {
  2287. if (!getLangOpts().CPlusPlus)
  2288. return false;
  2289. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2290. if (!DerivedRD)
  2291. return false;
  2292. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2293. if (!BaseRD)
  2294. return false;
  2295. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2296. return false;
  2297. return DerivedRD->isDerivedFrom(BaseRD, Paths);
  2298. }
  2299. static void BuildBasePathArray(const CXXBasePath &Path,
  2300. CXXCastPath &BasePathArray) {
  2301. // We first go backward and check if we have a virtual base.
  2302. // FIXME: It would be better if CXXBasePath had the base specifier for
  2303. // the nearest virtual base.
  2304. unsigned Start = 0;
  2305. for (unsigned I = Path.size(); I != 0; --I) {
  2306. if (Path[I - 1].Base->isVirtual()) {
  2307. Start = I - 1;
  2308. break;
  2309. }
  2310. }
  2311. // Now add all bases.
  2312. for (unsigned I = Start, E = Path.size(); I != E; ++I)
  2313. BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
  2314. }
  2315. void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
  2316. CXXCastPath &BasePathArray) {
  2317. assert(BasePathArray.empty() && "Base path array must be empty!");
  2318. assert(Paths.isRecordingPaths() && "Must record paths!");
  2319. return ::BuildBasePathArray(Paths.front(), BasePathArray);
  2320. }
  2321. /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
  2322. /// conversion (where Derived and Base are class types) is
  2323. /// well-formed, meaning that the conversion is unambiguous (and
  2324. /// that all of the base classes are accessible). Returns true
  2325. /// and emits a diagnostic if the code is ill-formed, returns false
  2326. /// otherwise. Loc is the location where this routine should point to
  2327. /// if there is an error, and Range is the source range to highlight
  2328. /// if there is an error.
  2329. ///
  2330. /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
  2331. /// diagnostic for the respective type of error will be suppressed, but the
  2332. /// check for ill-formed code will still be performed.
  2333. bool
  2334. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2335. unsigned InaccessibleBaseID,
  2336. unsigned AmbigiousBaseConvID,
  2337. SourceLocation Loc, SourceRange Range,
  2338. DeclarationName Name,
  2339. CXXCastPath *BasePath,
  2340. bool IgnoreAccess) {
  2341. // First, determine whether the path from Derived to Base is
  2342. // ambiguous. This is slightly more expensive than checking whether
  2343. // the Derived to Base conversion exists, because here we need to
  2344. // explore multiple paths to determine if there is an ambiguity.
  2345. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2346. /*DetectVirtual=*/false);
  2347. bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2348. if (!DerivationOkay)
  2349. return true;
  2350. const CXXBasePath *Path = nullptr;
  2351. if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
  2352. Path = &Paths.front();
  2353. // For MSVC compatibility, check if Derived directly inherits from Base. Clang
  2354. // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
  2355. // user to access such bases.
  2356. if (!Path && getLangOpts().MSVCCompat) {
  2357. for (const CXXBasePath &PossiblePath : Paths) {
  2358. if (PossiblePath.size() == 1) {
  2359. Path = &PossiblePath;
  2360. if (AmbigiousBaseConvID)
  2361. Diag(Loc, diag::ext_ms_ambiguous_direct_base)
  2362. << Base << Derived << Range;
  2363. break;
  2364. }
  2365. }
  2366. }
  2367. if (Path) {
  2368. if (!IgnoreAccess) {
  2369. // Check that the base class can be accessed.
  2370. switch (
  2371. CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
  2372. case AR_inaccessible:
  2373. return true;
  2374. case AR_accessible:
  2375. case AR_dependent:
  2376. case AR_delayed:
  2377. break;
  2378. }
  2379. }
  2380. // Build a base path if necessary.
  2381. if (BasePath)
  2382. ::BuildBasePathArray(*Path, *BasePath);
  2383. return false;
  2384. }
  2385. if (AmbigiousBaseConvID) {
  2386. // We know that the derived-to-base conversion is ambiguous, and
  2387. // we're going to produce a diagnostic. Perform the derived-to-base
  2388. // search just one more time to compute all of the possible paths so
  2389. // that we can print them out. This is more expensive than any of
  2390. // the previous derived-to-base checks we've done, but at this point
  2391. // performance isn't as much of an issue.
  2392. Paths.clear();
  2393. Paths.setRecordingPaths(true);
  2394. bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2395. assert(StillOkay && "Can only be used with a derived-to-base conversion");
  2396. (void)StillOkay;
  2397. // Build up a textual representation of the ambiguous paths, e.g.,
  2398. // D -> B -> A, that will be used to illustrate the ambiguous
  2399. // conversions in the diagnostic. We only print one of the paths
  2400. // to each base class subobject.
  2401. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2402. Diag(Loc, AmbigiousBaseConvID)
  2403. << Derived << Base << PathDisplayStr << Range << Name;
  2404. }
  2405. return true;
  2406. }
  2407. bool
  2408. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2409. SourceLocation Loc, SourceRange Range,
  2410. CXXCastPath *BasePath,
  2411. bool IgnoreAccess) {
  2412. return CheckDerivedToBaseConversion(
  2413. Derived, Base, diag::err_upcast_to_inaccessible_base,
  2414. diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
  2415. BasePath, IgnoreAccess);
  2416. }
  2417. /// Builds a string representing ambiguous paths from a
  2418. /// specific derived class to different subobjects of the same base
  2419. /// class.
  2420. ///
  2421. /// This function builds a string that can be used in error messages
  2422. /// to show the different paths that one can take through the
  2423. /// inheritance hierarchy to go from the derived class to different
  2424. /// subobjects of a base class. The result looks something like this:
  2425. /// @code
  2426. /// struct D -> struct B -> struct A
  2427. /// struct D -> struct C -> struct A
  2428. /// @endcode
  2429. std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
  2430. std::string PathDisplayStr;
  2431. std::set<unsigned> DisplayedPaths;
  2432. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  2433. Path != Paths.end(); ++Path) {
  2434. if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
  2435. // We haven't displayed a path to this particular base
  2436. // class subobject yet.
  2437. PathDisplayStr += "\n ";
  2438. PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
  2439. for (CXXBasePath::const_iterator Element = Path->begin();
  2440. Element != Path->end(); ++Element)
  2441. PathDisplayStr += " -> " + Element->Base->getType().getAsString();
  2442. }
  2443. }
  2444. return PathDisplayStr;
  2445. }
  2446. //===----------------------------------------------------------------------===//
  2447. // C++ class member Handling
  2448. //===----------------------------------------------------------------------===//
  2449. /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
  2450. bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
  2451. SourceLocation ColonLoc,
  2452. const ParsedAttributesView &Attrs) {
  2453. assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
  2454. AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
  2455. ASLoc, ColonLoc);
  2456. CurContext->addHiddenDecl(ASDecl);
  2457. return ProcessAccessDeclAttributeList(ASDecl, Attrs);
  2458. }
  2459. /// CheckOverrideControl - Check C++11 override control semantics.
  2460. void Sema::CheckOverrideControl(NamedDecl *D) {
  2461. if (D->isInvalidDecl())
  2462. return;
  2463. // We only care about "override" and "final" declarations.
  2464. if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
  2465. return;
  2466. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2467. // We can't check dependent instance methods.
  2468. if (MD && MD->isInstance() &&
  2469. (MD->getParent()->hasAnyDependentBases() ||
  2470. MD->getType()->isDependentType()))
  2471. return;
  2472. if (MD && !MD->isVirtual()) {
  2473. // If we have a non-virtual method, check if if hides a virtual method.
  2474. // (In that case, it's most likely the method has the wrong type.)
  2475. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  2476. FindHiddenVirtualMethods(MD, OverloadedMethods);
  2477. if (!OverloadedMethods.empty()) {
  2478. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2479. Diag(OA->getLocation(),
  2480. diag::override_keyword_hides_virtual_member_function)
  2481. << "override" << (OverloadedMethods.size() > 1);
  2482. } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2483. Diag(FA->getLocation(),
  2484. diag::override_keyword_hides_virtual_member_function)
  2485. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2486. << (OverloadedMethods.size() > 1);
  2487. }
  2488. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  2489. MD->setInvalidDecl();
  2490. return;
  2491. }
  2492. // Fall through into the general case diagnostic.
  2493. // FIXME: We might want to attempt typo correction here.
  2494. }
  2495. if (!MD || !MD->isVirtual()) {
  2496. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2497. Diag(OA->getLocation(),
  2498. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2499. << "override" << FixItHint::CreateRemoval(OA->getLocation());
  2500. D->dropAttr<OverrideAttr>();
  2501. }
  2502. if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2503. Diag(FA->getLocation(),
  2504. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2505. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2506. << FixItHint::CreateRemoval(FA->getLocation());
  2507. D->dropAttr<FinalAttr>();
  2508. }
  2509. return;
  2510. }
  2511. // C++11 [class.virtual]p5:
  2512. // If a function is marked with the virt-specifier override and
  2513. // does not override a member function of a base class, the program is
  2514. // ill-formed.
  2515. bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
  2516. if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
  2517. Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
  2518. << MD->getDeclName();
  2519. }
  2520. void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
  2521. if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
  2522. return;
  2523. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2524. if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
  2525. return;
  2526. SourceLocation Loc = MD->getLocation();
  2527. SourceLocation SpellingLoc = Loc;
  2528. if (getSourceManager().isMacroArgExpansion(Loc))
  2529. SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
  2530. SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
  2531. if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
  2532. return;
  2533. if (MD->size_overridden_methods() > 0) {
  2534. unsigned DiagID = isa<CXXDestructorDecl>(MD)
  2535. ? diag::warn_destructor_marked_not_override_overriding
  2536. : diag::warn_function_marked_not_override_overriding;
  2537. Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  2538. const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
  2539. Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
  2540. }
  2541. }
  2542. /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
  2543. /// function overrides a virtual member function marked 'final', according to
  2544. /// C++11 [class.virtual]p4.
  2545. bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
  2546. const CXXMethodDecl *Old) {
  2547. FinalAttr *FA = Old->getAttr<FinalAttr>();
  2548. if (!FA)
  2549. return false;
  2550. Diag(New->getLocation(), diag::err_final_function_overridden)
  2551. << New->getDeclName()
  2552. << FA->isSpelledAsSealed();
  2553. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  2554. return true;
  2555. }
  2556. static bool InitializationHasSideEffects(const FieldDecl &FD) {
  2557. const Type *T = FD.getType()->getBaseElementTypeUnsafe();
  2558. // FIXME: Destruction of ObjC lifetime types has side-effects.
  2559. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  2560. return !RD->isCompleteDefinition() ||
  2561. !RD->hasTrivialDefaultConstructor() ||
  2562. !RD->hasTrivialDestructor();
  2563. return false;
  2564. }
  2565. static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
  2566. ParsedAttributesView::const_iterator Itr =
  2567. llvm::find_if(list, [](const ParsedAttr &AL) {
  2568. return AL.isDeclspecPropertyAttribute();
  2569. });
  2570. if (Itr != list.end())
  2571. return &*Itr;
  2572. return nullptr;
  2573. }
  2574. // Check if there is a field shadowing.
  2575. void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
  2576. DeclarationName FieldName,
  2577. const CXXRecordDecl *RD,
  2578. bool DeclIsField) {
  2579. if (Diags.isIgnored(diag::warn_shadow_field, Loc))
  2580. return;
  2581. // To record a shadowed field in a base
  2582. std::map<CXXRecordDecl*, NamedDecl*> Bases;
  2583. auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
  2584. CXXBasePath &Path) {
  2585. const auto Base = Specifier->getType()->getAsCXXRecordDecl();
  2586. // Record an ambiguous path directly
  2587. if (Bases.find(Base) != Bases.end())
  2588. return true;
  2589. for (const auto Field : Base->lookup(FieldName)) {
  2590. if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
  2591. Field->getAccess() != AS_private) {
  2592. assert(Field->getAccess() != AS_none);
  2593. assert(Bases.find(Base) == Bases.end());
  2594. Bases[Base] = Field;
  2595. return true;
  2596. }
  2597. }
  2598. return false;
  2599. };
  2600. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2601. /*DetectVirtual=*/true);
  2602. if (!RD->lookupInBases(FieldShadowed, Paths))
  2603. return;
  2604. for (const auto &P : Paths) {
  2605. auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
  2606. auto It = Bases.find(Base);
  2607. // Skip duplicated bases
  2608. if (It == Bases.end())
  2609. continue;
  2610. auto BaseField = It->second;
  2611. assert(BaseField->getAccess() != AS_private);
  2612. if (AS_none !=
  2613. CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
  2614. Diag(Loc, diag::warn_shadow_field)
  2615. << FieldName << RD << Base << DeclIsField;
  2616. Diag(BaseField->getLocation(), diag::note_shadow_field);
  2617. Bases.erase(It);
  2618. }
  2619. }
  2620. }
  2621. /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
  2622. /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
  2623. /// bitfield width if there is one, 'InitExpr' specifies the initializer if
  2624. /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
  2625. /// present (but parsing it has been deferred).
  2626. NamedDecl *
  2627. Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
  2628. MultiTemplateParamsArg TemplateParameterLists,
  2629. Expr *BW, const VirtSpecifiers &VS,
  2630. InClassInitStyle InitStyle) {
  2631. const DeclSpec &DS = D.getDeclSpec();
  2632. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  2633. DeclarationName Name = NameInfo.getName();
  2634. SourceLocation Loc = NameInfo.getLoc();
  2635. // For anonymous bitfields, the location should point to the type.
  2636. if (Loc.isInvalid())
  2637. Loc = D.getBeginLoc();
  2638. Expr *BitWidth = static_cast<Expr*>(BW);
  2639. assert(isa<CXXRecordDecl>(CurContext));
  2640. assert(!DS.isFriendSpecified());
  2641. bool isFunc = D.isDeclarationOfFunction();
  2642. const ParsedAttr *MSPropertyAttr =
  2643. getMSPropertyAttr(D.getDeclSpec().getAttributes());
  2644. if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
  2645. // The Microsoft extension __interface only permits public member functions
  2646. // and prohibits constructors, destructors, operators, non-public member
  2647. // functions, static methods and data members.
  2648. unsigned InvalidDecl;
  2649. bool ShowDeclName = true;
  2650. if (!isFunc &&
  2651. (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
  2652. InvalidDecl = 0;
  2653. else if (!isFunc)
  2654. InvalidDecl = 1;
  2655. else if (AS != AS_public)
  2656. InvalidDecl = 2;
  2657. else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
  2658. InvalidDecl = 3;
  2659. else switch (Name.getNameKind()) {
  2660. case DeclarationName::CXXConstructorName:
  2661. InvalidDecl = 4;
  2662. ShowDeclName = false;
  2663. break;
  2664. case DeclarationName::CXXDestructorName:
  2665. InvalidDecl = 5;
  2666. ShowDeclName = false;
  2667. break;
  2668. case DeclarationName::CXXOperatorName:
  2669. case DeclarationName::CXXConversionFunctionName:
  2670. InvalidDecl = 6;
  2671. break;
  2672. default:
  2673. InvalidDecl = 0;
  2674. break;
  2675. }
  2676. if (InvalidDecl) {
  2677. if (ShowDeclName)
  2678. Diag(Loc, diag::err_invalid_member_in_interface)
  2679. << (InvalidDecl-1) << Name;
  2680. else
  2681. Diag(Loc, diag::err_invalid_member_in_interface)
  2682. << (InvalidDecl-1) << "";
  2683. return nullptr;
  2684. }
  2685. }
  2686. // C++ 9.2p6: A member shall not be declared to have automatic storage
  2687. // duration (auto, register) or with the extern storage-class-specifier.
  2688. // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
  2689. // data members and cannot be applied to names declared const or static,
  2690. // and cannot be applied to reference members.
  2691. switch (DS.getStorageClassSpec()) {
  2692. case DeclSpec::SCS_unspecified:
  2693. case DeclSpec::SCS_typedef:
  2694. case DeclSpec::SCS_static:
  2695. break;
  2696. case DeclSpec::SCS_mutable:
  2697. if (isFunc) {
  2698. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
  2699. // FIXME: It would be nicer if the keyword was ignored only for this
  2700. // declarator. Otherwise we could get follow-up errors.
  2701. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2702. }
  2703. break;
  2704. default:
  2705. Diag(DS.getStorageClassSpecLoc(),
  2706. diag::err_storageclass_invalid_for_member);
  2707. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2708. break;
  2709. }
  2710. bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
  2711. DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
  2712. !isFunc);
  2713. if (DS.hasConstexprSpecifier() && isInstField) {
  2714. SemaDiagnosticBuilder B =
  2715. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
  2716. SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
  2717. if (InitStyle == ICIS_NoInit) {
  2718. B << 0 << 0;
  2719. if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
  2720. B << FixItHint::CreateRemoval(ConstexprLoc);
  2721. else {
  2722. B << FixItHint::CreateReplacement(ConstexprLoc, "const");
  2723. D.getMutableDeclSpec().ClearConstexprSpec();
  2724. const char *PrevSpec;
  2725. unsigned DiagID;
  2726. bool Failed = D.getMutableDeclSpec().SetTypeQual(
  2727. DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
  2728. (void)Failed;
  2729. assert(!Failed && "Making a constexpr member const shouldn't fail");
  2730. }
  2731. } else {
  2732. B << 1;
  2733. const char *PrevSpec;
  2734. unsigned DiagID;
  2735. if (D.getMutableDeclSpec().SetStorageClassSpec(
  2736. *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
  2737. Context.getPrintingPolicy())) {
  2738. assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
  2739. "This is the only DeclSpec that should fail to be applied");
  2740. B << 1;
  2741. } else {
  2742. B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
  2743. isInstField = false;
  2744. }
  2745. }
  2746. }
  2747. NamedDecl *Member;
  2748. if (isInstField) {
  2749. CXXScopeSpec &SS = D.getCXXScopeSpec();
  2750. // Data members must have identifiers for names.
  2751. if (!Name.isIdentifier()) {
  2752. Diag(Loc, diag::err_bad_variable_name)
  2753. << Name;
  2754. return nullptr;
  2755. }
  2756. IdentifierInfo *II = Name.getAsIdentifierInfo();
  2757. // Member field could not be with "template" keyword.
  2758. // So TemplateParameterLists should be empty in this case.
  2759. if (TemplateParameterLists.size()) {
  2760. TemplateParameterList* TemplateParams = TemplateParameterLists[0];
  2761. if (TemplateParams->size()) {
  2762. // There is no such thing as a member field template.
  2763. Diag(D.getIdentifierLoc(), diag::err_template_member)
  2764. << II
  2765. << SourceRange(TemplateParams->getTemplateLoc(),
  2766. TemplateParams->getRAngleLoc());
  2767. } else {
  2768. // There is an extraneous 'template<>' for this member.
  2769. Diag(TemplateParams->getTemplateLoc(),
  2770. diag::err_template_member_noparams)
  2771. << II
  2772. << SourceRange(TemplateParams->getTemplateLoc(),
  2773. TemplateParams->getRAngleLoc());
  2774. }
  2775. return nullptr;
  2776. }
  2777. if (SS.isSet() && !SS.isInvalid()) {
  2778. // The user provided a superfluous scope specifier inside a class
  2779. // definition:
  2780. //
  2781. // class X {
  2782. // int X::member;
  2783. // };
  2784. if (DeclContext *DC = computeDeclContext(SS, false))
  2785. diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
  2786. D.getName().getKind() ==
  2787. UnqualifiedIdKind::IK_TemplateId);
  2788. else
  2789. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  2790. << Name << SS.getRange();
  2791. SS.clear();
  2792. }
  2793. if (MSPropertyAttr) {
  2794. Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2795. BitWidth, InitStyle, AS, *MSPropertyAttr);
  2796. if (!Member)
  2797. return nullptr;
  2798. isInstField = false;
  2799. } else {
  2800. Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2801. BitWidth, InitStyle, AS);
  2802. if (!Member)
  2803. return nullptr;
  2804. }
  2805. CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
  2806. } else {
  2807. Member = HandleDeclarator(S, D, TemplateParameterLists);
  2808. if (!Member)
  2809. return nullptr;
  2810. // Non-instance-fields can't have a bitfield.
  2811. if (BitWidth) {
  2812. if (Member->isInvalidDecl()) {
  2813. // don't emit another diagnostic.
  2814. } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
  2815. // C++ 9.6p3: A bit-field shall not be a static member.
  2816. // "static member 'A' cannot be a bit-field"
  2817. Diag(Loc, diag::err_static_not_bitfield)
  2818. << Name << BitWidth->getSourceRange();
  2819. } else if (isa<TypedefDecl>(Member)) {
  2820. // "typedef member 'x' cannot be a bit-field"
  2821. Diag(Loc, diag::err_typedef_not_bitfield)
  2822. << Name << BitWidth->getSourceRange();
  2823. } else {
  2824. // A function typedef ("typedef int f(); f a;").
  2825. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  2826. Diag(Loc, diag::err_not_integral_type_bitfield)
  2827. << Name << cast<ValueDecl>(Member)->getType()
  2828. << BitWidth->getSourceRange();
  2829. }
  2830. BitWidth = nullptr;
  2831. Member->setInvalidDecl();
  2832. }
  2833. NamedDecl *NonTemplateMember = Member;
  2834. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
  2835. NonTemplateMember = FunTmpl->getTemplatedDecl();
  2836. else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
  2837. NonTemplateMember = VarTmpl->getTemplatedDecl();
  2838. Member->setAccess(AS);
  2839. // If we have declared a member function template or static data member
  2840. // template, set the access of the templated declaration as well.
  2841. if (NonTemplateMember != Member)
  2842. NonTemplateMember->setAccess(AS);
  2843. // C++ [temp.deduct.guide]p3:
  2844. // A deduction guide [...] for a member class template [shall be
  2845. // declared] with the same access [as the template].
  2846. if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
  2847. auto *TD = DG->getDeducedTemplate();
  2848. // Access specifiers are only meaningful if both the template and the
  2849. // deduction guide are from the same scope.
  2850. if (AS != TD->getAccess() &&
  2851. TD->getDeclContext()->getRedeclContext()->Equals(
  2852. DG->getDeclContext()->getRedeclContext())) {
  2853. Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
  2854. Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
  2855. << TD->getAccess();
  2856. const AccessSpecDecl *LastAccessSpec = nullptr;
  2857. for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
  2858. if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
  2859. LastAccessSpec = AccessSpec;
  2860. }
  2861. assert(LastAccessSpec && "differing access with no access specifier");
  2862. Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
  2863. << AS;
  2864. }
  2865. }
  2866. }
  2867. if (VS.isOverrideSpecified())
  2868. Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
  2869. if (VS.isFinalSpecified())
  2870. Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
  2871. VS.isFinalSpelledSealed()));
  2872. if (VS.getLastLocation().isValid()) {
  2873. // Update the end location of a method that has a virt-specifiers.
  2874. if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
  2875. MD->setRangeEnd(VS.getLastLocation());
  2876. }
  2877. CheckOverrideControl(Member);
  2878. assert((Name || isInstField) && "No identifier for non-field ?");
  2879. if (isInstField) {
  2880. FieldDecl *FD = cast<FieldDecl>(Member);
  2881. FieldCollector->Add(FD);
  2882. if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
  2883. // Remember all explicit private FieldDecls that have a name, no side
  2884. // effects and are not part of a dependent type declaration.
  2885. if (!FD->isImplicit() && FD->getDeclName() &&
  2886. FD->getAccess() == AS_private &&
  2887. !FD->hasAttr<UnusedAttr>() &&
  2888. !FD->getParent()->isDependentContext() &&
  2889. !InitializationHasSideEffects(*FD))
  2890. UnusedPrivateFields.insert(FD);
  2891. }
  2892. }
  2893. return Member;
  2894. }
  2895. namespace {
  2896. class UninitializedFieldVisitor
  2897. : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
  2898. Sema &S;
  2899. // List of Decls to generate a warning on. Also remove Decls that become
  2900. // initialized.
  2901. llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
  2902. // List of base classes of the record. Classes are removed after their
  2903. // initializers.
  2904. llvm::SmallPtrSetImpl<QualType> &BaseClasses;
  2905. // Vector of decls to be removed from the Decl set prior to visiting the
  2906. // nodes. These Decls may have been initialized in the prior initializer.
  2907. llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
  2908. // If non-null, add a note to the warning pointing back to the constructor.
  2909. const CXXConstructorDecl *Constructor;
  2910. // Variables to hold state when processing an initializer list. When
  2911. // InitList is true, special case initialization of FieldDecls matching
  2912. // InitListFieldDecl.
  2913. bool InitList;
  2914. FieldDecl *InitListFieldDecl;
  2915. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  2916. public:
  2917. typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
  2918. UninitializedFieldVisitor(Sema &S,
  2919. llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
  2920. llvm::SmallPtrSetImpl<QualType> &BaseClasses)
  2921. : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
  2922. Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
  2923. // Returns true if the use of ME is not an uninitialized use.
  2924. bool IsInitListMemberExprInitialized(MemberExpr *ME,
  2925. bool CheckReferenceOnly) {
  2926. llvm::SmallVector<FieldDecl*, 4> Fields;
  2927. bool ReferenceField = false;
  2928. while (ME) {
  2929. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  2930. if (!FD)
  2931. return false;
  2932. Fields.push_back(FD);
  2933. if (FD->getType()->isReferenceType())
  2934. ReferenceField = true;
  2935. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
  2936. }
  2937. // Binding a reference to an uninitialized field is not an
  2938. // uninitialized use.
  2939. if (CheckReferenceOnly && !ReferenceField)
  2940. return true;
  2941. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  2942. // Discard the first field since it is the field decl that is being
  2943. // initialized.
  2944. for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
  2945. UsedFieldIndex.push_back((*I)->getFieldIndex());
  2946. }
  2947. for (auto UsedIter = UsedFieldIndex.begin(),
  2948. UsedEnd = UsedFieldIndex.end(),
  2949. OrigIter = InitFieldIndex.begin(),
  2950. OrigEnd = InitFieldIndex.end();
  2951. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  2952. if (*UsedIter < *OrigIter)
  2953. return true;
  2954. if (*UsedIter > *OrigIter)
  2955. break;
  2956. }
  2957. return false;
  2958. }
  2959. void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
  2960. bool AddressOf) {
  2961. if (isa<EnumConstantDecl>(ME->getMemberDecl()))
  2962. return;
  2963. // FieldME is the inner-most MemberExpr that is not an anonymous struct
  2964. // or union.
  2965. MemberExpr *FieldME = ME;
  2966. bool AllPODFields = FieldME->getType().isPODType(S.Context);
  2967. Expr *Base = ME;
  2968. while (MemberExpr *SubME =
  2969. dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
  2970. if (isa<VarDecl>(SubME->getMemberDecl()))
  2971. return;
  2972. if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
  2973. if (!FD->isAnonymousStructOrUnion())
  2974. FieldME = SubME;
  2975. if (!FieldME->getType().isPODType(S.Context))
  2976. AllPODFields = false;
  2977. Base = SubME->getBase();
  2978. }
  2979. if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
  2980. return;
  2981. if (AddressOf && AllPODFields)
  2982. return;
  2983. ValueDecl* FoundVD = FieldME->getMemberDecl();
  2984. if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
  2985. while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
  2986. BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
  2987. }
  2988. if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
  2989. QualType T = BaseCast->getType();
  2990. if (T->isPointerType() &&
  2991. BaseClasses.count(T->getPointeeType())) {
  2992. S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
  2993. << T->getPointeeType() << FoundVD;
  2994. }
  2995. }
  2996. }
  2997. if (!Decls.count(FoundVD))
  2998. return;
  2999. const bool IsReference = FoundVD->getType()->isReferenceType();
  3000. if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
  3001. // Special checking for initializer lists.
  3002. if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
  3003. return;
  3004. }
  3005. } else {
  3006. // Prevent double warnings on use of unbounded references.
  3007. if (CheckReferenceOnly && !IsReference)
  3008. return;
  3009. }
  3010. unsigned diag = IsReference
  3011. ? diag::warn_reference_field_is_uninit
  3012. : diag::warn_field_is_uninit;
  3013. S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
  3014. if (Constructor)
  3015. S.Diag(Constructor->getLocation(),
  3016. diag::note_uninit_in_this_constructor)
  3017. << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
  3018. }
  3019. void HandleValue(Expr *E, bool AddressOf) {
  3020. E = E->IgnoreParens();
  3021. if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3022. HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
  3023. AddressOf /*AddressOf*/);
  3024. return;
  3025. }
  3026. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  3027. Visit(CO->getCond());
  3028. HandleValue(CO->getTrueExpr(), AddressOf);
  3029. HandleValue(CO->getFalseExpr(), AddressOf);
  3030. return;
  3031. }
  3032. if (BinaryConditionalOperator *BCO =
  3033. dyn_cast<BinaryConditionalOperator>(E)) {
  3034. Visit(BCO->getCond());
  3035. HandleValue(BCO->getFalseExpr(), AddressOf);
  3036. return;
  3037. }
  3038. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  3039. HandleValue(OVE->getSourceExpr(), AddressOf);
  3040. return;
  3041. }
  3042. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  3043. switch (BO->getOpcode()) {
  3044. default:
  3045. break;
  3046. case(BO_PtrMemD):
  3047. case(BO_PtrMemI):
  3048. HandleValue(BO->getLHS(), AddressOf);
  3049. Visit(BO->getRHS());
  3050. return;
  3051. case(BO_Comma):
  3052. Visit(BO->getLHS());
  3053. HandleValue(BO->getRHS(), AddressOf);
  3054. return;
  3055. }
  3056. }
  3057. Visit(E);
  3058. }
  3059. void CheckInitListExpr(InitListExpr *ILE) {
  3060. InitFieldIndex.push_back(0);
  3061. for (auto Child : ILE->children()) {
  3062. if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
  3063. CheckInitListExpr(SubList);
  3064. } else {
  3065. Visit(Child);
  3066. }
  3067. ++InitFieldIndex.back();
  3068. }
  3069. InitFieldIndex.pop_back();
  3070. }
  3071. void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
  3072. FieldDecl *Field, const Type *BaseClass) {
  3073. // Remove Decls that may have been initialized in the previous
  3074. // initializer.
  3075. for (ValueDecl* VD : DeclsToRemove)
  3076. Decls.erase(VD);
  3077. DeclsToRemove.clear();
  3078. Constructor = FieldConstructor;
  3079. InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  3080. if (ILE && Field) {
  3081. InitList = true;
  3082. InitListFieldDecl = Field;
  3083. InitFieldIndex.clear();
  3084. CheckInitListExpr(ILE);
  3085. } else {
  3086. InitList = false;
  3087. Visit(E);
  3088. }
  3089. if (Field)
  3090. Decls.erase(Field);
  3091. if (BaseClass)
  3092. BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
  3093. }
  3094. void VisitMemberExpr(MemberExpr *ME) {
  3095. // All uses of unbounded reference fields will warn.
  3096. HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
  3097. }
  3098. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  3099. if (E->getCastKind() == CK_LValueToRValue) {
  3100. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3101. return;
  3102. }
  3103. Inherited::VisitImplicitCastExpr(E);
  3104. }
  3105. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  3106. if (E->getConstructor()->isCopyConstructor()) {
  3107. Expr *ArgExpr = E->getArg(0);
  3108. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  3109. if (ILE->getNumInits() == 1)
  3110. ArgExpr = ILE->getInit(0);
  3111. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  3112. if (ICE->getCastKind() == CK_NoOp)
  3113. ArgExpr = ICE->getSubExpr();
  3114. HandleValue(ArgExpr, false /*AddressOf*/);
  3115. return;
  3116. }
  3117. Inherited::VisitCXXConstructExpr(E);
  3118. }
  3119. void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  3120. Expr *Callee = E->getCallee();
  3121. if (isa<MemberExpr>(Callee)) {
  3122. HandleValue(Callee, false /*AddressOf*/);
  3123. for (auto Arg : E->arguments())
  3124. Visit(Arg);
  3125. return;
  3126. }
  3127. Inherited::VisitCXXMemberCallExpr(E);
  3128. }
  3129. void VisitCallExpr(CallExpr *E) {
  3130. // Treat std::move as a use.
  3131. if (E->isCallToStdMove()) {
  3132. HandleValue(E->getArg(0), /*AddressOf=*/false);
  3133. return;
  3134. }
  3135. Inherited::VisitCallExpr(E);
  3136. }
  3137. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  3138. Expr *Callee = E->getCallee();
  3139. if (isa<UnresolvedLookupExpr>(Callee))
  3140. return Inherited::VisitCXXOperatorCallExpr(E);
  3141. Visit(Callee);
  3142. for (auto Arg : E->arguments())
  3143. HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
  3144. }
  3145. void VisitBinaryOperator(BinaryOperator *E) {
  3146. // If a field assignment is detected, remove the field from the
  3147. // uninitiailized field set.
  3148. if (E->getOpcode() == BO_Assign)
  3149. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
  3150. if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  3151. if (!FD->getType()->isReferenceType())
  3152. DeclsToRemove.push_back(FD);
  3153. if (E->isCompoundAssignmentOp()) {
  3154. HandleValue(E->getLHS(), false /*AddressOf*/);
  3155. Visit(E->getRHS());
  3156. return;
  3157. }
  3158. Inherited::VisitBinaryOperator(E);
  3159. }
  3160. void VisitUnaryOperator(UnaryOperator *E) {
  3161. if (E->isIncrementDecrementOp()) {
  3162. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3163. return;
  3164. }
  3165. if (E->getOpcode() == UO_AddrOf) {
  3166. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
  3167. HandleValue(ME->getBase(), true /*AddressOf*/);
  3168. return;
  3169. }
  3170. }
  3171. Inherited::VisitUnaryOperator(E);
  3172. }
  3173. };
  3174. // Diagnose value-uses of fields to initialize themselves, e.g.
  3175. // foo(foo)
  3176. // where foo is not also a parameter to the constructor.
  3177. // Also diagnose across field uninitialized use such as
  3178. // x(y), y(x)
  3179. // TODO: implement -Wuninitialized and fold this into that framework.
  3180. static void DiagnoseUninitializedFields(
  3181. Sema &SemaRef, const CXXConstructorDecl *Constructor) {
  3182. if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
  3183. Constructor->getLocation())) {
  3184. return;
  3185. }
  3186. if (Constructor->isInvalidDecl())
  3187. return;
  3188. const CXXRecordDecl *RD = Constructor->getParent();
  3189. if (RD->getDescribedClassTemplate())
  3190. return;
  3191. // Holds fields that are uninitialized.
  3192. llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
  3193. // At the beginning, all fields are uninitialized.
  3194. for (auto *I : RD->decls()) {
  3195. if (auto *FD = dyn_cast<FieldDecl>(I)) {
  3196. UninitializedFields.insert(FD);
  3197. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
  3198. UninitializedFields.insert(IFD->getAnonField());
  3199. }
  3200. }
  3201. llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
  3202. for (auto I : RD->bases())
  3203. UninitializedBaseClasses.insert(I.getType().getCanonicalType());
  3204. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3205. return;
  3206. UninitializedFieldVisitor UninitializedChecker(SemaRef,
  3207. UninitializedFields,
  3208. UninitializedBaseClasses);
  3209. for (const auto *FieldInit : Constructor->inits()) {
  3210. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3211. break;
  3212. Expr *InitExpr = FieldInit->getInit();
  3213. if (!InitExpr)
  3214. continue;
  3215. if (CXXDefaultInitExpr *Default =
  3216. dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
  3217. InitExpr = Default->getExpr();
  3218. if (!InitExpr)
  3219. continue;
  3220. // In class initializers will point to the constructor.
  3221. UninitializedChecker.CheckInitializer(InitExpr, Constructor,
  3222. FieldInit->getAnyMember(),
  3223. FieldInit->getBaseClass());
  3224. } else {
  3225. UninitializedChecker.CheckInitializer(InitExpr, nullptr,
  3226. FieldInit->getAnyMember(),
  3227. FieldInit->getBaseClass());
  3228. }
  3229. }
  3230. }
  3231. } // namespace
  3232. /// Enter a new C++ default initializer scope. After calling this, the
  3233. /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
  3234. /// parsing or instantiating the initializer failed.
  3235. void Sema::ActOnStartCXXInClassMemberInitializer() {
  3236. // Create a synthetic function scope to represent the call to the constructor
  3237. // that notionally surrounds a use of this initializer.
  3238. PushFunctionScope();
  3239. }
  3240. /// This is invoked after parsing an in-class initializer for a
  3241. /// non-static C++ class member, and after instantiating an in-class initializer
  3242. /// in a class template. Such actions are deferred until the class is complete.
  3243. void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
  3244. SourceLocation InitLoc,
  3245. Expr *InitExpr) {
  3246. // Pop the notional constructor scope we created earlier.
  3247. PopFunctionScopeInfo(nullptr, D);
  3248. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  3249. assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
  3250. "must set init style when field is created");
  3251. if (!InitExpr) {
  3252. D->setInvalidDecl();
  3253. if (FD)
  3254. FD->removeInClassInitializer();
  3255. return;
  3256. }
  3257. if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
  3258. FD->setInvalidDecl();
  3259. FD->removeInClassInitializer();
  3260. return;
  3261. }
  3262. ExprResult Init = InitExpr;
  3263. if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
  3264. InitializedEntity Entity =
  3265. InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
  3266. InitializationKind Kind =
  3267. FD->getInClassInitStyle() == ICIS_ListInit
  3268. ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
  3269. InitExpr->getBeginLoc(),
  3270. InitExpr->getEndLoc())
  3271. : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
  3272. InitializationSequence Seq(*this, Entity, Kind, InitExpr);
  3273. Init = Seq.Perform(*this, Entity, Kind, InitExpr);
  3274. if (Init.isInvalid()) {
  3275. FD->setInvalidDecl();
  3276. return;
  3277. }
  3278. }
  3279. // C++11 [class.base.init]p7:
  3280. // The initialization of each base and member constitutes a
  3281. // full-expression.
  3282. Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
  3283. if (Init.isInvalid()) {
  3284. FD->setInvalidDecl();
  3285. return;
  3286. }
  3287. InitExpr = Init.get();
  3288. FD->setInClassInitializer(InitExpr);
  3289. }
  3290. /// Find the direct and/or virtual base specifiers that
  3291. /// correspond to the given base type, for use in base initialization
  3292. /// within a constructor.
  3293. static bool FindBaseInitializer(Sema &SemaRef,
  3294. CXXRecordDecl *ClassDecl,
  3295. QualType BaseType,
  3296. const CXXBaseSpecifier *&DirectBaseSpec,
  3297. const CXXBaseSpecifier *&VirtualBaseSpec) {
  3298. // First, check for a direct base class.
  3299. DirectBaseSpec = nullptr;
  3300. for (const auto &Base : ClassDecl->bases()) {
  3301. if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
  3302. // We found a direct base of this type. That's what we're
  3303. // initializing.
  3304. DirectBaseSpec = &Base;
  3305. break;
  3306. }
  3307. }
  3308. // Check for a virtual base class.
  3309. // FIXME: We might be able to short-circuit this if we know in advance that
  3310. // there are no virtual bases.
  3311. VirtualBaseSpec = nullptr;
  3312. if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
  3313. // We haven't found a base yet; search the class hierarchy for a
  3314. // virtual base class.
  3315. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  3316. /*DetectVirtual=*/false);
  3317. if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
  3318. SemaRef.Context.getTypeDeclType(ClassDecl),
  3319. BaseType, Paths)) {
  3320. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  3321. Path != Paths.end(); ++Path) {
  3322. if (Path->back().Base->isVirtual()) {
  3323. VirtualBaseSpec = Path->back().Base;
  3324. break;
  3325. }
  3326. }
  3327. }
  3328. }
  3329. return DirectBaseSpec || VirtualBaseSpec;
  3330. }
  3331. /// Handle a C++ member initializer using braced-init-list syntax.
  3332. MemInitResult
  3333. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3334. Scope *S,
  3335. CXXScopeSpec &SS,
  3336. IdentifierInfo *MemberOrBase,
  3337. ParsedType TemplateTypeTy,
  3338. const DeclSpec &DS,
  3339. SourceLocation IdLoc,
  3340. Expr *InitList,
  3341. SourceLocation EllipsisLoc) {
  3342. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3343. DS, IdLoc, InitList,
  3344. EllipsisLoc);
  3345. }
  3346. /// Handle a C++ member initializer using parentheses syntax.
  3347. MemInitResult
  3348. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3349. Scope *S,
  3350. CXXScopeSpec &SS,
  3351. IdentifierInfo *MemberOrBase,
  3352. ParsedType TemplateTypeTy,
  3353. const DeclSpec &DS,
  3354. SourceLocation IdLoc,
  3355. SourceLocation LParenLoc,
  3356. ArrayRef<Expr *> Args,
  3357. SourceLocation RParenLoc,
  3358. SourceLocation EllipsisLoc) {
  3359. Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
  3360. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3361. DS, IdLoc, List, EllipsisLoc);
  3362. }
  3363. namespace {
  3364. // Callback to only accept typo corrections that can be a valid C++ member
  3365. // intializer: either a non-static field member or a base class.
  3366. class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
  3367. public:
  3368. explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
  3369. : ClassDecl(ClassDecl) {}
  3370. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3371. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  3372. if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
  3373. return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
  3374. return isa<TypeDecl>(ND);
  3375. }
  3376. return false;
  3377. }
  3378. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  3379. return llvm::make_unique<MemInitializerValidatorCCC>(*this);
  3380. }
  3381. private:
  3382. CXXRecordDecl *ClassDecl;
  3383. };
  3384. }
  3385. ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
  3386. CXXScopeSpec &SS,
  3387. ParsedType TemplateTypeTy,
  3388. IdentifierInfo *MemberOrBase) {
  3389. if (SS.getScopeRep() || TemplateTypeTy)
  3390. return nullptr;
  3391. DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
  3392. if (Result.empty())
  3393. return nullptr;
  3394. ValueDecl *Member;
  3395. if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
  3396. (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
  3397. return Member;
  3398. return nullptr;
  3399. }
  3400. /// Handle a C++ member initializer.
  3401. MemInitResult
  3402. Sema::BuildMemInitializer(Decl *ConstructorD,
  3403. Scope *S,
  3404. CXXScopeSpec &SS,
  3405. IdentifierInfo *MemberOrBase,
  3406. ParsedType TemplateTypeTy,
  3407. const DeclSpec &DS,
  3408. SourceLocation IdLoc,
  3409. Expr *Init,
  3410. SourceLocation EllipsisLoc) {
  3411. ExprResult Res = CorrectDelayedTyposInExpr(Init);
  3412. if (!Res.isUsable())
  3413. return true;
  3414. Init = Res.get();
  3415. if (!ConstructorD)
  3416. return true;
  3417. AdjustDeclIfTemplate(ConstructorD);
  3418. CXXConstructorDecl *Constructor
  3419. = dyn_cast<CXXConstructorDecl>(ConstructorD);
  3420. if (!Constructor) {
  3421. // The user wrote a constructor initializer on a function that is
  3422. // not a C++ constructor. Ignore the error for now, because we may
  3423. // have more member initializers coming; we'll diagnose it just
  3424. // once in ActOnMemInitializers.
  3425. return true;
  3426. }
  3427. CXXRecordDecl *ClassDecl = Constructor->getParent();
  3428. // C++ [class.base.init]p2:
  3429. // Names in a mem-initializer-id are looked up in the scope of the
  3430. // constructor's class and, if not found in that scope, are looked
  3431. // up in the scope containing the constructor's definition.
  3432. // [Note: if the constructor's class contains a member with the
  3433. // same name as a direct or virtual base class of the class, a
  3434. // mem-initializer-id naming the member or base class and composed
  3435. // of a single identifier refers to the class member. A
  3436. // mem-initializer-id for the hidden base class may be specified
  3437. // using a qualified name. ]
  3438. // Look for a member, first.
  3439. if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
  3440. ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
  3441. if (EllipsisLoc.isValid())
  3442. Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
  3443. << MemberOrBase
  3444. << SourceRange(IdLoc, Init->getSourceRange().getEnd());
  3445. return BuildMemberInitializer(Member, Init, IdLoc);
  3446. }
  3447. // It didn't name a member, so see if it names a class.
  3448. QualType BaseType;
  3449. TypeSourceInfo *TInfo = nullptr;
  3450. if (TemplateTypeTy) {
  3451. BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
  3452. if (BaseType.isNull())
  3453. return true;
  3454. } else if (DS.getTypeSpecType() == TST_decltype) {
  3455. BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
  3456. } else if (DS.getTypeSpecType() == TST_decltype_auto) {
  3457. Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
  3458. return true;
  3459. } else {
  3460. LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
  3461. LookupParsedName(R, S, &SS);
  3462. TypeDecl *TyD = R.getAsSingle<TypeDecl>();
  3463. if (!TyD) {
  3464. if (R.isAmbiguous()) return true;
  3465. // We don't want access-control diagnostics here.
  3466. R.suppressDiagnostics();
  3467. if (SS.isSet() && isDependentScopeSpecifier(SS)) {
  3468. bool NotUnknownSpecialization = false;
  3469. DeclContext *DC = computeDeclContext(SS, false);
  3470. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
  3471. NotUnknownSpecialization = !Record->hasAnyDependentBases();
  3472. if (!NotUnknownSpecialization) {
  3473. // When the scope specifier can refer to a member of an unknown
  3474. // specialization, we take it as a type name.
  3475. BaseType = CheckTypenameType(ETK_None, SourceLocation(),
  3476. SS.getWithLocInContext(Context),
  3477. *MemberOrBase, IdLoc);
  3478. if (BaseType.isNull())
  3479. return true;
  3480. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3481. DependentNameTypeLoc TL =
  3482. TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
  3483. if (!TL.isNull()) {
  3484. TL.setNameLoc(IdLoc);
  3485. TL.setElaboratedKeywordLoc(SourceLocation());
  3486. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3487. }
  3488. R.clear();
  3489. R.setLookupName(MemberOrBase);
  3490. }
  3491. }
  3492. // If no results were found, try to correct typos.
  3493. TypoCorrection Corr;
  3494. MemInitializerValidatorCCC CCC(ClassDecl);
  3495. if (R.empty() && BaseType.isNull() &&
  3496. (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  3497. CCC, CTK_ErrorRecovery, ClassDecl))) {
  3498. if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
  3499. // We have found a non-static data member with a similar
  3500. // name to what was typed; complain and initialize that
  3501. // member.
  3502. diagnoseTypo(Corr,
  3503. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3504. << MemberOrBase << true);
  3505. return BuildMemberInitializer(Member, Init, IdLoc);
  3506. } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
  3507. const CXXBaseSpecifier *DirectBaseSpec;
  3508. const CXXBaseSpecifier *VirtualBaseSpec;
  3509. if (FindBaseInitializer(*this, ClassDecl,
  3510. Context.getTypeDeclType(Type),
  3511. DirectBaseSpec, VirtualBaseSpec)) {
  3512. // We have found a direct or virtual base class with a
  3513. // similar name to what was typed; complain and initialize
  3514. // that base class.
  3515. diagnoseTypo(Corr,
  3516. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3517. << MemberOrBase << false,
  3518. PDiag() /*Suppress note, we provide our own.*/);
  3519. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
  3520. : VirtualBaseSpec;
  3521. Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
  3522. << BaseSpec->getType() << BaseSpec->getSourceRange();
  3523. TyD = Type;
  3524. }
  3525. }
  3526. }
  3527. if (!TyD && BaseType.isNull()) {
  3528. Diag(IdLoc, diag::err_mem_init_not_member_or_class)
  3529. << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
  3530. return true;
  3531. }
  3532. }
  3533. if (BaseType.isNull()) {
  3534. BaseType = Context.getTypeDeclType(TyD);
  3535. MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
  3536. if (SS.isSet()) {
  3537. BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
  3538. BaseType);
  3539. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3540. ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
  3541. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
  3542. TL.setElaboratedKeywordLoc(SourceLocation());
  3543. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3544. }
  3545. }
  3546. }
  3547. if (!TInfo)
  3548. TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
  3549. return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
  3550. }
  3551. MemInitResult
  3552. Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
  3553. SourceLocation IdLoc) {
  3554. FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
  3555. IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
  3556. assert((DirectMember || IndirectMember) &&
  3557. "Member must be a FieldDecl or IndirectFieldDecl");
  3558. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3559. return true;
  3560. if (Member->isInvalidDecl())
  3561. return true;
  3562. MultiExprArg Args;
  3563. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3564. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3565. } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  3566. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  3567. } else {
  3568. // Template instantiation doesn't reconstruct ParenListExprs for us.
  3569. Args = Init;
  3570. }
  3571. SourceRange InitRange = Init->getSourceRange();
  3572. if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
  3573. // Can't check initialization for a member of dependent type or when
  3574. // any of the arguments are type-dependent expressions.
  3575. DiscardCleanupsInEvaluationContext();
  3576. } else {
  3577. bool InitList = false;
  3578. if (isa<InitListExpr>(Init)) {
  3579. InitList = true;
  3580. Args = Init;
  3581. }
  3582. // Initialize the member.
  3583. InitializedEntity MemberEntity =
  3584. DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
  3585. : InitializedEntity::InitializeMember(IndirectMember,
  3586. nullptr);
  3587. InitializationKind Kind =
  3588. InitList ? InitializationKind::CreateDirectList(
  3589. IdLoc, Init->getBeginLoc(), Init->getEndLoc())
  3590. : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
  3591. InitRange.getEnd());
  3592. InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
  3593. ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
  3594. nullptr);
  3595. if (MemberInit.isInvalid())
  3596. return true;
  3597. // C++11 [class.base.init]p7:
  3598. // The initialization of each base and member constitutes a
  3599. // full-expression.
  3600. MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
  3601. /*DiscardedValue*/ false);
  3602. if (MemberInit.isInvalid())
  3603. return true;
  3604. Init = MemberInit.get();
  3605. }
  3606. if (DirectMember) {
  3607. return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
  3608. InitRange.getBegin(), Init,
  3609. InitRange.getEnd());
  3610. } else {
  3611. return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
  3612. InitRange.getBegin(), Init,
  3613. InitRange.getEnd());
  3614. }
  3615. }
  3616. MemInitResult
  3617. Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
  3618. CXXRecordDecl *ClassDecl) {
  3619. SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3620. if (!LangOpts.CPlusPlus11)
  3621. return Diag(NameLoc, diag::err_delegating_ctor)
  3622. << TInfo->getTypeLoc().getLocalSourceRange();
  3623. Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
  3624. bool InitList = true;
  3625. MultiExprArg Args = Init;
  3626. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3627. InitList = false;
  3628. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3629. }
  3630. SourceRange InitRange = Init->getSourceRange();
  3631. // Initialize the object.
  3632. InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
  3633. QualType(ClassDecl->getTypeForDecl(), 0));
  3634. InitializationKind Kind =
  3635. InitList ? InitializationKind::CreateDirectList(
  3636. NameLoc, Init->getBeginLoc(), Init->getEndLoc())
  3637. : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
  3638. InitRange.getEnd());
  3639. InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
  3640. ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
  3641. Args, nullptr);
  3642. if (DelegationInit.isInvalid())
  3643. return true;
  3644. assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
  3645. "Delegating constructor with no target?");
  3646. // C++11 [class.base.init]p7:
  3647. // The initialization of each base and member constitutes a
  3648. // full-expression.
  3649. DelegationInit = ActOnFinishFullExpr(
  3650. DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
  3651. if (DelegationInit.isInvalid())
  3652. return true;
  3653. // If we are in a dependent context, template instantiation will
  3654. // perform this type-checking again. Just save the arguments that we
  3655. // received in a ParenListExpr.
  3656. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3657. // of the information that we have about the base
  3658. // initializer. However, deconstructing the ASTs is a dicey process,
  3659. // and this approach is far more likely to get the corner cases right.
  3660. if (CurContext->isDependentContext())
  3661. DelegationInit = Init;
  3662. return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
  3663. DelegationInit.getAs<Expr>(),
  3664. InitRange.getEnd());
  3665. }
  3666. MemInitResult
  3667. Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
  3668. Expr *Init, CXXRecordDecl *ClassDecl,
  3669. SourceLocation EllipsisLoc) {
  3670. SourceLocation BaseLoc
  3671. = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3672. if (!BaseType->isDependentType() && !BaseType->isRecordType())
  3673. return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
  3674. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3675. // C++ [class.base.init]p2:
  3676. // [...] Unless the mem-initializer-id names a nonstatic data
  3677. // member of the constructor's class or a direct or virtual base
  3678. // of that class, the mem-initializer is ill-formed. A
  3679. // mem-initializer-list can initialize a base class using any
  3680. // name that denotes that base class type.
  3681. bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
  3682. SourceRange InitRange = Init->getSourceRange();
  3683. if (EllipsisLoc.isValid()) {
  3684. // This is a pack expansion.
  3685. if (!BaseType->containsUnexpandedParameterPack()) {
  3686. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  3687. << SourceRange(BaseLoc, InitRange.getEnd());
  3688. EllipsisLoc = SourceLocation();
  3689. }
  3690. } else {
  3691. // Check for any unexpanded parameter packs.
  3692. if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
  3693. return true;
  3694. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3695. return true;
  3696. }
  3697. // Check for direct and virtual base classes.
  3698. const CXXBaseSpecifier *DirectBaseSpec = nullptr;
  3699. const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
  3700. if (!Dependent) {
  3701. if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
  3702. BaseType))
  3703. return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
  3704. FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
  3705. VirtualBaseSpec);
  3706. // C++ [base.class.init]p2:
  3707. // Unless the mem-initializer-id names a nonstatic data member of the
  3708. // constructor's class or a direct or virtual base of that class, the
  3709. // mem-initializer is ill-formed.
  3710. if (!DirectBaseSpec && !VirtualBaseSpec) {
  3711. // If the class has any dependent bases, then it's possible that
  3712. // one of those types will resolve to the same type as
  3713. // BaseType. Therefore, just treat this as a dependent base
  3714. // class initialization. FIXME: Should we try to check the
  3715. // initialization anyway? It seems odd.
  3716. if (ClassDecl->hasAnyDependentBases())
  3717. Dependent = true;
  3718. else
  3719. return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
  3720. << BaseType << Context.getTypeDeclType(ClassDecl)
  3721. << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3722. }
  3723. }
  3724. if (Dependent) {
  3725. DiscardCleanupsInEvaluationContext();
  3726. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3727. /*IsVirtual=*/false,
  3728. InitRange.getBegin(), Init,
  3729. InitRange.getEnd(), EllipsisLoc);
  3730. }
  3731. // C++ [base.class.init]p2:
  3732. // If a mem-initializer-id is ambiguous because it designates both
  3733. // a direct non-virtual base class and an inherited virtual base
  3734. // class, the mem-initializer is ill-formed.
  3735. if (DirectBaseSpec && VirtualBaseSpec)
  3736. return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
  3737. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3738. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
  3739. if (!BaseSpec)
  3740. BaseSpec = VirtualBaseSpec;
  3741. // Initialize the base.
  3742. bool InitList = true;
  3743. MultiExprArg Args = Init;
  3744. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3745. InitList = false;
  3746. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3747. }
  3748. InitializedEntity BaseEntity =
  3749. InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
  3750. InitializationKind Kind =
  3751. InitList ? InitializationKind::CreateDirectList(BaseLoc)
  3752. : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
  3753. InitRange.getEnd());
  3754. InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
  3755. ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
  3756. if (BaseInit.isInvalid())
  3757. return true;
  3758. // C++11 [class.base.init]p7:
  3759. // The initialization of each base and member constitutes a
  3760. // full-expression.
  3761. BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
  3762. /*DiscardedValue*/ false);
  3763. if (BaseInit.isInvalid())
  3764. return true;
  3765. // If we are in a dependent context, template instantiation will
  3766. // perform this type-checking again. Just save the arguments that we
  3767. // received in a ParenListExpr.
  3768. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3769. // of the information that we have about the base
  3770. // initializer. However, deconstructing the ASTs is a dicey process,
  3771. // and this approach is far more likely to get the corner cases right.
  3772. if (CurContext->isDependentContext())
  3773. BaseInit = Init;
  3774. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3775. BaseSpec->isVirtual(),
  3776. InitRange.getBegin(),
  3777. BaseInit.getAs<Expr>(),
  3778. InitRange.getEnd(), EllipsisLoc);
  3779. }
  3780. // Create a static_cast\<T&&>(expr).
  3781. static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
  3782. if (T.isNull()) T = E->getType();
  3783. QualType TargetType = SemaRef.BuildReferenceType(
  3784. T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
  3785. SourceLocation ExprLoc = E->getBeginLoc();
  3786. TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
  3787. TargetType, ExprLoc);
  3788. return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  3789. SourceRange(ExprLoc, ExprLoc),
  3790. E->getSourceRange()).get();
  3791. }
  3792. /// ImplicitInitializerKind - How an implicit base or member initializer should
  3793. /// initialize its base or member.
  3794. enum ImplicitInitializerKind {
  3795. IIK_Default,
  3796. IIK_Copy,
  3797. IIK_Move,
  3798. IIK_Inherit
  3799. };
  3800. static bool
  3801. BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3802. ImplicitInitializerKind ImplicitInitKind,
  3803. CXXBaseSpecifier *BaseSpec,
  3804. bool IsInheritedVirtualBase,
  3805. CXXCtorInitializer *&CXXBaseInit) {
  3806. InitializedEntity InitEntity
  3807. = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
  3808. IsInheritedVirtualBase);
  3809. ExprResult BaseInit;
  3810. switch (ImplicitInitKind) {
  3811. case IIK_Inherit:
  3812. case IIK_Default: {
  3813. InitializationKind InitKind
  3814. = InitializationKind::CreateDefault(Constructor->getLocation());
  3815. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  3816. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  3817. break;
  3818. }
  3819. case IIK_Move:
  3820. case IIK_Copy: {
  3821. bool Moving = ImplicitInitKind == IIK_Move;
  3822. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3823. QualType ParamType = Param->getType().getNonReferenceType();
  3824. Expr *CopyCtorArg =
  3825. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3826. SourceLocation(), Param, false,
  3827. Constructor->getLocation(), ParamType,
  3828. VK_LValue, nullptr);
  3829. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
  3830. // Cast to the base class to avoid ambiguities.
  3831. QualType ArgTy =
  3832. SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
  3833. ParamType.getQualifiers());
  3834. if (Moving) {
  3835. CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
  3836. }
  3837. CXXCastPath BasePath;
  3838. BasePath.push_back(BaseSpec);
  3839. CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
  3840. CK_UncheckedDerivedToBase,
  3841. Moving ? VK_XValue : VK_LValue,
  3842. &BasePath).get();
  3843. InitializationKind InitKind
  3844. = InitializationKind::CreateDirect(Constructor->getLocation(),
  3845. SourceLocation(), SourceLocation());
  3846. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3847. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3848. break;
  3849. }
  3850. }
  3851. BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
  3852. if (BaseInit.isInvalid())
  3853. return true;
  3854. CXXBaseInit =
  3855. new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3856. SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
  3857. SourceLocation()),
  3858. BaseSpec->isVirtual(),
  3859. SourceLocation(),
  3860. BaseInit.getAs<Expr>(),
  3861. SourceLocation(),
  3862. SourceLocation());
  3863. return false;
  3864. }
  3865. static bool RefersToRValueRef(Expr *MemRef) {
  3866. ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
  3867. return Referenced->getType()->isRValueReferenceType();
  3868. }
  3869. static bool
  3870. BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3871. ImplicitInitializerKind ImplicitInitKind,
  3872. FieldDecl *Field, IndirectFieldDecl *Indirect,
  3873. CXXCtorInitializer *&CXXMemberInit) {
  3874. if (Field->isInvalidDecl())
  3875. return true;
  3876. SourceLocation Loc = Constructor->getLocation();
  3877. if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
  3878. bool Moving = ImplicitInitKind == IIK_Move;
  3879. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3880. QualType ParamType = Param->getType().getNonReferenceType();
  3881. // Suppress copying zero-width bitfields.
  3882. if (Field->isZeroLengthBitField(SemaRef.Context))
  3883. return false;
  3884. Expr *MemberExprBase =
  3885. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3886. SourceLocation(), Param, false,
  3887. Loc, ParamType, VK_LValue, nullptr);
  3888. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
  3889. if (Moving) {
  3890. MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
  3891. }
  3892. // Build a reference to this field within the parameter.
  3893. CXXScopeSpec SS;
  3894. LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
  3895. Sema::LookupMemberName);
  3896. MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
  3897. : cast<ValueDecl>(Field), AS_public);
  3898. MemberLookup.resolveKind();
  3899. ExprResult CtorArg
  3900. = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
  3901. ParamType, Loc,
  3902. /*IsArrow=*/false,
  3903. SS,
  3904. /*TemplateKWLoc=*/SourceLocation(),
  3905. /*FirstQualifierInScope=*/nullptr,
  3906. MemberLookup,
  3907. /*TemplateArgs=*/nullptr,
  3908. /*S*/nullptr);
  3909. if (CtorArg.isInvalid())
  3910. return true;
  3911. // C++11 [class.copy]p15:
  3912. // - if a member m has rvalue reference type T&&, it is direct-initialized
  3913. // with static_cast<T&&>(x.m);
  3914. if (RefersToRValueRef(CtorArg.get())) {
  3915. CtorArg = CastForMoving(SemaRef, CtorArg.get());
  3916. }
  3917. InitializedEntity Entity =
  3918. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  3919. /*Implicit*/ true)
  3920. : InitializedEntity::InitializeMember(Field, nullptr,
  3921. /*Implicit*/ true);
  3922. // Direct-initialize to use the copy constructor.
  3923. InitializationKind InitKind =
  3924. InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
  3925. Expr *CtorArgE = CtorArg.getAs<Expr>();
  3926. InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
  3927. ExprResult MemberInit =
  3928. InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
  3929. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  3930. if (MemberInit.isInvalid())
  3931. return true;
  3932. if (Indirect)
  3933. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  3934. SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  3935. else
  3936. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  3937. SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  3938. return false;
  3939. }
  3940. assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
  3941. "Unhandled implicit init kind!");
  3942. QualType FieldBaseElementType =
  3943. SemaRef.Context.getBaseElementType(Field->getType());
  3944. if (FieldBaseElementType->isRecordType()) {
  3945. InitializedEntity InitEntity =
  3946. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  3947. /*Implicit*/ true)
  3948. : InitializedEntity::InitializeMember(Field, nullptr,
  3949. /*Implicit*/ true);
  3950. InitializationKind InitKind =
  3951. InitializationKind::CreateDefault(Loc);
  3952. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  3953. ExprResult MemberInit =
  3954. InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  3955. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  3956. if (MemberInit.isInvalid())
  3957. return true;
  3958. if (Indirect)
  3959. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3960. Indirect, Loc,
  3961. Loc,
  3962. MemberInit.get(),
  3963. Loc);
  3964. else
  3965. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3966. Field, Loc, Loc,
  3967. MemberInit.get(),
  3968. Loc);
  3969. return false;
  3970. }
  3971. if (!Field->getParent()->isUnion()) {
  3972. if (FieldBaseElementType->isReferenceType()) {
  3973. SemaRef.Diag(Constructor->getLocation(),
  3974. diag::err_uninitialized_member_in_ctor)
  3975. << (int)Constructor->isImplicit()
  3976. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  3977. << 0 << Field->getDeclName();
  3978. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  3979. return true;
  3980. }
  3981. if (FieldBaseElementType.isConstQualified()) {
  3982. SemaRef.Diag(Constructor->getLocation(),
  3983. diag::err_uninitialized_member_in_ctor)
  3984. << (int)Constructor->isImplicit()
  3985. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  3986. << 1 << Field->getDeclName();
  3987. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  3988. return true;
  3989. }
  3990. }
  3991. if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
  3992. // ARC and Weak:
  3993. // Default-initialize Objective-C pointers to NULL.
  3994. CXXMemberInit
  3995. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
  3996. Loc, Loc,
  3997. new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
  3998. Loc);
  3999. return false;
  4000. }
  4001. // Nothing to initialize.
  4002. CXXMemberInit = nullptr;
  4003. return false;
  4004. }
  4005. namespace {
  4006. struct BaseAndFieldInfo {
  4007. Sema &S;
  4008. CXXConstructorDecl *Ctor;
  4009. bool AnyErrorsInInits;
  4010. ImplicitInitializerKind IIK;
  4011. llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
  4012. SmallVector<CXXCtorInitializer*, 8> AllToInit;
  4013. llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
  4014. BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
  4015. : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
  4016. bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
  4017. if (Ctor->getInheritedConstructor())
  4018. IIK = IIK_Inherit;
  4019. else if (Generated && Ctor->isCopyConstructor())
  4020. IIK = IIK_Copy;
  4021. else if (Generated && Ctor->isMoveConstructor())
  4022. IIK = IIK_Move;
  4023. else
  4024. IIK = IIK_Default;
  4025. }
  4026. bool isImplicitCopyOrMove() const {
  4027. switch (IIK) {
  4028. case IIK_Copy:
  4029. case IIK_Move:
  4030. return true;
  4031. case IIK_Default:
  4032. case IIK_Inherit:
  4033. return false;
  4034. }
  4035. llvm_unreachable("Invalid ImplicitInitializerKind!");
  4036. }
  4037. bool addFieldInitializer(CXXCtorInitializer *Init) {
  4038. AllToInit.push_back(Init);
  4039. // Check whether this initializer makes the field "used".
  4040. if (Init->getInit()->HasSideEffects(S.Context))
  4041. S.UnusedPrivateFields.remove(Init->getAnyMember());
  4042. return false;
  4043. }
  4044. bool isInactiveUnionMember(FieldDecl *Field) {
  4045. RecordDecl *Record = Field->getParent();
  4046. if (!Record->isUnion())
  4047. return false;
  4048. if (FieldDecl *Active =
  4049. ActiveUnionMember.lookup(Record->getCanonicalDecl()))
  4050. return Active != Field->getCanonicalDecl();
  4051. // In an implicit copy or move constructor, ignore any in-class initializer.
  4052. if (isImplicitCopyOrMove())
  4053. return true;
  4054. // If there's no explicit initialization, the field is active only if it
  4055. // has an in-class initializer...
  4056. if (Field->hasInClassInitializer())
  4057. return false;
  4058. // ... or it's an anonymous struct or union whose class has an in-class
  4059. // initializer.
  4060. if (!Field->isAnonymousStructOrUnion())
  4061. return true;
  4062. CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
  4063. return !FieldRD->hasInClassInitializer();
  4064. }
  4065. /// Determine whether the given field is, or is within, a union member
  4066. /// that is inactive (because there was an initializer given for a different
  4067. /// member of the union, or because the union was not initialized at all).
  4068. bool isWithinInactiveUnionMember(FieldDecl *Field,
  4069. IndirectFieldDecl *Indirect) {
  4070. if (!Indirect)
  4071. return isInactiveUnionMember(Field);
  4072. for (auto *C : Indirect->chain()) {
  4073. FieldDecl *Field = dyn_cast<FieldDecl>(C);
  4074. if (Field && isInactiveUnionMember(Field))
  4075. return true;
  4076. }
  4077. return false;
  4078. }
  4079. };
  4080. }
  4081. /// Determine whether the given type is an incomplete or zero-lenfgth
  4082. /// array type.
  4083. static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
  4084. if (T->isIncompleteArrayType())
  4085. return true;
  4086. while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
  4087. if (!ArrayT->getSize())
  4088. return true;
  4089. T = ArrayT->getElementType();
  4090. }
  4091. return false;
  4092. }
  4093. static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
  4094. FieldDecl *Field,
  4095. IndirectFieldDecl *Indirect = nullptr) {
  4096. if (Field->isInvalidDecl())
  4097. return false;
  4098. // Overwhelmingly common case: we have a direct initializer for this field.
  4099. if (CXXCtorInitializer *Init =
  4100. Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
  4101. return Info.addFieldInitializer(Init);
  4102. // C++11 [class.base.init]p8:
  4103. // if the entity is a non-static data member that has a
  4104. // brace-or-equal-initializer and either
  4105. // -- the constructor's class is a union and no other variant member of that
  4106. // union is designated by a mem-initializer-id or
  4107. // -- the constructor's class is not a union, and, if the entity is a member
  4108. // of an anonymous union, no other member of that union is designated by
  4109. // a mem-initializer-id,
  4110. // the entity is initialized as specified in [dcl.init].
  4111. //
  4112. // We also apply the same rules to handle anonymous structs within anonymous
  4113. // unions.
  4114. if (Info.isWithinInactiveUnionMember(Field, Indirect))
  4115. return false;
  4116. if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
  4117. ExprResult DIE =
  4118. SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
  4119. if (DIE.isInvalid())
  4120. return true;
  4121. auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
  4122. SemaRef.checkInitializerLifetime(Entity, DIE.get());
  4123. CXXCtorInitializer *Init;
  4124. if (Indirect)
  4125. Init = new (SemaRef.Context)
  4126. CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
  4127. SourceLocation(), DIE.get(), SourceLocation());
  4128. else
  4129. Init = new (SemaRef.Context)
  4130. CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
  4131. SourceLocation(), DIE.get(), SourceLocation());
  4132. return Info.addFieldInitializer(Init);
  4133. }
  4134. // Don't initialize incomplete or zero-length arrays.
  4135. if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
  4136. return false;
  4137. // Don't try to build an implicit initializer if there were semantic
  4138. // errors in any of the initializers (and therefore we might be
  4139. // missing some that the user actually wrote).
  4140. if (Info.AnyErrorsInInits)
  4141. return false;
  4142. CXXCtorInitializer *Init = nullptr;
  4143. if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
  4144. Indirect, Init))
  4145. return true;
  4146. if (!Init)
  4147. return false;
  4148. return Info.addFieldInitializer(Init);
  4149. }
  4150. bool
  4151. Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
  4152. CXXCtorInitializer *Initializer) {
  4153. assert(Initializer->isDelegatingInitializer());
  4154. Constructor->setNumCtorInitializers(1);
  4155. CXXCtorInitializer **initializer =
  4156. new (Context) CXXCtorInitializer*[1];
  4157. memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
  4158. Constructor->setCtorInitializers(initializer);
  4159. if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
  4160. MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
  4161. DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
  4162. }
  4163. DelegatingCtorDecls.push_back(Constructor);
  4164. DiagnoseUninitializedFields(*this, Constructor);
  4165. return false;
  4166. }
  4167. bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
  4168. ArrayRef<CXXCtorInitializer *> Initializers) {
  4169. if (Constructor->isDependentContext()) {
  4170. // Just store the initializers as written, they will be checked during
  4171. // instantiation.
  4172. if (!Initializers.empty()) {
  4173. Constructor->setNumCtorInitializers(Initializers.size());
  4174. CXXCtorInitializer **baseOrMemberInitializers =
  4175. new (Context) CXXCtorInitializer*[Initializers.size()];
  4176. memcpy(baseOrMemberInitializers, Initializers.data(),
  4177. Initializers.size() * sizeof(CXXCtorInitializer*));
  4178. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4179. }
  4180. // Let template instantiation know whether we had errors.
  4181. if (AnyErrors)
  4182. Constructor->setInvalidDecl();
  4183. return false;
  4184. }
  4185. BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
  4186. // We need to build the initializer AST according to order of construction
  4187. // and not what user specified in the Initializers list.
  4188. CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
  4189. if (!ClassDecl)
  4190. return true;
  4191. bool HadError = false;
  4192. for (unsigned i = 0; i < Initializers.size(); i++) {
  4193. CXXCtorInitializer *Member = Initializers[i];
  4194. if (Member->isBaseInitializer())
  4195. Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
  4196. else {
  4197. Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
  4198. if (IndirectFieldDecl *F = Member->getIndirectMember()) {
  4199. for (auto *C : F->chain()) {
  4200. FieldDecl *FD = dyn_cast<FieldDecl>(C);
  4201. if (FD && FD->getParent()->isUnion())
  4202. Info.ActiveUnionMember.insert(std::make_pair(
  4203. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4204. }
  4205. } else if (FieldDecl *FD = Member->getMember()) {
  4206. if (FD->getParent()->isUnion())
  4207. Info.ActiveUnionMember.insert(std::make_pair(
  4208. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4209. }
  4210. }
  4211. }
  4212. // Keep track of the direct virtual bases.
  4213. llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
  4214. for (auto &I : ClassDecl->bases()) {
  4215. if (I.isVirtual())
  4216. DirectVBases.insert(&I);
  4217. }
  4218. // Push virtual bases before others.
  4219. for (auto &VBase : ClassDecl->vbases()) {
  4220. if (CXXCtorInitializer *Value
  4221. = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
  4222. // [class.base.init]p7, per DR257:
  4223. // A mem-initializer where the mem-initializer-id names a virtual base
  4224. // class is ignored during execution of a constructor of any class that
  4225. // is not the most derived class.
  4226. if (ClassDecl->isAbstract()) {
  4227. // FIXME: Provide a fixit to remove the base specifier. This requires
  4228. // tracking the location of the associated comma for a base specifier.
  4229. Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
  4230. << VBase.getType() << ClassDecl;
  4231. DiagnoseAbstractType(ClassDecl);
  4232. }
  4233. Info.AllToInit.push_back(Value);
  4234. } else if (!AnyErrors && !ClassDecl->isAbstract()) {
  4235. // [class.base.init]p8, per DR257:
  4236. // If a given [...] base class is not named by a mem-initializer-id
  4237. // [...] and the entity is not a virtual base class of an abstract
  4238. // class, then [...] the entity is default-initialized.
  4239. bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
  4240. CXXCtorInitializer *CXXBaseInit;
  4241. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4242. &VBase, IsInheritedVirtualBase,
  4243. CXXBaseInit)) {
  4244. HadError = true;
  4245. continue;
  4246. }
  4247. Info.AllToInit.push_back(CXXBaseInit);
  4248. }
  4249. }
  4250. // Non-virtual bases.
  4251. for (auto &Base : ClassDecl->bases()) {
  4252. // Virtuals are in the virtual base list and already constructed.
  4253. if (Base.isVirtual())
  4254. continue;
  4255. if (CXXCtorInitializer *Value
  4256. = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
  4257. Info.AllToInit.push_back(Value);
  4258. } else if (!AnyErrors) {
  4259. CXXCtorInitializer *CXXBaseInit;
  4260. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4261. &Base, /*IsInheritedVirtualBase=*/false,
  4262. CXXBaseInit)) {
  4263. HadError = true;
  4264. continue;
  4265. }
  4266. Info.AllToInit.push_back(CXXBaseInit);
  4267. }
  4268. }
  4269. // Fields.
  4270. for (auto *Mem : ClassDecl->decls()) {
  4271. if (auto *F = dyn_cast<FieldDecl>(Mem)) {
  4272. // C++ [class.bit]p2:
  4273. // A declaration for a bit-field that omits the identifier declares an
  4274. // unnamed bit-field. Unnamed bit-fields are not members and cannot be
  4275. // initialized.
  4276. if (F->isUnnamedBitfield())
  4277. continue;
  4278. // If we're not generating the implicit copy/move constructor, then we'll
  4279. // handle anonymous struct/union fields based on their individual
  4280. // indirect fields.
  4281. if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
  4282. continue;
  4283. if (CollectFieldInitializer(*this, Info, F))
  4284. HadError = true;
  4285. continue;
  4286. }
  4287. // Beyond this point, we only consider default initialization.
  4288. if (Info.isImplicitCopyOrMove())
  4289. continue;
  4290. if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
  4291. if (F->getType()->isIncompleteArrayType()) {
  4292. assert(ClassDecl->hasFlexibleArrayMember() &&
  4293. "Incomplete array type is not valid");
  4294. continue;
  4295. }
  4296. // Initialize each field of an anonymous struct individually.
  4297. if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
  4298. HadError = true;
  4299. continue;
  4300. }
  4301. }
  4302. unsigned NumInitializers = Info.AllToInit.size();
  4303. if (NumInitializers > 0) {
  4304. Constructor->setNumCtorInitializers(NumInitializers);
  4305. CXXCtorInitializer **baseOrMemberInitializers =
  4306. new (Context) CXXCtorInitializer*[NumInitializers];
  4307. memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
  4308. NumInitializers * sizeof(CXXCtorInitializer*));
  4309. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4310. // Constructors implicitly reference the base and member
  4311. // destructors.
  4312. MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
  4313. Constructor->getParent());
  4314. }
  4315. return HadError;
  4316. }
  4317. static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
  4318. if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
  4319. const RecordDecl *RD = RT->getDecl();
  4320. if (RD->isAnonymousStructOrUnion()) {
  4321. for (auto *Field : RD->fields())
  4322. PopulateKeysForFields(Field, IdealInits);
  4323. return;
  4324. }
  4325. }
  4326. IdealInits.push_back(Field->getCanonicalDecl());
  4327. }
  4328. static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
  4329. return Context.getCanonicalType(BaseType).getTypePtr();
  4330. }
  4331. static const void *GetKeyForMember(ASTContext &Context,
  4332. CXXCtorInitializer *Member) {
  4333. if (!Member->isAnyMemberInitializer())
  4334. return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
  4335. return Member->getAnyMember()->getCanonicalDecl();
  4336. }
  4337. static void DiagnoseBaseOrMemInitializerOrder(
  4338. Sema &SemaRef, const CXXConstructorDecl *Constructor,
  4339. ArrayRef<CXXCtorInitializer *> Inits) {
  4340. if (Constructor->getDeclContext()->isDependentContext())
  4341. return;
  4342. // Don't check initializers order unless the warning is enabled at the
  4343. // location of at least one initializer.
  4344. bool ShouldCheckOrder = false;
  4345. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4346. CXXCtorInitializer *Init = Inits[InitIndex];
  4347. if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
  4348. Init->getSourceLocation())) {
  4349. ShouldCheckOrder = true;
  4350. break;
  4351. }
  4352. }
  4353. if (!ShouldCheckOrder)
  4354. return;
  4355. // Build the list of bases and members in the order that they'll
  4356. // actually be initialized. The explicit initializers should be in
  4357. // this same order but may be missing things.
  4358. SmallVector<const void*, 32> IdealInitKeys;
  4359. const CXXRecordDecl *ClassDecl = Constructor->getParent();
  4360. // 1. Virtual bases.
  4361. for (const auto &VBase : ClassDecl->vbases())
  4362. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
  4363. // 2. Non-virtual bases.
  4364. for (const auto &Base : ClassDecl->bases()) {
  4365. if (Base.isVirtual())
  4366. continue;
  4367. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
  4368. }
  4369. // 3. Direct fields.
  4370. for (auto *Field : ClassDecl->fields()) {
  4371. if (Field->isUnnamedBitfield())
  4372. continue;
  4373. PopulateKeysForFields(Field, IdealInitKeys);
  4374. }
  4375. unsigned NumIdealInits = IdealInitKeys.size();
  4376. unsigned IdealIndex = 0;
  4377. CXXCtorInitializer *PrevInit = nullptr;
  4378. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4379. CXXCtorInitializer *Init = Inits[InitIndex];
  4380. const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
  4381. // Scan forward to try to find this initializer in the idealized
  4382. // initializers list.
  4383. for (; IdealIndex != NumIdealInits; ++IdealIndex)
  4384. if (InitKey == IdealInitKeys[IdealIndex])
  4385. break;
  4386. // If we didn't find this initializer, it must be because we
  4387. // scanned past it on a previous iteration. That can only
  4388. // happen if we're out of order; emit a warning.
  4389. if (IdealIndex == NumIdealInits && PrevInit) {
  4390. Sema::SemaDiagnosticBuilder D =
  4391. SemaRef.Diag(PrevInit->getSourceLocation(),
  4392. diag::warn_initializer_out_of_order);
  4393. if (PrevInit->isAnyMemberInitializer())
  4394. D << 0 << PrevInit->getAnyMember()->getDeclName();
  4395. else
  4396. D << 1 << PrevInit->getTypeSourceInfo()->getType();
  4397. if (Init->isAnyMemberInitializer())
  4398. D << 0 << Init->getAnyMember()->getDeclName();
  4399. else
  4400. D << 1 << Init->getTypeSourceInfo()->getType();
  4401. // Move back to the initializer's location in the ideal list.
  4402. for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
  4403. if (InitKey == IdealInitKeys[IdealIndex])
  4404. break;
  4405. assert(IdealIndex < NumIdealInits &&
  4406. "initializer not found in initializer list");
  4407. }
  4408. PrevInit = Init;
  4409. }
  4410. }
  4411. namespace {
  4412. bool CheckRedundantInit(Sema &S,
  4413. CXXCtorInitializer *Init,
  4414. CXXCtorInitializer *&PrevInit) {
  4415. if (!PrevInit) {
  4416. PrevInit = Init;
  4417. return false;
  4418. }
  4419. if (FieldDecl *Field = Init->getAnyMember())
  4420. S.Diag(Init->getSourceLocation(),
  4421. diag::err_multiple_mem_initialization)
  4422. << Field->getDeclName()
  4423. << Init->getSourceRange();
  4424. else {
  4425. const Type *BaseClass = Init->getBaseClass();
  4426. assert(BaseClass && "neither field nor base");
  4427. S.Diag(Init->getSourceLocation(),
  4428. diag::err_multiple_base_initialization)
  4429. << QualType(BaseClass, 0)
  4430. << Init->getSourceRange();
  4431. }
  4432. S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
  4433. << 0 << PrevInit->getSourceRange();
  4434. return true;
  4435. }
  4436. typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
  4437. typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
  4438. bool CheckRedundantUnionInit(Sema &S,
  4439. CXXCtorInitializer *Init,
  4440. RedundantUnionMap &Unions) {
  4441. FieldDecl *Field = Init->getAnyMember();
  4442. RecordDecl *Parent = Field->getParent();
  4443. NamedDecl *Child = Field;
  4444. while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
  4445. if (Parent->isUnion()) {
  4446. UnionEntry &En = Unions[Parent];
  4447. if (En.first && En.first != Child) {
  4448. S.Diag(Init->getSourceLocation(),
  4449. diag::err_multiple_mem_union_initialization)
  4450. << Field->getDeclName()
  4451. << Init->getSourceRange();
  4452. S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
  4453. << 0 << En.second->getSourceRange();
  4454. return true;
  4455. }
  4456. if (!En.first) {
  4457. En.first = Child;
  4458. En.second = Init;
  4459. }
  4460. if (!Parent->isAnonymousStructOrUnion())
  4461. return false;
  4462. }
  4463. Child = Parent;
  4464. Parent = cast<RecordDecl>(Parent->getDeclContext());
  4465. }
  4466. return false;
  4467. }
  4468. }
  4469. /// ActOnMemInitializers - Handle the member initializers for a constructor.
  4470. void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
  4471. SourceLocation ColonLoc,
  4472. ArrayRef<CXXCtorInitializer*> MemInits,
  4473. bool AnyErrors) {
  4474. if (!ConstructorDecl)
  4475. return;
  4476. AdjustDeclIfTemplate(ConstructorDecl);
  4477. CXXConstructorDecl *Constructor
  4478. = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
  4479. if (!Constructor) {
  4480. Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
  4481. return;
  4482. }
  4483. // Mapping for the duplicate initializers check.
  4484. // For member initializers, this is keyed with a FieldDecl*.
  4485. // For base initializers, this is keyed with a Type*.
  4486. llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
  4487. // Mapping for the inconsistent anonymous-union initializers check.
  4488. RedundantUnionMap MemberUnions;
  4489. bool HadError = false;
  4490. for (unsigned i = 0; i < MemInits.size(); i++) {
  4491. CXXCtorInitializer *Init = MemInits[i];
  4492. // Set the source order index.
  4493. Init->setSourceOrder(i);
  4494. if (Init->isAnyMemberInitializer()) {
  4495. const void *Key = GetKeyForMember(Context, Init);
  4496. if (CheckRedundantInit(*this, Init, Members[Key]) ||
  4497. CheckRedundantUnionInit(*this, Init, MemberUnions))
  4498. HadError = true;
  4499. } else if (Init->isBaseInitializer()) {
  4500. const void *Key = GetKeyForMember(Context, Init);
  4501. if (CheckRedundantInit(*this, Init, Members[Key]))
  4502. HadError = true;
  4503. } else {
  4504. assert(Init->isDelegatingInitializer());
  4505. // This must be the only initializer
  4506. if (MemInits.size() != 1) {
  4507. Diag(Init->getSourceLocation(),
  4508. diag::err_delegating_initializer_alone)
  4509. << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
  4510. // We will treat this as being the only initializer.
  4511. }
  4512. SetDelegatingInitializer(Constructor, MemInits[i]);
  4513. // Return immediately as the initializer is set.
  4514. return;
  4515. }
  4516. }
  4517. if (HadError)
  4518. return;
  4519. DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
  4520. SetCtorInitializers(Constructor, AnyErrors, MemInits);
  4521. DiagnoseUninitializedFields(*this, Constructor);
  4522. }
  4523. void
  4524. Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
  4525. CXXRecordDecl *ClassDecl) {
  4526. // Ignore dependent contexts. Also ignore unions, since their members never
  4527. // have destructors implicitly called.
  4528. if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
  4529. return;
  4530. // FIXME: all the access-control diagnostics are positioned on the
  4531. // field/base declaration. That's probably good; that said, the
  4532. // user might reasonably want to know why the destructor is being
  4533. // emitted, and we currently don't say.
  4534. // Non-static data members.
  4535. for (auto *Field : ClassDecl->fields()) {
  4536. if (Field->isInvalidDecl())
  4537. continue;
  4538. // Don't destroy incomplete or zero-length arrays.
  4539. if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
  4540. continue;
  4541. QualType FieldType = Context.getBaseElementType(Field->getType());
  4542. const RecordType* RT = FieldType->getAs<RecordType>();
  4543. if (!RT)
  4544. continue;
  4545. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4546. if (FieldClassDecl->isInvalidDecl())
  4547. continue;
  4548. if (FieldClassDecl->hasIrrelevantDestructor())
  4549. continue;
  4550. // The destructor for an implicit anonymous union member is never invoked.
  4551. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  4552. continue;
  4553. CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
  4554. assert(Dtor && "No dtor found for FieldClassDecl!");
  4555. CheckDestructorAccess(Field->getLocation(), Dtor,
  4556. PDiag(diag::err_access_dtor_field)
  4557. << Field->getDeclName()
  4558. << FieldType);
  4559. MarkFunctionReferenced(Location, Dtor);
  4560. DiagnoseUseOfDecl(Dtor, Location);
  4561. }
  4562. // We only potentially invoke the destructors of potentially constructed
  4563. // subobjects.
  4564. bool VisitVirtualBases = !ClassDecl->isAbstract();
  4565. llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
  4566. // Bases.
  4567. for (const auto &Base : ClassDecl->bases()) {
  4568. // Bases are always records in a well-formed non-dependent class.
  4569. const RecordType *RT = Base.getType()->getAs<RecordType>();
  4570. // Remember direct virtual bases.
  4571. if (Base.isVirtual()) {
  4572. if (!VisitVirtualBases)
  4573. continue;
  4574. DirectVirtualBases.insert(RT);
  4575. }
  4576. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4577. // If our base class is invalid, we probably can't get its dtor anyway.
  4578. if (BaseClassDecl->isInvalidDecl())
  4579. continue;
  4580. if (BaseClassDecl->hasIrrelevantDestructor())
  4581. continue;
  4582. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4583. assert(Dtor && "No dtor found for BaseClassDecl!");
  4584. // FIXME: caret should be on the start of the class name
  4585. CheckDestructorAccess(Base.getBeginLoc(), Dtor,
  4586. PDiag(diag::err_access_dtor_base)
  4587. << Base.getType() << Base.getSourceRange(),
  4588. Context.getTypeDeclType(ClassDecl));
  4589. MarkFunctionReferenced(Location, Dtor);
  4590. DiagnoseUseOfDecl(Dtor, Location);
  4591. }
  4592. if (!VisitVirtualBases)
  4593. return;
  4594. // Virtual bases.
  4595. for (const auto &VBase : ClassDecl->vbases()) {
  4596. // Bases are always records in a well-formed non-dependent class.
  4597. const RecordType *RT = VBase.getType()->castAs<RecordType>();
  4598. // Ignore direct virtual bases.
  4599. if (DirectVirtualBases.count(RT))
  4600. continue;
  4601. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4602. // If our base class is invalid, we probably can't get its dtor anyway.
  4603. if (BaseClassDecl->isInvalidDecl())
  4604. continue;
  4605. if (BaseClassDecl->hasIrrelevantDestructor())
  4606. continue;
  4607. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4608. assert(Dtor && "No dtor found for BaseClassDecl!");
  4609. if (CheckDestructorAccess(
  4610. ClassDecl->getLocation(), Dtor,
  4611. PDiag(diag::err_access_dtor_vbase)
  4612. << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
  4613. Context.getTypeDeclType(ClassDecl)) ==
  4614. AR_accessible) {
  4615. CheckDerivedToBaseConversion(
  4616. Context.getTypeDeclType(ClassDecl), VBase.getType(),
  4617. diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
  4618. SourceRange(), DeclarationName(), nullptr);
  4619. }
  4620. MarkFunctionReferenced(Location, Dtor);
  4621. DiagnoseUseOfDecl(Dtor, Location);
  4622. }
  4623. }
  4624. void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
  4625. if (!CDtorDecl)
  4626. return;
  4627. if (CXXConstructorDecl *Constructor
  4628. = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
  4629. SetCtorInitializers(Constructor, /*AnyErrors=*/false);
  4630. DiagnoseUninitializedFields(*this, Constructor);
  4631. }
  4632. }
  4633. bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
  4634. if (!getLangOpts().CPlusPlus)
  4635. return false;
  4636. const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
  4637. if (!RD)
  4638. return false;
  4639. // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
  4640. // class template specialization here, but doing so breaks a lot of code.
  4641. // We can't answer whether something is abstract until it has a
  4642. // definition. If it's currently being defined, we'll walk back
  4643. // over all the declarations when we have a full definition.
  4644. const CXXRecordDecl *Def = RD->getDefinition();
  4645. if (!Def || Def->isBeingDefined())
  4646. return false;
  4647. return RD->isAbstract();
  4648. }
  4649. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  4650. TypeDiagnoser &Diagnoser) {
  4651. if (!isAbstractType(Loc, T))
  4652. return false;
  4653. T = Context.getBaseElementType(T);
  4654. Diagnoser.diagnose(*this, Loc, T);
  4655. DiagnoseAbstractType(T->getAsCXXRecordDecl());
  4656. return true;
  4657. }
  4658. void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
  4659. // Check if we've already emitted the list of pure virtual functions
  4660. // for this class.
  4661. if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
  4662. return;
  4663. // If the diagnostic is suppressed, don't emit the notes. We're only
  4664. // going to emit them once, so try to attach them to a diagnostic we're
  4665. // actually going to show.
  4666. if (Diags.isLastDiagnosticIgnored())
  4667. return;
  4668. CXXFinalOverriderMap FinalOverriders;
  4669. RD->getFinalOverriders(FinalOverriders);
  4670. // Keep a set of seen pure methods so we won't diagnose the same method
  4671. // more than once.
  4672. llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
  4673. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  4674. MEnd = FinalOverriders.end();
  4675. M != MEnd;
  4676. ++M) {
  4677. for (OverridingMethods::iterator SO = M->second.begin(),
  4678. SOEnd = M->second.end();
  4679. SO != SOEnd; ++SO) {
  4680. // C++ [class.abstract]p4:
  4681. // A class is abstract if it contains or inherits at least one
  4682. // pure virtual function for which the final overrider is pure
  4683. // virtual.
  4684. //
  4685. if (SO->second.size() != 1)
  4686. continue;
  4687. if (!SO->second.front().Method->isPure())
  4688. continue;
  4689. if (!SeenPureMethods.insert(SO->second.front().Method).second)
  4690. continue;
  4691. Diag(SO->second.front().Method->getLocation(),
  4692. diag::note_pure_virtual_function)
  4693. << SO->second.front().Method->getDeclName() << RD->getDeclName();
  4694. }
  4695. }
  4696. if (!PureVirtualClassDiagSet)
  4697. PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
  4698. PureVirtualClassDiagSet->insert(RD);
  4699. }
  4700. namespace {
  4701. struct AbstractUsageInfo {
  4702. Sema &S;
  4703. CXXRecordDecl *Record;
  4704. CanQualType AbstractType;
  4705. bool Invalid;
  4706. AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
  4707. : S(S), Record(Record),
  4708. AbstractType(S.Context.getCanonicalType(
  4709. S.Context.getTypeDeclType(Record))),
  4710. Invalid(false) {}
  4711. void DiagnoseAbstractType() {
  4712. if (Invalid) return;
  4713. S.DiagnoseAbstractType(Record);
  4714. Invalid = true;
  4715. }
  4716. void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
  4717. };
  4718. struct CheckAbstractUsage {
  4719. AbstractUsageInfo &Info;
  4720. const NamedDecl *Ctx;
  4721. CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
  4722. : Info(Info), Ctx(Ctx) {}
  4723. void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4724. switch (TL.getTypeLocClass()) {
  4725. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  4726. #define TYPELOC(CLASS, PARENT) \
  4727. case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
  4728. #include "clang/AST/TypeLocNodes.def"
  4729. }
  4730. }
  4731. void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4732. Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
  4733. for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
  4734. if (!TL.getParam(I))
  4735. continue;
  4736. TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
  4737. if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
  4738. }
  4739. }
  4740. void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4741. Visit(TL.getElementLoc(), Sema::AbstractArrayType);
  4742. }
  4743. void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4744. // Visit the type parameters from a permissive context.
  4745. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
  4746. TemplateArgumentLoc TAL = TL.getArgLoc(I);
  4747. if (TAL.getArgument().getKind() == TemplateArgument::Type)
  4748. if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
  4749. Visit(TSI->getTypeLoc(), Sema::AbstractNone);
  4750. // TODO: other template argument types?
  4751. }
  4752. }
  4753. // Visit pointee types from a permissive context.
  4754. #define CheckPolymorphic(Type) \
  4755. void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
  4756. Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
  4757. }
  4758. CheckPolymorphic(PointerTypeLoc)
  4759. CheckPolymorphic(ReferenceTypeLoc)
  4760. CheckPolymorphic(MemberPointerTypeLoc)
  4761. CheckPolymorphic(BlockPointerTypeLoc)
  4762. CheckPolymorphic(AtomicTypeLoc)
  4763. /// Handle all the types we haven't given a more specific
  4764. /// implementation for above.
  4765. void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4766. // Every other kind of type that we haven't called out already
  4767. // that has an inner type is either (1) sugar or (2) contains that
  4768. // inner type in some way as a subobject.
  4769. if (TypeLoc Next = TL.getNextTypeLoc())
  4770. return Visit(Next, Sel);
  4771. // If there's no inner type and we're in a permissive context,
  4772. // don't diagnose.
  4773. if (Sel == Sema::AbstractNone) return;
  4774. // Check whether the type matches the abstract type.
  4775. QualType T = TL.getType();
  4776. if (T->isArrayType()) {
  4777. Sel = Sema::AbstractArrayType;
  4778. T = Info.S.Context.getBaseElementType(T);
  4779. }
  4780. CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
  4781. if (CT != Info.AbstractType) return;
  4782. // It matched; do some magic.
  4783. if (Sel == Sema::AbstractArrayType) {
  4784. Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
  4785. << T << TL.getSourceRange();
  4786. } else {
  4787. Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
  4788. << Sel << T << TL.getSourceRange();
  4789. }
  4790. Info.DiagnoseAbstractType();
  4791. }
  4792. };
  4793. void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
  4794. Sema::AbstractDiagSelID Sel) {
  4795. CheckAbstractUsage(*this, D).Visit(TL, Sel);
  4796. }
  4797. }
  4798. /// Check for invalid uses of an abstract type in a method declaration.
  4799. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4800. CXXMethodDecl *MD) {
  4801. // No need to do the check on definitions, which require that
  4802. // the return/param types be complete.
  4803. if (MD->doesThisDeclarationHaveABody())
  4804. return;
  4805. // For safety's sake, just ignore it if we don't have type source
  4806. // information. This should never happen for non-implicit methods,
  4807. // but...
  4808. if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
  4809. Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
  4810. }
  4811. /// Check for invalid uses of an abstract type within a class definition.
  4812. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4813. CXXRecordDecl *RD) {
  4814. for (auto *D : RD->decls()) {
  4815. if (D->isImplicit()) continue;
  4816. // Methods and method templates.
  4817. if (isa<CXXMethodDecl>(D)) {
  4818. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
  4819. } else if (isa<FunctionTemplateDecl>(D)) {
  4820. FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
  4821. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
  4822. // Fields and static variables.
  4823. } else if (isa<FieldDecl>(D)) {
  4824. FieldDecl *FD = cast<FieldDecl>(D);
  4825. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  4826. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
  4827. } else if (isa<VarDecl>(D)) {
  4828. VarDecl *VD = cast<VarDecl>(D);
  4829. if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
  4830. Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
  4831. // Nested classes and class templates.
  4832. } else if (isa<CXXRecordDecl>(D)) {
  4833. CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
  4834. } else if (isa<ClassTemplateDecl>(D)) {
  4835. CheckAbstractClassUsage(Info,
  4836. cast<ClassTemplateDecl>(D)->getTemplatedDecl());
  4837. }
  4838. }
  4839. }
  4840. static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
  4841. Attr *ClassAttr = getDLLAttr(Class);
  4842. if (!ClassAttr)
  4843. return;
  4844. assert(ClassAttr->getKind() == attr::DLLExport);
  4845. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  4846. if (TSK == TSK_ExplicitInstantiationDeclaration)
  4847. // Don't go any further if this is just an explicit instantiation
  4848. // declaration.
  4849. return;
  4850. if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
  4851. S.MarkVTableUsed(Class->getLocation(), Class, true);
  4852. for (Decl *Member : Class->decls()) {
  4853. // Defined static variables that are members of an exported base
  4854. // class must be marked export too.
  4855. auto *VD = dyn_cast<VarDecl>(Member);
  4856. if (VD && Member->getAttr<DLLExportAttr>() &&
  4857. VD->getStorageClass() == SC_Static &&
  4858. TSK == TSK_ImplicitInstantiation)
  4859. S.MarkVariableReferenced(VD->getLocation(), VD);
  4860. auto *MD = dyn_cast<CXXMethodDecl>(Member);
  4861. if (!MD)
  4862. continue;
  4863. if (Member->getAttr<DLLExportAttr>()) {
  4864. if (MD->isUserProvided()) {
  4865. // Instantiate non-default class member functions ...
  4866. // .. except for certain kinds of template specializations.
  4867. if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
  4868. continue;
  4869. S.MarkFunctionReferenced(Class->getLocation(), MD);
  4870. // The function will be passed to the consumer when its definition is
  4871. // encountered.
  4872. } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
  4873. MD->isCopyAssignmentOperator() ||
  4874. MD->isMoveAssignmentOperator()) {
  4875. // Synthesize and instantiate non-trivial implicit methods, explicitly
  4876. // defaulted methods, and the copy and move assignment operators. The
  4877. // latter are exported even if they are trivial, because the address of
  4878. // an operator can be taken and should compare equal across libraries.
  4879. DiagnosticErrorTrap Trap(S.Diags);
  4880. S.MarkFunctionReferenced(Class->getLocation(), MD);
  4881. if (Trap.hasErrorOccurred()) {
  4882. S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
  4883. << Class << !S.getLangOpts().CPlusPlus11;
  4884. break;
  4885. }
  4886. // There is no later point when we will see the definition of this
  4887. // function, so pass it to the consumer now.
  4888. S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
  4889. }
  4890. }
  4891. }
  4892. }
  4893. static void checkForMultipleExportedDefaultConstructors(Sema &S,
  4894. CXXRecordDecl *Class) {
  4895. // Only the MS ABI has default constructor closures, so we don't need to do
  4896. // this semantic checking anywhere else.
  4897. if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
  4898. return;
  4899. CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
  4900. for (Decl *Member : Class->decls()) {
  4901. // Look for exported default constructors.
  4902. auto *CD = dyn_cast<CXXConstructorDecl>(Member);
  4903. if (!CD || !CD->isDefaultConstructor())
  4904. continue;
  4905. auto *Attr = CD->getAttr<DLLExportAttr>();
  4906. if (!Attr)
  4907. continue;
  4908. // If the class is non-dependent, mark the default arguments as ODR-used so
  4909. // that we can properly codegen the constructor closure.
  4910. if (!Class->isDependentContext()) {
  4911. for (ParmVarDecl *PD : CD->parameters()) {
  4912. (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
  4913. S.DiscardCleanupsInEvaluationContext();
  4914. }
  4915. }
  4916. if (LastExportedDefaultCtor) {
  4917. S.Diag(LastExportedDefaultCtor->getLocation(),
  4918. diag::err_attribute_dll_ambiguous_default_ctor)
  4919. << Class;
  4920. S.Diag(CD->getLocation(), diag::note_entity_declared_at)
  4921. << CD->getDeclName();
  4922. return;
  4923. }
  4924. LastExportedDefaultCtor = CD;
  4925. }
  4926. }
  4927. void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
  4928. // Mark any compiler-generated routines with the implicit code_seg attribute.
  4929. for (auto *Method : Class->methods()) {
  4930. if (Method->isUserProvided())
  4931. continue;
  4932. if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
  4933. Method->addAttr(A);
  4934. }
  4935. }
  4936. /// Check class-level dllimport/dllexport attribute.
  4937. void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
  4938. Attr *ClassAttr = getDLLAttr(Class);
  4939. // MSVC inherits DLL attributes to partial class template specializations.
  4940. if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
  4941. if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
  4942. if (Attr *TemplateAttr =
  4943. getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
  4944. auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
  4945. A->setInherited(true);
  4946. ClassAttr = A;
  4947. }
  4948. }
  4949. }
  4950. if (!ClassAttr)
  4951. return;
  4952. if (!Class->isExternallyVisible()) {
  4953. Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
  4954. << Class << ClassAttr;
  4955. return;
  4956. }
  4957. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  4958. !ClassAttr->isInherited()) {
  4959. // Diagnose dll attributes on members of class with dll attribute.
  4960. for (Decl *Member : Class->decls()) {
  4961. if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
  4962. continue;
  4963. InheritableAttr *MemberAttr = getDLLAttr(Member);
  4964. if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
  4965. continue;
  4966. Diag(MemberAttr->getLocation(),
  4967. diag::err_attribute_dll_member_of_dll_class)
  4968. << MemberAttr << ClassAttr;
  4969. Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
  4970. Member->setInvalidDecl();
  4971. }
  4972. }
  4973. if (Class->getDescribedClassTemplate())
  4974. // Don't inherit dll attribute until the template is instantiated.
  4975. return;
  4976. // The class is either imported or exported.
  4977. const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
  4978. // Check if this was a dllimport attribute propagated from a derived class to
  4979. // a base class template specialization. We don't apply these attributes to
  4980. // static data members.
  4981. const bool PropagatedImport =
  4982. !ClassExported &&
  4983. cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
  4984. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  4985. // Ignore explicit dllexport on explicit class template instantiation
  4986. // declarations, except in MinGW mode.
  4987. if (ClassExported && !ClassAttr->isInherited() &&
  4988. TSK == TSK_ExplicitInstantiationDeclaration &&
  4989. !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
  4990. Class->dropAttr<DLLExportAttr>();
  4991. return;
  4992. }
  4993. // Force declaration of implicit members so they can inherit the attribute.
  4994. ForceDeclarationOfImplicitMembers(Class);
  4995. // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
  4996. // seem to be true in practice?
  4997. for (Decl *Member : Class->decls()) {
  4998. VarDecl *VD = dyn_cast<VarDecl>(Member);
  4999. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
  5000. // Only methods and static fields inherit the attributes.
  5001. if (!VD && !MD)
  5002. continue;
  5003. if (MD) {
  5004. // Don't process deleted methods.
  5005. if (MD->isDeleted())
  5006. continue;
  5007. if (MD->isInlined()) {
  5008. // MinGW does not import or export inline methods. But do it for
  5009. // template instantiations.
  5010. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  5011. !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
  5012. TSK != TSK_ExplicitInstantiationDeclaration &&
  5013. TSK != TSK_ExplicitInstantiationDefinition)
  5014. continue;
  5015. // MSVC versions before 2015 don't export the move assignment operators
  5016. // and move constructor, so don't attempt to import/export them if
  5017. // we have a definition.
  5018. auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
  5019. if ((MD->isMoveAssignmentOperator() ||
  5020. (Ctor && Ctor->isMoveConstructor())) &&
  5021. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
  5022. continue;
  5023. // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
  5024. // operator is exported anyway.
  5025. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  5026. (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
  5027. continue;
  5028. }
  5029. }
  5030. // Don't apply dllimport attributes to static data members of class template
  5031. // instantiations when the attribute is propagated from a derived class.
  5032. if (VD && PropagatedImport)
  5033. continue;
  5034. if (!cast<NamedDecl>(Member)->isExternallyVisible())
  5035. continue;
  5036. if (!getDLLAttr(Member)) {
  5037. InheritableAttr *NewAttr = nullptr;
  5038. // Do not export/import inline function when -fno-dllexport-inlines is
  5039. // passed. But add attribute for later local static var check.
  5040. if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
  5041. TSK != TSK_ExplicitInstantiationDeclaration &&
  5042. TSK != TSK_ExplicitInstantiationDefinition) {
  5043. if (ClassExported) {
  5044. NewAttr = ::new (getASTContext())
  5045. DLLExportStaticLocalAttr(ClassAttr->getRange(),
  5046. getASTContext(),
  5047. ClassAttr->getSpellingListIndex());
  5048. } else {
  5049. NewAttr = ::new (getASTContext())
  5050. DLLImportStaticLocalAttr(ClassAttr->getRange(),
  5051. getASTContext(),
  5052. ClassAttr->getSpellingListIndex());
  5053. }
  5054. } else {
  5055. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5056. }
  5057. NewAttr->setInherited(true);
  5058. Member->addAttr(NewAttr);
  5059. if (MD) {
  5060. // Propagate DLLAttr to friend re-declarations of MD that have already
  5061. // been constructed.
  5062. for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
  5063. FD = FD->getPreviousDecl()) {
  5064. if (FD->getFriendObjectKind() == Decl::FOK_None)
  5065. continue;
  5066. assert(!getDLLAttr(FD) &&
  5067. "friend re-decl should not already have a DLLAttr");
  5068. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5069. NewAttr->setInherited(true);
  5070. FD->addAttr(NewAttr);
  5071. }
  5072. }
  5073. }
  5074. }
  5075. if (ClassExported)
  5076. DelayedDllExportClasses.push_back(Class);
  5077. }
  5078. /// Perform propagation of DLL attributes from a derived class to a
  5079. /// templated base class for MS compatibility.
  5080. void Sema::propagateDLLAttrToBaseClassTemplate(
  5081. CXXRecordDecl *Class, Attr *ClassAttr,
  5082. ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
  5083. if (getDLLAttr(
  5084. BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
  5085. // If the base class template has a DLL attribute, don't try to change it.
  5086. return;
  5087. }
  5088. auto TSK = BaseTemplateSpec->getSpecializationKind();
  5089. if (!getDLLAttr(BaseTemplateSpec) &&
  5090. (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
  5091. TSK == TSK_ImplicitInstantiation)) {
  5092. // The template hasn't been instantiated yet (or it has, but only as an
  5093. // explicit instantiation declaration or implicit instantiation, which means
  5094. // we haven't codegenned any members yet), so propagate the attribute.
  5095. auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5096. NewAttr->setInherited(true);
  5097. BaseTemplateSpec->addAttr(NewAttr);
  5098. // If this was an import, mark that we propagated it from a derived class to
  5099. // a base class template specialization.
  5100. if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
  5101. ImportAttr->setPropagatedToBaseTemplate();
  5102. // If the template is already instantiated, checkDLLAttributeRedeclaration()
  5103. // needs to be run again to work see the new attribute. Otherwise this will
  5104. // get run whenever the template is instantiated.
  5105. if (TSK != TSK_Undeclared)
  5106. checkClassLevelDLLAttribute(BaseTemplateSpec);
  5107. return;
  5108. }
  5109. if (getDLLAttr(BaseTemplateSpec)) {
  5110. // The template has already been specialized or instantiated with an
  5111. // attribute, explicitly or through propagation. We should not try to change
  5112. // it.
  5113. return;
  5114. }
  5115. // The template was previously instantiated or explicitly specialized without
  5116. // a dll attribute, It's too late for us to add an attribute, so warn that
  5117. // this is unsupported.
  5118. Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
  5119. << BaseTemplateSpec->isExplicitSpecialization();
  5120. Diag(ClassAttr->getLocation(), diag::note_attribute);
  5121. if (BaseTemplateSpec->isExplicitSpecialization()) {
  5122. Diag(BaseTemplateSpec->getLocation(),
  5123. diag::note_template_class_explicit_specialization_was_here)
  5124. << BaseTemplateSpec;
  5125. } else {
  5126. Diag(BaseTemplateSpec->getPointOfInstantiation(),
  5127. diag::note_template_class_instantiation_was_here)
  5128. << BaseTemplateSpec;
  5129. }
  5130. }
  5131. static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
  5132. SourceLocation DefaultLoc) {
  5133. switch (S.getSpecialMember(MD)) {
  5134. case Sema::CXXDefaultConstructor:
  5135. S.DefineImplicitDefaultConstructor(DefaultLoc,
  5136. cast<CXXConstructorDecl>(MD));
  5137. break;
  5138. case Sema::CXXCopyConstructor:
  5139. S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  5140. break;
  5141. case Sema::CXXCopyAssignment:
  5142. S.DefineImplicitCopyAssignment(DefaultLoc, MD);
  5143. break;
  5144. case Sema::CXXDestructor:
  5145. S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
  5146. break;
  5147. case Sema::CXXMoveConstructor:
  5148. S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  5149. break;
  5150. case Sema::CXXMoveAssignment:
  5151. S.DefineImplicitMoveAssignment(DefaultLoc, MD);
  5152. break;
  5153. case Sema::CXXInvalid:
  5154. llvm_unreachable("Invalid special member.");
  5155. }
  5156. }
  5157. /// Determine whether a type is permitted to be passed or returned in
  5158. /// registers, per C++ [class.temporary]p3.
  5159. static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
  5160. TargetInfo::CallingConvKind CCK) {
  5161. if (D->isDependentType() || D->isInvalidDecl())
  5162. return false;
  5163. // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
  5164. // The PS4 platform ABI follows the behavior of Clang 3.2.
  5165. if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
  5166. return !D->hasNonTrivialDestructorForCall() &&
  5167. !D->hasNonTrivialCopyConstructorForCall();
  5168. if (CCK == TargetInfo::CCK_MicrosoftWin64) {
  5169. bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
  5170. bool DtorIsTrivialForCall = false;
  5171. // If a class has at least one non-deleted, trivial copy constructor, it
  5172. // is passed according to the C ABI. Otherwise, it is passed indirectly.
  5173. //
  5174. // Note: This permits classes with non-trivial copy or move ctors to be
  5175. // passed in registers, so long as they *also* have a trivial copy ctor,
  5176. // which is non-conforming.
  5177. if (D->needsImplicitCopyConstructor()) {
  5178. if (!D->defaultedCopyConstructorIsDeleted()) {
  5179. if (D->hasTrivialCopyConstructor())
  5180. CopyCtorIsTrivial = true;
  5181. if (D->hasTrivialCopyConstructorForCall())
  5182. CopyCtorIsTrivialForCall = true;
  5183. }
  5184. } else {
  5185. for (const CXXConstructorDecl *CD : D->ctors()) {
  5186. if (CD->isCopyConstructor() && !CD->isDeleted()) {
  5187. if (CD->isTrivial())
  5188. CopyCtorIsTrivial = true;
  5189. if (CD->isTrivialForCall())
  5190. CopyCtorIsTrivialForCall = true;
  5191. }
  5192. }
  5193. }
  5194. if (D->needsImplicitDestructor()) {
  5195. if (!D->defaultedDestructorIsDeleted() &&
  5196. D->hasTrivialDestructorForCall())
  5197. DtorIsTrivialForCall = true;
  5198. } else if (const auto *DD = D->getDestructor()) {
  5199. if (!DD->isDeleted() && DD->isTrivialForCall())
  5200. DtorIsTrivialForCall = true;
  5201. }
  5202. // If the copy ctor and dtor are both trivial-for-calls, pass direct.
  5203. if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
  5204. return true;
  5205. // If a class has a destructor, we'd really like to pass it indirectly
  5206. // because it allows us to elide copies. Unfortunately, MSVC makes that
  5207. // impossible for small types, which it will pass in a single register or
  5208. // stack slot. Most objects with dtors are large-ish, so handle that early.
  5209. // We can't call out all large objects as being indirect because there are
  5210. // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
  5211. // how we pass large POD types.
  5212. // Note: This permits small classes with nontrivial destructors to be
  5213. // passed in registers, which is non-conforming.
  5214. bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
  5215. uint64_t TypeSize = isAArch64 ? 128 : 64;
  5216. if (CopyCtorIsTrivial &&
  5217. S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
  5218. return true;
  5219. return false;
  5220. }
  5221. // Per C++ [class.temporary]p3, the relevant condition is:
  5222. // each copy constructor, move constructor, and destructor of X is
  5223. // either trivial or deleted, and X has at least one non-deleted copy
  5224. // or move constructor
  5225. bool HasNonDeletedCopyOrMove = false;
  5226. if (D->needsImplicitCopyConstructor() &&
  5227. !D->defaultedCopyConstructorIsDeleted()) {
  5228. if (!D->hasTrivialCopyConstructorForCall())
  5229. return false;
  5230. HasNonDeletedCopyOrMove = true;
  5231. }
  5232. if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
  5233. !D->defaultedMoveConstructorIsDeleted()) {
  5234. if (!D->hasTrivialMoveConstructorForCall())
  5235. return false;
  5236. HasNonDeletedCopyOrMove = true;
  5237. }
  5238. if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
  5239. !D->hasTrivialDestructorForCall())
  5240. return false;
  5241. for (const CXXMethodDecl *MD : D->methods()) {
  5242. if (MD->isDeleted())
  5243. continue;
  5244. auto *CD = dyn_cast<CXXConstructorDecl>(MD);
  5245. if (CD && CD->isCopyOrMoveConstructor())
  5246. HasNonDeletedCopyOrMove = true;
  5247. else if (!isa<CXXDestructorDecl>(MD))
  5248. continue;
  5249. if (!MD->isTrivialForCall())
  5250. return false;
  5251. }
  5252. return HasNonDeletedCopyOrMove;
  5253. }
  5254. /// Perform semantic checks on a class definition that has been
  5255. /// completing, introducing implicitly-declared members, checking for
  5256. /// abstract types, etc.
  5257. void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
  5258. if (!Record)
  5259. return;
  5260. if (Record->isAbstract() && !Record->isInvalidDecl()) {
  5261. AbstractUsageInfo Info(*this, Record);
  5262. CheckAbstractClassUsage(Info, Record);
  5263. }
  5264. // If this is not an aggregate type and has no user-declared constructor,
  5265. // complain about any non-static data members of reference or const scalar
  5266. // type, since they will never get initializers.
  5267. if (!Record->isInvalidDecl() && !Record->isDependentType() &&
  5268. !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
  5269. !Record->isLambda()) {
  5270. bool Complained = false;
  5271. for (const auto *F : Record->fields()) {
  5272. if (F->hasInClassInitializer() || F->isUnnamedBitfield())
  5273. continue;
  5274. if (F->getType()->isReferenceType() ||
  5275. (F->getType().isConstQualified() && F->getType()->isScalarType())) {
  5276. if (!Complained) {
  5277. Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
  5278. << Record->getTagKind() << Record;
  5279. Complained = true;
  5280. }
  5281. Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
  5282. << F->getType()->isReferenceType()
  5283. << F->getDeclName();
  5284. }
  5285. }
  5286. }
  5287. if (Record->getIdentifier()) {
  5288. // C++ [class.mem]p13:
  5289. // If T is the name of a class, then each of the following shall have a
  5290. // name different from T:
  5291. // - every member of every anonymous union that is a member of class T.
  5292. //
  5293. // C++ [class.mem]p14:
  5294. // In addition, if class T has a user-declared constructor (12.1), every
  5295. // non-static data member of class T shall have a name different from T.
  5296. DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
  5297. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
  5298. ++I) {
  5299. NamedDecl *D = (*I)->getUnderlyingDecl();
  5300. if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
  5301. Record->hasUserDeclaredConstructor()) ||
  5302. isa<IndirectFieldDecl>(D)) {
  5303. Diag((*I)->getLocation(), diag::err_member_name_of_class)
  5304. << D->getDeclName();
  5305. break;
  5306. }
  5307. }
  5308. }
  5309. // Warn if the class has virtual methods but non-virtual public destructor.
  5310. if (Record->isPolymorphic() && !Record->isDependentType()) {
  5311. CXXDestructorDecl *dtor = Record->getDestructor();
  5312. if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
  5313. !Record->hasAttr<FinalAttr>())
  5314. Diag(dtor ? dtor->getLocation() : Record->getLocation(),
  5315. diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
  5316. }
  5317. if (Record->isAbstract()) {
  5318. if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
  5319. Diag(Record->getLocation(), diag::warn_abstract_final_class)
  5320. << FA->isSpelledAsSealed();
  5321. DiagnoseAbstractType(Record);
  5322. }
  5323. }
  5324. // See if trivial_abi has to be dropped.
  5325. if (Record->hasAttr<TrivialABIAttr>())
  5326. checkIllFormedTrivialABIStruct(*Record);
  5327. // Set HasTrivialSpecialMemberForCall if the record has attribute
  5328. // "trivial_abi".
  5329. bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
  5330. if (HasTrivialABI)
  5331. Record->setHasTrivialSpecialMemberForCall();
  5332. auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
  5333. // Check whether the explicitly-defaulted special members are valid.
  5334. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
  5335. CheckExplicitlyDefaultedSpecialMember(M);
  5336. // For an explicitly defaulted or deleted special member, we defer
  5337. // determining triviality until the class is complete. That time is now!
  5338. CXXSpecialMember CSM = getSpecialMember(M);
  5339. if (!M->isImplicit() && !M->isUserProvided()) {
  5340. if (CSM != CXXInvalid) {
  5341. M->setTrivial(SpecialMemberIsTrivial(M, CSM));
  5342. // Inform the class that we've finished declaring this member.
  5343. Record->finishedDefaultedOrDeletedMember(M);
  5344. M->setTrivialForCall(
  5345. HasTrivialABI ||
  5346. SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
  5347. Record->setTrivialForCallFlags(M);
  5348. }
  5349. }
  5350. // Set triviality for the purpose of calls if this is a user-provided
  5351. // copy/move constructor or destructor.
  5352. if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
  5353. CSM == CXXDestructor) && M->isUserProvided()) {
  5354. M->setTrivialForCall(HasTrivialABI);
  5355. Record->setTrivialForCallFlags(M);
  5356. }
  5357. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
  5358. M->hasAttr<DLLExportAttr>()) {
  5359. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  5360. M->isTrivial() &&
  5361. (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
  5362. CSM == CXXDestructor))
  5363. M->dropAttr<DLLExportAttr>();
  5364. if (M->hasAttr<DLLExportAttr>()) {
  5365. DefineImplicitSpecialMember(*this, M, M->getLocation());
  5366. ActOnFinishInlineFunctionDef(M);
  5367. }
  5368. }
  5369. };
  5370. bool HasMethodWithOverrideControl = false,
  5371. HasOverridingMethodWithoutOverrideControl = false;
  5372. if (!Record->isDependentType()) {
  5373. // Check the destructor before any other member function. We need to
  5374. // determine whether it's trivial in order to determine whether the claas
  5375. // type is a literal type, which is a prerequisite for determining whether
  5376. // other special member functions are valid and whether they're implicitly
  5377. // 'constexpr'.
  5378. if (CXXDestructorDecl *Dtor = Record->getDestructor())
  5379. CompleteMemberFunction(Dtor);
  5380. for (auto *M : Record->methods()) {
  5381. // See if a method overloads virtual methods in a base
  5382. // class without overriding any.
  5383. if (!M->isStatic())
  5384. DiagnoseHiddenVirtualMethods(M);
  5385. if (M->hasAttr<OverrideAttr>())
  5386. HasMethodWithOverrideControl = true;
  5387. else if (M->size_overridden_methods() > 0)
  5388. HasOverridingMethodWithoutOverrideControl = true;
  5389. if (!isa<CXXDestructorDecl>(M))
  5390. CompleteMemberFunction(M);
  5391. }
  5392. }
  5393. if (HasMethodWithOverrideControl &&
  5394. HasOverridingMethodWithoutOverrideControl) {
  5395. // At least one method has the 'override' control declared.
  5396. // Diagnose all other overridden methods which do not have 'override' specified on them.
  5397. for (auto *M : Record->methods())
  5398. DiagnoseAbsenceOfOverrideControl(M);
  5399. }
  5400. // ms_struct is a request to use the same ABI rules as MSVC. Check
  5401. // whether this class uses any C++ features that are implemented
  5402. // completely differently in MSVC, and if so, emit a diagnostic.
  5403. // That diagnostic defaults to an error, but we allow projects to
  5404. // map it down to a warning (or ignore it). It's a fairly common
  5405. // practice among users of the ms_struct pragma to mass-annotate
  5406. // headers, sweeping up a bunch of types that the project doesn't
  5407. // really rely on MSVC-compatible layout for. We must therefore
  5408. // support "ms_struct except for C++ stuff" as a secondary ABI.
  5409. if (Record->isMsStruct(Context) &&
  5410. (Record->isPolymorphic() || Record->getNumBases())) {
  5411. Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
  5412. }
  5413. checkClassLevelDLLAttribute(Record);
  5414. checkClassLevelCodeSegAttribute(Record);
  5415. bool ClangABICompat4 =
  5416. Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
  5417. TargetInfo::CallingConvKind CCK =
  5418. Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
  5419. bool CanPass = canPassInRegisters(*this, Record, CCK);
  5420. // Do not change ArgPassingRestrictions if it has already been set to
  5421. // APK_CanNeverPassInRegs.
  5422. if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
  5423. Record->setArgPassingRestrictions(CanPass
  5424. ? RecordDecl::APK_CanPassInRegs
  5425. : RecordDecl::APK_CannotPassInRegs);
  5426. // If canPassInRegisters returns true despite the record having a non-trivial
  5427. // destructor, the record is destructed in the callee. This happens only when
  5428. // the record or one of its subobjects has a field annotated with trivial_abi
  5429. // or a field qualified with ObjC __strong/__weak.
  5430. if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
  5431. Record->setParamDestroyedInCallee(true);
  5432. else if (Record->hasNonTrivialDestructor())
  5433. Record->setParamDestroyedInCallee(CanPass);
  5434. if (getLangOpts().ForceEmitVTables) {
  5435. // If we want to emit all the vtables, we need to mark it as used. This
  5436. // is especially required for cases like vtable assumption loads.
  5437. MarkVTableUsed(Record->getInnerLocStart(), Record);
  5438. }
  5439. }
  5440. /// Look up the special member function that would be called by a special
  5441. /// member function for a subobject of class type.
  5442. ///
  5443. /// \param Class The class type of the subobject.
  5444. /// \param CSM The kind of special member function.
  5445. /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
  5446. /// \param ConstRHS True if this is a copy operation with a const object
  5447. /// on its RHS, that is, if the argument to the outer special member
  5448. /// function is 'const' and this is not a field marked 'mutable'.
  5449. static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
  5450. Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
  5451. unsigned FieldQuals, bool ConstRHS) {
  5452. unsigned LHSQuals = 0;
  5453. if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
  5454. LHSQuals = FieldQuals;
  5455. unsigned RHSQuals = FieldQuals;
  5456. if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
  5457. RHSQuals = 0;
  5458. else if (ConstRHS)
  5459. RHSQuals |= Qualifiers::Const;
  5460. return S.LookupSpecialMember(Class, CSM,
  5461. RHSQuals & Qualifiers::Const,
  5462. RHSQuals & Qualifiers::Volatile,
  5463. false,
  5464. LHSQuals & Qualifiers::Const,
  5465. LHSQuals & Qualifiers::Volatile);
  5466. }
  5467. class Sema::InheritedConstructorInfo {
  5468. Sema &S;
  5469. SourceLocation UseLoc;
  5470. /// A mapping from the base classes through which the constructor was
  5471. /// inherited to the using shadow declaration in that base class (or a null
  5472. /// pointer if the constructor was declared in that base class).
  5473. llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
  5474. InheritedFromBases;
  5475. public:
  5476. InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
  5477. ConstructorUsingShadowDecl *Shadow)
  5478. : S(S), UseLoc(UseLoc) {
  5479. bool DiagnosedMultipleConstructedBases = false;
  5480. CXXRecordDecl *ConstructedBase = nullptr;
  5481. UsingDecl *ConstructedBaseUsing = nullptr;
  5482. // Find the set of such base class subobjects and check that there's a
  5483. // unique constructed subobject.
  5484. for (auto *D : Shadow->redecls()) {
  5485. auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
  5486. auto *DNominatedBase = DShadow->getNominatedBaseClass();
  5487. auto *DConstructedBase = DShadow->getConstructedBaseClass();
  5488. InheritedFromBases.insert(
  5489. std::make_pair(DNominatedBase->getCanonicalDecl(),
  5490. DShadow->getNominatedBaseClassShadowDecl()));
  5491. if (DShadow->constructsVirtualBase())
  5492. InheritedFromBases.insert(
  5493. std::make_pair(DConstructedBase->getCanonicalDecl(),
  5494. DShadow->getConstructedBaseClassShadowDecl()));
  5495. else
  5496. assert(DNominatedBase == DConstructedBase);
  5497. // [class.inhctor.init]p2:
  5498. // If the constructor was inherited from multiple base class subobjects
  5499. // of type B, the program is ill-formed.
  5500. if (!ConstructedBase) {
  5501. ConstructedBase = DConstructedBase;
  5502. ConstructedBaseUsing = D->getUsingDecl();
  5503. } else if (ConstructedBase != DConstructedBase &&
  5504. !Shadow->isInvalidDecl()) {
  5505. if (!DiagnosedMultipleConstructedBases) {
  5506. S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
  5507. << Shadow->getTargetDecl();
  5508. S.Diag(ConstructedBaseUsing->getLocation(),
  5509. diag::note_ambiguous_inherited_constructor_using)
  5510. << ConstructedBase;
  5511. DiagnosedMultipleConstructedBases = true;
  5512. }
  5513. S.Diag(D->getUsingDecl()->getLocation(),
  5514. diag::note_ambiguous_inherited_constructor_using)
  5515. << DConstructedBase;
  5516. }
  5517. }
  5518. if (DiagnosedMultipleConstructedBases)
  5519. Shadow->setInvalidDecl();
  5520. }
  5521. /// Find the constructor to use for inherited construction of a base class,
  5522. /// and whether that base class constructor inherits the constructor from a
  5523. /// virtual base class (in which case it won't actually invoke it).
  5524. std::pair<CXXConstructorDecl *, bool>
  5525. findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
  5526. auto It = InheritedFromBases.find(Base->getCanonicalDecl());
  5527. if (It == InheritedFromBases.end())
  5528. return std::make_pair(nullptr, false);
  5529. // This is an intermediary class.
  5530. if (It->second)
  5531. return std::make_pair(
  5532. S.findInheritingConstructor(UseLoc, Ctor, It->second),
  5533. It->second->constructsVirtualBase());
  5534. // This is the base class from which the constructor was inherited.
  5535. return std::make_pair(Ctor, false);
  5536. }
  5537. };
  5538. /// Is the special member function which would be selected to perform the
  5539. /// specified operation on the specified class type a constexpr constructor?
  5540. static bool
  5541. specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
  5542. Sema::CXXSpecialMember CSM, unsigned Quals,
  5543. bool ConstRHS,
  5544. CXXConstructorDecl *InheritedCtor = nullptr,
  5545. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5546. // If we're inheriting a constructor, see if we need to call it for this base
  5547. // class.
  5548. if (InheritedCtor) {
  5549. assert(CSM == Sema::CXXDefaultConstructor);
  5550. auto BaseCtor =
  5551. Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
  5552. if (BaseCtor)
  5553. return BaseCtor->isConstexpr();
  5554. }
  5555. if (CSM == Sema::CXXDefaultConstructor)
  5556. return ClassDecl->hasConstexprDefaultConstructor();
  5557. Sema::SpecialMemberOverloadResult SMOR =
  5558. lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
  5559. if (!SMOR.getMethod())
  5560. // A constructor we wouldn't select can't be "involved in initializing"
  5561. // anything.
  5562. return true;
  5563. return SMOR.getMethod()->isConstexpr();
  5564. }
  5565. /// Determine whether the specified special member function would be constexpr
  5566. /// if it were implicitly defined.
  5567. static bool defaultedSpecialMemberIsConstexpr(
  5568. Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
  5569. bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
  5570. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5571. if (!S.getLangOpts().CPlusPlus11)
  5572. return false;
  5573. // C++11 [dcl.constexpr]p4:
  5574. // In the definition of a constexpr constructor [...]
  5575. bool Ctor = true;
  5576. switch (CSM) {
  5577. case Sema::CXXDefaultConstructor:
  5578. if (Inherited)
  5579. break;
  5580. // Since default constructor lookup is essentially trivial (and cannot
  5581. // involve, for instance, template instantiation), we compute whether a
  5582. // defaulted default constructor is constexpr directly within CXXRecordDecl.
  5583. //
  5584. // This is important for performance; we need to know whether the default
  5585. // constructor is constexpr to determine whether the type is a literal type.
  5586. return ClassDecl->defaultedDefaultConstructorIsConstexpr();
  5587. case Sema::CXXCopyConstructor:
  5588. case Sema::CXXMoveConstructor:
  5589. // For copy or move constructors, we need to perform overload resolution.
  5590. break;
  5591. case Sema::CXXCopyAssignment:
  5592. case Sema::CXXMoveAssignment:
  5593. if (!S.getLangOpts().CPlusPlus14)
  5594. return false;
  5595. // In C++1y, we need to perform overload resolution.
  5596. Ctor = false;
  5597. break;
  5598. case Sema::CXXDestructor:
  5599. case Sema::CXXInvalid:
  5600. return false;
  5601. }
  5602. // -- if the class is a non-empty union, or for each non-empty anonymous
  5603. // union member of a non-union class, exactly one non-static data member
  5604. // shall be initialized; [DR1359]
  5605. //
  5606. // If we squint, this is guaranteed, since exactly one non-static data member
  5607. // will be initialized (if the constructor isn't deleted), we just don't know
  5608. // which one.
  5609. if (Ctor && ClassDecl->isUnion())
  5610. return CSM == Sema::CXXDefaultConstructor
  5611. ? ClassDecl->hasInClassInitializer() ||
  5612. !ClassDecl->hasVariantMembers()
  5613. : true;
  5614. // -- the class shall not have any virtual base classes;
  5615. if (Ctor && ClassDecl->getNumVBases())
  5616. return false;
  5617. // C++1y [class.copy]p26:
  5618. // -- [the class] is a literal type, and
  5619. if (!Ctor && !ClassDecl->isLiteral())
  5620. return false;
  5621. // -- every constructor involved in initializing [...] base class
  5622. // sub-objects shall be a constexpr constructor;
  5623. // -- the assignment operator selected to copy/move each direct base
  5624. // class is a constexpr function, and
  5625. for (const auto &B : ClassDecl->bases()) {
  5626. const RecordType *BaseType = B.getType()->getAs<RecordType>();
  5627. if (!BaseType) continue;
  5628. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  5629. if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
  5630. InheritedCtor, Inherited))
  5631. return false;
  5632. }
  5633. // -- every constructor involved in initializing non-static data members
  5634. // [...] shall be a constexpr constructor;
  5635. // -- every non-static data member and base class sub-object shall be
  5636. // initialized
  5637. // -- for each non-static data member of X that is of class type (or array
  5638. // thereof), the assignment operator selected to copy/move that member is
  5639. // a constexpr function
  5640. for (const auto *F : ClassDecl->fields()) {
  5641. if (F->isInvalidDecl())
  5642. continue;
  5643. if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
  5644. continue;
  5645. QualType BaseType = S.Context.getBaseElementType(F->getType());
  5646. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  5647. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  5648. if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
  5649. BaseType.getCVRQualifiers(),
  5650. ConstArg && !F->isMutable()))
  5651. return false;
  5652. } else if (CSM == Sema::CXXDefaultConstructor) {
  5653. return false;
  5654. }
  5655. }
  5656. // All OK, it's constexpr!
  5657. return true;
  5658. }
  5659. static Sema::ImplicitExceptionSpecification
  5660. ComputeDefaultedSpecialMemberExceptionSpec(
  5661. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  5662. Sema::InheritedConstructorInfo *ICI);
  5663. static Sema::ImplicitExceptionSpecification
  5664. computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
  5665. auto CSM = S.getSpecialMember(MD);
  5666. if (CSM != Sema::CXXInvalid)
  5667. return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
  5668. auto *CD = cast<CXXConstructorDecl>(MD);
  5669. assert(CD->getInheritedConstructor() &&
  5670. "only special members have implicit exception specs");
  5671. Sema::InheritedConstructorInfo ICI(
  5672. S, Loc, CD->getInheritedConstructor().getShadowDecl());
  5673. return ComputeDefaultedSpecialMemberExceptionSpec(
  5674. S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
  5675. }
  5676. static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
  5677. CXXMethodDecl *MD) {
  5678. FunctionProtoType::ExtProtoInfo EPI;
  5679. // Build an exception specification pointing back at this member.
  5680. EPI.ExceptionSpec.Type = EST_Unevaluated;
  5681. EPI.ExceptionSpec.SourceDecl = MD;
  5682. // Set the calling convention to the default for C++ instance methods.
  5683. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
  5684. S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  5685. /*IsCXXMethod=*/true));
  5686. return EPI;
  5687. }
  5688. void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
  5689. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  5690. if (FPT->getExceptionSpecType() != EST_Unevaluated)
  5691. return;
  5692. // Evaluate the exception specification.
  5693. auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
  5694. auto ESI = IES.getExceptionSpec();
  5695. // Update the type of the special member to use it.
  5696. UpdateExceptionSpec(MD, ESI);
  5697. // A user-provided destructor can be defined outside the class. When that
  5698. // happens, be sure to update the exception specification on both
  5699. // declarations.
  5700. const FunctionProtoType *CanonicalFPT =
  5701. MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
  5702. if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
  5703. UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
  5704. }
  5705. void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
  5706. CXXRecordDecl *RD = MD->getParent();
  5707. CXXSpecialMember CSM = getSpecialMember(MD);
  5708. assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
  5709. "not an explicitly-defaulted special member");
  5710. // Whether this was the first-declared instance of the constructor.
  5711. // This affects whether we implicitly add an exception spec and constexpr.
  5712. bool First = MD == MD->getCanonicalDecl();
  5713. bool HadError = false;
  5714. // C++11 [dcl.fct.def.default]p1:
  5715. // A function that is explicitly defaulted shall
  5716. // -- be a special member function (checked elsewhere),
  5717. // -- have the same type (except for ref-qualifiers, and except that a
  5718. // copy operation can take a non-const reference) as an implicit
  5719. // declaration, and
  5720. // -- not have default arguments.
  5721. // C++2a changes the second bullet to instead delete the function if it's
  5722. // defaulted on its first declaration, unless it's "an assignment operator,
  5723. // and its return type differs or its parameter type is not a reference".
  5724. bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
  5725. bool ShouldDeleteForTypeMismatch = false;
  5726. unsigned ExpectedParams = 1;
  5727. if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
  5728. ExpectedParams = 0;
  5729. if (MD->getNumParams() != ExpectedParams) {
  5730. // This checks for default arguments: a copy or move constructor with a
  5731. // default argument is classified as a default constructor, and assignment
  5732. // operations and destructors can't have default arguments.
  5733. Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
  5734. << CSM << MD->getSourceRange();
  5735. HadError = true;
  5736. } else if (MD->isVariadic()) {
  5737. if (DeleteOnTypeMismatch)
  5738. ShouldDeleteForTypeMismatch = true;
  5739. else {
  5740. Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
  5741. << CSM << MD->getSourceRange();
  5742. HadError = true;
  5743. }
  5744. }
  5745. const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
  5746. bool CanHaveConstParam = false;
  5747. if (CSM == CXXCopyConstructor)
  5748. CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
  5749. else if (CSM == CXXCopyAssignment)
  5750. CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
  5751. QualType ReturnType = Context.VoidTy;
  5752. if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
  5753. // Check for return type matching.
  5754. ReturnType = Type->getReturnType();
  5755. QualType DeclType = Context.getTypeDeclType(RD);
  5756. DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
  5757. QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
  5758. if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
  5759. Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
  5760. << (CSM == CXXMoveAssignment) << ExpectedReturnType;
  5761. HadError = true;
  5762. }
  5763. // A defaulted special member cannot have cv-qualifiers.
  5764. if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
  5765. if (DeleteOnTypeMismatch)
  5766. ShouldDeleteForTypeMismatch = true;
  5767. else {
  5768. Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
  5769. << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
  5770. HadError = true;
  5771. }
  5772. }
  5773. }
  5774. // Check for parameter type matching.
  5775. QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
  5776. bool HasConstParam = false;
  5777. if (ExpectedParams && ArgType->isReferenceType()) {
  5778. // Argument must be reference to possibly-const T.
  5779. QualType ReferentType = ArgType->getPointeeType();
  5780. HasConstParam = ReferentType.isConstQualified();
  5781. if (ReferentType.isVolatileQualified()) {
  5782. if (DeleteOnTypeMismatch)
  5783. ShouldDeleteForTypeMismatch = true;
  5784. else {
  5785. Diag(MD->getLocation(),
  5786. diag::err_defaulted_special_member_volatile_param) << CSM;
  5787. HadError = true;
  5788. }
  5789. }
  5790. if (HasConstParam && !CanHaveConstParam) {
  5791. if (DeleteOnTypeMismatch)
  5792. ShouldDeleteForTypeMismatch = true;
  5793. else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
  5794. Diag(MD->getLocation(),
  5795. diag::err_defaulted_special_member_copy_const_param)
  5796. << (CSM == CXXCopyAssignment);
  5797. // FIXME: Explain why this special member can't be const.
  5798. HadError = true;
  5799. } else {
  5800. Diag(MD->getLocation(),
  5801. diag::err_defaulted_special_member_move_const_param)
  5802. << (CSM == CXXMoveAssignment);
  5803. HadError = true;
  5804. }
  5805. }
  5806. } else if (ExpectedParams) {
  5807. // A copy assignment operator can take its argument by value, but a
  5808. // defaulted one cannot.
  5809. assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
  5810. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
  5811. HadError = true;
  5812. }
  5813. // C++11 [dcl.fct.def.default]p2:
  5814. // An explicitly-defaulted function may be declared constexpr only if it
  5815. // would have been implicitly declared as constexpr,
  5816. // Do not apply this rule to members of class templates, since core issue 1358
  5817. // makes such functions always instantiate to constexpr functions. For
  5818. // functions which cannot be constexpr (for non-constructors in C++11 and for
  5819. // destructors in C++1y), this is checked elsewhere.
  5820. //
  5821. // FIXME: This should not apply if the member is deleted.
  5822. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
  5823. HasConstParam);
  5824. if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
  5825. : isa<CXXConstructorDecl>(MD)) &&
  5826. MD->isConstexpr() && !Constexpr &&
  5827. MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
  5828. Diag(MD->getBeginLoc(), MD->isConsteval()
  5829. ? diag::err_incorrect_defaulted_consteval
  5830. : diag::err_incorrect_defaulted_constexpr)
  5831. << CSM;
  5832. // FIXME: Explain why the special member can't be constexpr.
  5833. HadError = true;
  5834. }
  5835. if (First) {
  5836. // C++2a [dcl.fct.def.default]p3:
  5837. // If a function is explicitly defaulted on its first declaration, it is
  5838. // implicitly considered to be constexpr if the implicit declaration
  5839. // would be.
  5840. MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified);
  5841. if (!Type->hasExceptionSpec()) {
  5842. // C++2a [except.spec]p3:
  5843. // If a declaration of a function does not have a noexcept-specifier
  5844. // [and] is defaulted on its first declaration, [...] the exception
  5845. // specification is as specified below
  5846. FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
  5847. EPI.ExceptionSpec.Type = EST_Unevaluated;
  5848. EPI.ExceptionSpec.SourceDecl = MD;
  5849. MD->setType(Context.getFunctionType(ReturnType,
  5850. llvm::makeArrayRef(&ArgType,
  5851. ExpectedParams),
  5852. EPI));
  5853. }
  5854. }
  5855. if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
  5856. if (First) {
  5857. SetDeclDeleted(MD, MD->getLocation());
  5858. if (!inTemplateInstantiation() && !HadError) {
  5859. Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
  5860. if (ShouldDeleteForTypeMismatch) {
  5861. Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
  5862. } else {
  5863. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  5864. }
  5865. }
  5866. if (ShouldDeleteForTypeMismatch && !HadError) {
  5867. Diag(MD->getLocation(),
  5868. diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
  5869. }
  5870. } else {
  5871. // C++11 [dcl.fct.def.default]p4:
  5872. // [For a] user-provided explicitly-defaulted function [...] if such a
  5873. // function is implicitly defined as deleted, the program is ill-formed.
  5874. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
  5875. assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
  5876. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  5877. HadError = true;
  5878. }
  5879. }
  5880. if (HadError)
  5881. MD->setInvalidDecl();
  5882. }
  5883. void Sema::CheckDelayedMemberExceptionSpecs() {
  5884. decltype(DelayedOverridingExceptionSpecChecks) Overriding;
  5885. decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
  5886. std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
  5887. std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
  5888. // Perform any deferred checking of exception specifications for virtual
  5889. // destructors.
  5890. for (auto &Check : Overriding)
  5891. CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
  5892. // Perform any deferred checking of exception specifications for befriended
  5893. // special members.
  5894. for (auto &Check : Equivalent)
  5895. CheckEquivalentExceptionSpec(Check.second, Check.first);
  5896. }
  5897. namespace {
  5898. /// CRTP base class for visiting operations performed by a special member
  5899. /// function (or inherited constructor).
  5900. template<typename Derived>
  5901. struct SpecialMemberVisitor {
  5902. Sema &S;
  5903. CXXMethodDecl *MD;
  5904. Sema::CXXSpecialMember CSM;
  5905. Sema::InheritedConstructorInfo *ICI;
  5906. // Properties of the special member, computed for convenience.
  5907. bool IsConstructor = false, IsAssignment = false, ConstArg = false;
  5908. SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  5909. Sema::InheritedConstructorInfo *ICI)
  5910. : S(S), MD(MD), CSM(CSM), ICI(ICI) {
  5911. switch (CSM) {
  5912. case Sema::CXXDefaultConstructor:
  5913. case Sema::CXXCopyConstructor:
  5914. case Sema::CXXMoveConstructor:
  5915. IsConstructor = true;
  5916. break;
  5917. case Sema::CXXCopyAssignment:
  5918. case Sema::CXXMoveAssignment:
  5919. IsAssignment = true;
  5920. break;
  5921. case Sema::CXXDestructor:
  5922. break;
  5923. case Sema::CXXInvalid:
  5924. llvm_unreachable("invalid special member kind");
  5925. }
  5926. if (MD->getNumParams()) {
  5927. if (const ReferenceType *RT =
  5928. MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
  5929. ConstArg = RT->getPointeeType().isConstQualified();
  5930. }
  5931. }
  5932. Derived &getDerived() { return static_cast<Derived&>(*this); }
  5933. /// Is this a "move" special member?
  5934. bool isMove() const {
  5935. return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
  5936. }
  5937. /// Look up the corresponding special member in the given class.
  5938. Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
  5939. unsigned Quals, bool IsMutable) {
  5940. return lookupCallFromSpecialMember(S, Class, CSM, Quals,
  5941. ConstArg && !IsMutable);
  5942. }
  5943. /// Look up the constructor for the specified base class to see if it's
  5944. /// overridden due to this being an inherited constructor.
  5945. Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
  5946. if (!ICI)
  5947. return {};
  5948. assert(CSM == Sema::CXXDefaultConstructor);
  5949. auto *BaseCtor =
  5950. cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
  5951. if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
  5952. return MD;
  5953. return {};
  5954. }
  5955. /// A base or member subobject.
  5956. typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
  5957. /// Get the location to use for a subobject in diagnostics.
  5958. static SourceLocation getSubobjectLoc(Subobject Subobj) {
  5959. // FIXME: For an indirect virtual base, the direct base leading to
  5960. // the indirect virtual base would be a more useful choice.
  5961. if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
  5962. return B->getBaseTypeLoc();
  5963. else
  5964. return Subobj.get<FieldDecl*>()->getLocation();
  5965. }
  5966. enum BasesToVisit {
  5967. /// Visit all non-virtual (direct) bases.
  5968. VisitNonVirtualBases,
  5969. /// Visit all direct bases, virtual or not.
  5970. VisitDirectBases,
  5971. /// Visit all non-virtual bases, and all virtual bases if the class
  5972. /// is not abstract.
  5973. VisitPotentiallyConstructedBases,
  5974. /// Visit all direct or virtual bases.
  5975. VisitAllBases
  5976. };
  5977. // Visit the bases and members of the class.
  5978. bool visit(BasesToVisit Bases) {
  5979. CXXRecordDecl *RD = MD->getParent();
  5980. if (Bases == VisitPotentiallyConstructedBases)
  5981. Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
  5982. for (auto &B : RD->bases())
  5983. if ((Bases == VisitDirectBases || !B.isVirtual()) &&
  5984. getDerived().visitBase(&B))
  5985. return true;
  5986. if (Bases == VisitAllBases)
  5987. for (auto &B : RD->vbases())
  5988. if (getDerived().visitBase(&B))
  5989. return true;
  5990. for (auto *F : RD->fields())
  5991. if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
  5992. getDerived().visitField(F))
  5993. return true;
  5994. return false;
  5995. }
  5996. };
  5997. }
  5998. namespace {
  5999. struct SpecialMemberDeletionInfo
  6000. : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
  6001. bool Diagnose;
  6002. SourceLocation Loc;
  6003. bool AllFieldsAreConst;
  6004. SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
  6005. Sema::CXXSpecialMember CSM,
  6006. Sema::InheritedConstructorInfo *ICI, bool Diagnose)
  6007. : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
  6008. Loc(MD->getLocation()), AllFieldsAreConst(true) {}
  6009. bool inUnion() const { return MD->getParent()->isUnion(); }
  6010. Sema::CXXSpecialMember getEffectiveCSM() {
  6011. return ICI ? Sema::CXXInvalid : CSM;
  6012. }
  6013. bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
  6014. bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
  6015. bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
  6016. bool shouldDeleteForBase(CXXBaseSpecifier *Base);
  6017. bool shouldDeleteForField(FieldDecl *FD);
  6018. bool shouldDeleteForAllConstMembers();
  6019. bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  6020. unsigned Quals);
  6021. bool shouldDeleteForSubobjectCall(Subobject Subobj,
  6022. Sema::SpecialMemberOverloadResult SMOR,
  6023. bool IsDtorCallInCtor);
  6024. bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
  6025. };
  6026. }
  6027. /// Is the given special member inaccessible when used on the given
  6028. /// sub-object.
  6029. bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
  6030. CXXMethodDecl *target) {
  6031. /// If we're operating on a base class, the object type is the
  6032. /// type of this special member.
  6033. QualType objectTy;
  6034. AccessSpecifier access = target->getAccess();
  6035. if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
  6036. objectTy = S.Context.getTypeDeclType(MD->getParent());
  6037. access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
  6038. // If we're operating on a field, the object type is the type of the field.
  6039. } else {
  6040. objectTy = S.Context.getTypeDeclType(target->getParent());
  6041. }
  6042. return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
  6043. }
  6044. /// Check whether we should delete a special member due to the implicit
  6045. /// definition containing a call to a special member of a subobject.
  6046. bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
  6047. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
  6048. bool IsDtorCallInCtor) {
  6049. CXXMethodDecl *Decl = SMOR.getMethod();
  6050. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  6051. int DiagKind = -1;
  6052. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
  6053. DiagKind = !Decl ? 0 : 1;
  6054. else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  6055. DiagKind = 2;
  6056. else if (!isAccessible(Subobj, Decl))
  6057. DiagKind = 3;
  6058. else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
  6059. !Decl->isTrivial()) {
  6060. // A member of a union must have a trivial corresponding special member.
  6061. // As a weird special case, a destructor call from a union's constructor
  6062. // must be accessible and non-deleted, but need not be trivial. Such a
  6063. // destructor is never actually called, but is semantically checked as
  6064. // if it were.
  6065. DiagKind = 4;
  6066. }
  6067. if (DiagKind == -1)
  6068. return false;
  6069. if (Diagnose) {
  6070. if (Field) {
  6071. S.Diag(Field->getLocation(),
  6072. diag::note_deleted_special_member_class_subobject)
  6073. << getEffectiveCSM() << MD->getParent() << /*IsField*/true
  6074. << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
  6075. } else {
  6076. CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
  6077. S.Diag(Base->getBeginLoc(),
  6078. diag::note_deleted_special_member_class_subobject)
  6079. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  6080. << Base->getType() << DiagKind << IsDtorCallInCtor
  6081. << /*IsObjCPtr*/false;
  6082. }
  6083. if (DiagKind == 1)
  6084. S.NoteDeletedFunction(Decl);
  6085. // FIXME: Explain inaccessibility if DiagKind == 3.
  6086. }
  6087. return true;
  6088. }
  6089. /// Check whether we should delete a special member function due to having a
  6090. /// direct or virtual base class or non-static data member of class type M.
  6091. bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
  6092. CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
  6093. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  6094. bool IsMutable = Field && Field->isMutable();
  6095. // C++11 [class.ctor]p5:
  6096. // -- any direct or virtual base class, or non-static data member with no
  6097. // brace-or-equal-initializer, has class type M (or array thereof) and
  6098. // either M has no default constructor or overload resolution as applied
  6099. // to M's default constructor results in an ambiguity or in a function
  6100. // that is deleted or inaccessible
  6101. // C++11 [class.copy]p11, C++11 [class.copy]p23:
  6102. // -- a direct or virtual base class B that cannot be copied/moved because
  6103. // overload resolution, as applied to B's corresponding special member,
  6104. // results in an ambiguity or a function that is deleted or inaccessible
  6105. // from the defaulted special member
  6106. // C++11 [class.dtor]p5:
  6107. // -- any direct or virtual base class [...] has a type with a destructor
  6108. // that is deleted or inaccessible
  6109. if (!(CSM == Sema::CXXDefaultConstructor &&
  6110. Field && Field->hasInClassInitializer()) &&
  6111. shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
  6112. false))
  6113. return true;
  6114. // C++11 [class.ctor]p5, C++11 [class.copy]p11:
  6115. // -- any direct or virtual base class or non-static data member has a
  6116. // type with a destructor that is deleted or inaccessible
  6117. if (IsConstructor) {
  6118. Sema::SpecialMemberOverloadResult SMOR =
  6119. S.LookupSpecialMember(Class, Sema::CXXDestructor,
  6120. false, false, false, false, false);
  6121. if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
  6122. return true;
  6123. }
  6124. return false;
  6125. }
  6126. bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
  6127. FieldDecl *FD, QualType FieldType) {
  6128. // The defaulted special functions are defined as deleted if this is a variant
  6129. // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
  6130. // type under ARC.
  6131. if (!FieldType.hasNonTrivialObjCLifetime())
  6132. return false;
  6133. // Don't make the defaulted default constructor defined as deleted if the
  6134. // member has an in-class initializer.
  6135. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
  6136. return false;
  6137. if (Diagnose) {
  6138. auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
  6139. S.Diag(FD->getLocation(),
  6140. diag::note_deleted_special_member_class_subobject)
  6141. << getEffectiveCSM() << ParentClass << /*IsField*/true
  6142. << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
  6143. }
  6144. return true;
  6145. }
  6146. /// Check whether we should delete a special member function due to the class
  6147. /// having a particular direct or virtual base class.
  6148. bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
  6149. CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
  6150. // If program is correct, BaseClass cannot be null, but if it is, the error
  6151. // must be reported elsewhere.
  6152. if (!BaseClass)
  6153. return false;
  6154. // If we have an inheriting constructor, check whether we're calling an
  6155. // inherited constructor instead of a default constructor.
  6156. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  6157. if (auto *BaseCtor = SMOR.getMethod()) {
  6158. // Note that we do not check access along this path; other than that,
  6159. // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
  6160. // FIXME: Check that the base has a usable destructor! Sink this into
  6161. // shouldDeleteForClassSubobject.
  6162. if (BaseCtor->isDeleted() && Diagnose) {
  6163. S.Diag(Base->getBeginLoc(),
  6164. diag::note_deleted_special_member_class_subobject)
  6165. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  6166. << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
  6167. << /*IsObjCPtr*/false;
  6168. S.NoteDeletedFunction(BaseCtor);
  6169. }
  6170. return BaseCtor->isDeleted();
  6171. }
  6172. return shouldDeleteForClassSubobject(BaseClass, Base, 0);
  6173. }
  6174. /// Check whether we should delete a special member function due to the class
  6175. /// having a particular non-static data member.
  6176. bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
  6177. QualType FieldType = S.Context.getBaseElementType(FD->getType());
  6178. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  6179. if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
  6180. return true;
  6181. if (CSM == Sema::CXXDefaultConstructor) {
  6182. // For a default constructor, all references must be initialized in-class
  6183. // and, if a union, it must have a non-const member.
  6184. if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
  6185. if (Diagnose)
  6186. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  6187. << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
  6188. return true;
  6189. }
  6190. // C++11 [class.ctor]p5: any non-variant non-static data member of
  6191. // const-qualified type (or array thereof) with no
  6192. // brace-or-equal-initializer does not have a user-provided default
  6193. // constructor.
  6194. if (!inUnion() && FieldType.isConstQualified() &&
  6195. !FD->hasInClassInitializer() &&
  6196. (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
  6197. if (Diagnose)
  6198. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  6199. << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
  6200. return true;
  6201. }
  6202. if (inUnion() && !FieldType.isConstQualified())
  6203. AllFieldsAreConst = false;
  6204. } else if (CSM == Sema::CXXCopyConstructor) {
  6205. // For a copy constructor, data members must not be of rvalue reference
  6206. // type.
  6207. if (FieldType->isRValueReferenceType()) {
  6208. if (Diagnose)
  6209. S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
  6210. << MD->getParent() << FD << FieldType;
  6211. return true;
  6212. }
  6213. } else if (IsAssignment) {
  6214. // For an assignment operator, data members must not be of reference type.
  6215. if (FieldType->isReferenceType()) {
  6216. if (Diagnose)
  6217. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  6218. << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
  6219. return true;
  6220. }
  6221. if (!FieldRecord && FieldType.isConstQualified()) {
  6222. // C++11 [class.copy]p23:
  6223. // -- a non-static data member of const non-class type (or array thereof)
  6224. if (Diagnose)
  6225. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  6226. << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
  6227. return true;
  6228. }
  6229. }
  6230. if (FieldRecord) {
  6231. // Some additional restrictions exist on the variant members.
  6232. if (!inUnion() && FieldRecord->isUnion() &&
  6233. FieldRecord->isAnonymousStructOrUnion()) {
  6234. bool AllVariantFieldsAreConst = true;
  6235. // FIXME: Handle anonymous unions declared within anonymous unions.
  6236. for (auto *UI : FieldRecord->fields()) {
  6237. QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
  6238. if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
  6239. return true;
  6240. if (!UnionFieldType.isConstQualified())
  6241. AllVariantFieldsAreConst = false;
  6242. CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
  6243. if (UnionFieldRecord &&
  6244. shouldDeleteForClassSubobject(UnionFieldRecord, UI,
  6245. UnionFieldType.getCVRQualifiers()))
  6246. return true;
  6247. }
  6248. // At least one member in each anonymous union must be non-const
  6249. if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
  6250. !FieldRecord->field_empty()) {
  6251. if (Diagnose)
  6252. S.Diag(FieldRecord->getLocation(),
  6253. diag::note_deleted_default_ctor_all_const)
  6254. << !!ICI << MD->getParent() << /*anonymous union*/1;
  6255. return true;
  6256. }
  6257. // Don't check the implicit member of the anonymous union type.
  6258. // This is technically non-conformant, but sanity demands it.
  6259. return false;
  6260. }
  6261. if (shouldDeleteForClassSubobject(FieldRecord, FD,
  6262. FieldType.getCVRQualifiers()))
  6263. return true;
  6264. }
  6265. return false;
  6266. }
  6267. /// C++11 [class.ctor] p5:
  6268. /// A defaulted default constructor for a class X is defined as deleted if
  6269. /// X is a union and all of its variant members are of const-qualified type.
  6270. bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
  6271. // This is a silly definition, because it gives an empty union a deleted
  6272. // default constructor. Don't do that.
  6273. if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
  6274. bool AnyFields = false;
  6275. for (auto *F : MD->getParent()->fields())
  6276. if ((AnyFields = !F->isUnnamedBitfield()))
  6277. break;
  6278. if (!AnyFields)
  6279. return false;
  6280. if (Diagnose)
  6281. S.Diag(MD->getParent()->getLocation(),
  6282. diag::note_deleted_default_ctor_all_const)
  6283. << !!ICI << MD->getParent() << /*not anonymous union*/0;
  6284. return true;
  6285. }
  6286. return false;
  6287. }
  6288. /// Determine whether a defaulted special member function should be defined as
  6289. /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
  6290. /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
  6291. bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
  6292. InheritedConstructorInfo *ICI,
  6293. bool Diagnose) {
  6294. if (MD->isInvalidDecl())
  6295. return false;
  6296. CXXRecordDecl *RD = MD->getParent();
  6297. assert(!RD->isDependentType() && "do deletion after instantiation");
  6298. if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
  6299. return false;
  6300. // C++11 [expr.lambda.prim]p19:
  6301. // The closure type associated with a lambda-expression has a
  6302. // deleted (8.4.3) default constructor and a deleted copy
  6303. // assignment operator.
  6304. // C++2a adds back these operators if the lambda has no lambda-capture.
  6305. if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
  6306. (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
  6307. if (Diagnose)
  6308. Diag(RD->getLocation(), diag::note_lambda_decl);
  6309. return true;
  6310. }
  6311. // For an anonymous struct or union, the copy and assignment special members
  6312. // will never be used, so skip the check. For an anonymous union declared at
  6313. // namespace scope, the constructor and destructor are used.
  6314. if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
  6315. RD->isAnonymousStructOrUnion())
  6316. return false;
  6317. // C++11 [class.copy]p7, p18:
  6318. // If the class definition declares a move constructor or move assignment
  6319. // operator, an implicitly declared copy constructor or copy assignment
  6320. // operator is defined as deleted.
  6321. if (MD->isImplicit() &&
  6322. (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
  6323. CXXMethodDecl *UserDeclaredMove = nullptr;
  6324. // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
  6325. // deletion of the corresponding copy operation, not both copy operations.
  6326. // MSVC 2015 has adopted the standards conforming behavior.
  6327. bool DeletesOnlyMatchingCopy =
  6328. getLangOpts().MSVCCompat &&
  6329. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
  6330. if (RD->hasUserDeclaredMoveConstructor() &&
  6331. (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
  6332. if (!Diagnose) return true;
  6333. // Find any user-declared move constructor.
  6334. for (auto *I : RD->ctors()) {
  6335. if (I->isMoveConstructor()) {
  6336. UserDeclaredMove = I;
  6337. break;
  6338. }
  6339. }
  6340. assert(UserDeclaredMove);
  6341. } else if (RD->hasUserDeclaredMoveAssignment() &&
  6342. (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
  6343. if (!Diagnose) return true;
  6344. // Find any user-declared move assignment operator.
  6345. for (auto *I : RD->methods()) {
  6346. if (I->isMoveAssignmentOperator()) {
  6347. UserDeclaredMove = I;
  6348. break;
  6349. }
  6350. }
  6351. assert(UserDeclaredMove);
  6352. }
  6353. if (UserDeclaredMove) {
  6354. Diag(UserDeclaredMove->getLocation(),
  6355. diag::note_deleted_copy_user_declared_move)
  6356. << (CSM == CXXCopyAssignment) << RD
  6357. << UserDeclaredMove->isMoveAssignmentOperator();
  6358. return true;
  6359. }
  6360. }
  6361. // Do access control from the special member function
  6362. ContextRAII MethodContext(*this, MD);
  6363. // C++11 [class.dtor]p5:
  6364. // -- for a virtual destructor, lookup of the non-array deallocation function
  6365. // results in an ambiguity or in a function that is deleted or inaccessible
  6366. if (CSM == CXXDestructor && MD->isVirtual()) {
  6367. FunctionDecl *OperatorDelete = nullptr;
  6368. DeclarationName Name =
  6369. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  6370. if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
  6371. OperatorDelete, /*Diagnose*/false)) {
  6372. if (Diagnose)
  6373. Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
  6374. return true;
  6375. }
  6376. }
  6377. SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
  6378. // Per DR1611, do not consider virtual bases of constructors of abstract
  6379. // classes, since we are not going to construct them.
  6380. // Per DR1658, do not consider virtual bases of destructors of abstract
  6381. // classes either.
  6382. // Per DR2180, for assignment operators we only assign (and thus only
  6383. // consider) direct bases.
  6384. if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
  6385. : SMI.VisitPotentiallyConstructedBases))
  6386. return true;
  6387. if (SMI.shouldDeleteForAllConstMembers())
  6388. return true;
  6389. if (getLangOpts().CUDA) {
  6390. // We should delete the special member in CUDA mode if target inference
  6391. // failed.
  6392. // For inherited constructors (non-null ICI), CSM may be passed so that MD
  6393. // is treated as certain special member, which may not reflect what special
  6394. // member MD really is. However inferCUDATargetForImplicitSpecialMember
  6395. // expects CSM to match MD, therefore recalculate CSM.
  6396. assert(ICI || CSM == getSpecialMember(MD));
  6397. auto RealCSM = CSM;
  6398. if (ICI)
  6399. RealCSM = getSpecialMember(MD);
  6400. return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
  6401. SMI.ConstArg, Diagnose);
  6402. }
  6403. return false;
  6404. }
  6405. /// Perform lookup for a special member of the specified kind, and determine
  6406. /// whether it is trivial. If the triviality can be determined without the
  6407. /// lookup, skip it. This is intended for use when determining whether a
  6408. /// special member of a containing object is trivial, and thus does not ever
  6409. /// perform overload resolution for default constructors.
  6410. ///
  6411. /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
  6412. /// member that was most likely to be intended to be trivial, if any.
  6413. ///
  6414. /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
  6415. /// determine whether the special member is trivial.
  6416. static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
  6417. Sema::CXXSpecialMember CSM, unsigned Quals,
  6418. bool ConstRHS,
  6419. Sema::TrivialABIHandling TAH,
  6420. CXXMethodDecl **Selected) {
  6421. if (Selected)
  6422. *Selected = nullptr;
  6423. switch (CSM) {
  6424. case Sema::CXXInvalid:
  6425. llvm_unreachable("not a special member");
  6426. case Sema::CXXDefaultConstructor:
  6427. // C++11 [class.ctor]p5:
  6428. // A default constructor is trivial if:
  6429. // - all the [direct subobjects] have trivial default constructors
  6430. //
  6431. // Note, no overload resolution is performed in this case.
  6432. if (RD->hasTrivialDefaultConstructor())
  6433. return true;
  6434. if (Selected) {
  6435. // If there's a default constructor which could have been trivial, dig it
  6436. // out. Otherwise, if there's any user-provided default constructor, point
  6437. // to that as an example of why there's not a trivial one.
  6438. CXXConstructorDecl *DefCtor = nullptr;
  6439. if (RD->needsImplicitDefaultConstructor())
  6440. S.DeclareImplicitDefaultConstructor(RD);
  6441. for (auto *CI : RD->ctors()) {
  6442. if (!CI->isDefaultConstructor())
  6443. continue;
  6444. DefCtor = CI;
  6445. if (!DefCtor->isUserProvided())
  6446. break;
  6447. }
  6448. *Selected = DefCtor;
  6449. }
  6450. return false;
  6451. case Sema::CXXDestructor:
  6452. // C++11 [class.dtor]p5:
  6453. // A destructor is trivial if:
  6454. // - all the direct [subobjects] have trivial destructors
  6455. if (RD->hasTrivialDestructor() ||
  6456. (TAH == Sema::TAH_ConsiderTrivialABI &&
  6457. RD->hasTrivialDestructorForCall()))
  6458. return true;
  6459. if (Selected) {
  6460. if (RD->needsImplicitDestructor())
  6461. S.DeclareImplicitDestructor(RD);
  6462. *Selected = RD->getDestructor();
  6463. }
  6464. return false;
  6465. case Sema::CXXCopyConstructor:
  6466. // C++11 [class.copy]p12:
  6467. // A copy constructor is trivial if:
  6468. // - the constructor selected to copy each direct [subobject] is trivial
  6469. if (RD->hasTrivialCopyConstructor() ||
  6470. (TAH == Sema::TAH_ConsiderTrivialABI &&
  6471. RD->hasTrivialCopyConstructorForCall())) {
  6472. if (Quals == Qualifiers::Const)
  6473. // We must either select the trivial copy constructor or reach an
  6474. // ambiguity; no need to actually perform overload resolution.
  6475. return true;
  6476. } else if (!Selected) {
  6477. return false;
  6478. }
  6479. // In C++98, we are not supposed to perform overload resolution here, but we
  6480. // treat that as a language defect, as suggested on cxx-abi-dev, to treat
  6481. // cases like B as having a non-trivial copy constructor:
  6482. // struct A { template<typename T> A(T&); };
  6483. // struct B { mutable A a; };
  6484. goto NeedOverloadResolution;
  6485. case Sema::CXXCopyAssignment:
  6486. // C++11 [class.copy]p25:
  6487. // A copy assignment operator is trivial if:
  6488. // - the assignment operator selected to copy each direct [subobject] is
  6489. // trivial
  6490. if (RD->hasTrivialCopyAssignment()) {
  6491. if (Quals == Qualifiers::Const)
  6492. return true;
  6493. } else if (!Selected) {
  6494. return false;
  6495. }
  6496. // In C++98, we are not supposed to perform overload resolution here, but we
  6497. // treat that as a language defect.
  6498. goto NeedOverloadResolution;
  6499. case Sema::CXXMoveConstructor:
  6500. case Sema::CXXMoveAssignment:
  6501. NeedOverloadResolution:
  6502. Sema::SpecialMemberOverloadResult SMOR =
  6503. lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
  6504. // The standard doesn't describe how to behave if the lookup is ambiguous.
  6505. // We treat it as not making the member non-trivial, just like the standard
  6506. // mandates for the default constructor. This should rarely matter, because
  6507. // the member will also be deleted.
  6508. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  6509. return true;
  6510. if (!SMOR.getMethod()) {
  6511. assert(SMOR.getKind() ==
  6512. Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
  6513. return false;
  6514. }
  6515. // We deliberately don't check if we found a deleted special member. We're
  6516. // not supposed to!
  6517. if (Selected)
  6518. *Selected = SMOR.getMethod();
  6519. if (TAH == Sema::TAH_ConsiderTrivialABI &&
  6520. (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
  6521. return SMOR.getMethod()->isTrivialForCall();
  6522. return SMOR.getMethod()->isTrivial();
  6523. }
  6524. llvm_unreachable("unknown special method kind");
  6525. }
  6526. static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
  6527. for (auto *CI : RD->ctors())
  6528. if (!CI->isImplicit())
  6529. return CI;
  6530. // Look for constructor templates.
  6531. typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
  6532. for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
  6533. if (CXXConstructorDecl *CD =
  6534. dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
  6535. return CD;
  6536. }
  6537. return nullptr;
  6538. }
  6539. /// The kind of subobject we are checking for triviality. The values of this
  6540. /// enumeration are used in diagnostics.
  6541. enum TrivialSubobjectKind {
  6542. /// The subobject is a base class.
  6543. TSK_BaseClass,
  6544. /// The subobject is a non-static data member.
  6545. TSK_Field,
  6546. /// The object is actually the complete object.
  6547. TSK_CompleteObject
  6548. };
  6549. /// Check whether the special member selected for a given type would be trivial.
  6550. static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
  6551. QualType SubType, bool ConstRHS,
  6552. Sema::CXXSpecialMember CSM,
  6553. TrivialSubobjectKind Kind,
  6554. Sema::TrivialABIHandling TAH, bool Diagnose) {
  6555. CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
  6556. if (!SubRD)
  6557. return true;
  6558. CXXMethodDecl *Selected;
  6559. if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
  6560. ConstRHS, TAH, Diagnose ? &Selected : nullptr))
  6561. return true;
  6562. if (Diagnose) {
  6563. if (ConstRHS)
  6564. SubType.addConst();
  6565. if (!Selected && CSM == Sema::CXXDefaultConstructor) {
  6566. S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
  6567. << Kind << SubType.getUnqualifiedType();
  6568. if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
  6569. S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
  6570. } else if (!Selected)
  6571. S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
  6572. << Kind << SubType.getUnqualifiedType() << CSM << SubType;
  6573. else if (Selected->isUserProvided()) {
  6574. if (Kind == TSK_CompleteObject)
  6575. S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
  6576. << Kind << SubType.getUnqualifiedType() << CSM;
  6577. else {
  6578. S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
  6579. << Kind << SubType.getUnqualifiedType() << CSM;
  6580. S.Diag(Selected->getLocation(), diag::note_declared_at);
  6581. }
  6582. } else {
  6583. if (Kind != TSK_CompleteObject)
  6584. S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
  6585. << Kind << SubType.getUnqualifiedType() << CSM;
  6586. // Explain why the defaulted or deleted special member isn't trivial.
  6587. S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
  6588. Diagnose);
  6589. }
  6590. }
  6591. return false;
  6592. }
  6593. /// Check whether the members of a class type allow a special member to be
  6594. /// trivial.
  6595. static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
  6596. Sema::CXXSpecialMember CSM,
  6597. bool ConstArg,
  6598. Sema::TrivialABIHandling TAH,
  6599. bool Diagnose) {
  6600. for (const auto *FI : RD->fields()) {
  6601. if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
  6602. continue;
  6603. QualType FieldType = S.Context.getBaseElementType(FI->getType());
  6604. // Pretend anonymous struct or union members are members of this class.
  6605. if (FI->isAnonymousStructOrUnion()) {
  6606. if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
  6607. CSM, ConstArg, TAH, Diagnose))
  6608. return false;
  6609. continue;
  6610. }
  6611. // C++11 [class.ctor]p5:
  6612. // A default constructor is trivial if [...]
  6613. // -- no non-static data member of its class has a
  6614. // brace-or-equal-initializer
  6615. if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
  6616. if (Diagnose)
  6617. S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
  6618. return false;
  6619. }
  6620. // Objective C ARC 4.3.5:
  6621. // [...] nontrivally ownership-qualified types are [...] not trivially
  6622. // default constructible, copy constructible, move constructible, copy
  6623. // assignable, move assignable, or destructible [...]
  6624. if (FieldType.hasNonTrivialObjCLifetime()) {
  6625. if (Diagnose)
  6626. S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
  6627. << RD << FieldType.getObjCLifetime();
  6628. return false;
  6629. }
  6630. bool ConstRHS = ConstArg && !FI->isMutable();
  6631. if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
  6632. CSM, TSK_Field, TAH, Diagnose))
  6633. return false;
  6634. }
  6635. return true;
  6636. }
  6637. /// Diagnose why the specified class does not have a trivial special member of
  6638. /// the given kind.
  6639. void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
  6640. QualType Ty = Context.getRecordType(RD);
  6641. bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
  6642. checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
  6643. TSK_CompleteObject, TAH_IgnoreTrivialABI,
  6644. /*Diagnose*/true);
  6645. }
  6646. /// Determine whether a defaulted or deleted special member function is trivial,
  6647. /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
  6648. /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
  6649. bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
  6650. TrivialABIHandling TAH, bool Diagnose) {
  6651. assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
  6652. CXXRecordDecl *RD = MD->getParent();
  6653. bool ConstArg = false;
  6654. // C++11 [class.copy]p12, p25: [DR1593]
  6655. // A [special member] is trivial if [...] its parameter-type-list is
  6656. // equivalent to the parameter-type-list of an implicit declaration [...]
  6657. switch (CSM) {
  6658. case CXXDefaultConstructor:
  6659. case CXXDestructor:
  6660. // Trivial default constructors and destructors cannot have parameters.
  6661. break;
  6662. case CXXCopyConstructor:
  6663. case CXXCopyAssignment: {
  6664. // Trivial copy operations always have const, non-volatile parameter types.
  6665. ConstArg = true;
  6666. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6667. const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
  6668. if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
  6669. if (Diagnose)
  6670. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6671. << Param0->getSourceRange() << Param0->getType()
  6672. << Context.getLValueReferenceType(
  6673. Context.getRecordType(RD).withConst());
  6674. return false;
  6675. }
  6676. break;
  6677. }
  6678. case CXXMoveConstructor:
  6679. case CXXMoveAssignment: {
  6680. // Trivial move operations always have non-cv-qualified parameters.
  6681. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6682. const RValueReferenceType *RT =
  6683. Param0->getType()->getAs<RValueReferenceType>();
  6684. if (!RT || RT->getPointeeType().getCVRQualifiers()) {
  6685. if (Diagnose)
  6686. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6687. << Param0->getSourceRange() << Param0->getType()
  6688. << Context.getRValueReferenceType(Context.getRecordType(RD));
  6689. return false;
  6690. }
  6691. break;
  6692. }
  6693. case CXXInvalid:
  6694. llvm_unreachable("not a special member");
  6695. }
  6696. if (MD->getMinRequiredArguments() < MD->getNumParams()) {
  6697. if (Diagnose)
  6698. Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
  6699. diag::note_nontrivial_default_arg)
  6700. << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
  6701. return false;
  6702. }
  6703. if (MD->isVariadic()) {
  6704. if (Diagnose)
  6705. Diag(MD->getLocation(), diag::note_nontrivial_variadic);
  6706. return false;
  6707. }
  6708. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6709. // A copy/move [constructor or assignment operator] is trivial if
  6710. // -- the [member] selected to copy/move each direct base class subobject
  6711. // is trivial
  6712. //
  6713. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6714. // A [default constructor or destructor] is trivial if
  6715. // -- all the direct base classes have trivial [default constructors or
  6716. // destructors]
  6717. for (const auto &BI : RD->bases())
  6718. if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
  6719. ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
  6720. return false;
  6721. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6722. // A copy/move [constructor or assignment operator] for a class X is
  6723. // trivial if
  6724. // -- for each non-static data member of X that is of class type (or array
  6725. // thereof), the constructor selected to copy/move that member is
  6726. // trivial
  6727. //
  6728. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6729. // A [default constructor or destructor] is trivial if
  6730. // -- for all of the non-static data members of its class that are of class
  6731. // type (or array thereof), each such class has a trivial [default
  6732. // constructor or destructor]
  6733. if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
  6734. return false;
  6735. // C++11 [class.dtor]p5:
  6736. // A destructor is trivial if [...]
  6737. // -- the destructor is not virtual
  6738. if (CSM == CXXDestructor && MD->isVirtual()) {
  6739. if (Diagnose)
  6740. Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
  6741. return false;
  6742. }
  6743. // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
  6744. // A [special member] for class X is trivial if [...]
  6745. // -- class X has no virtual functions and no virtual base classes
  6746. if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
  6747. if (!Diagnose)
  6748. return false;
  6749. if (RD->getNumVBases()) {
  6750. // Check for virtual bases. We already know that the corresponding
  6751. // member in all bases is trivial, so vbases must all be direct.
  6752. CXXBaseSpecifier &BS = *RD->vbases_begin();
  6753. assert(BS.isVirtual());
  6754. Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
  6755. return false;
  6756. }
  6757. // Must have a virtual method.
  6758. for (const auto *MI : RD->methods()) {
  6759. if (MI->isVirtual()) {
  6760. SourceLocation MLoc = MI->getBeginLoc();
  6761. Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
  6762. return false;
  6763. }
  6764. }
  6765. llvm_unreachable("dynamic class with no vbases and no virtual functions");
  6766. }
  6767. // Looks like it's trivial!
  6768. return true;
  6769. }
  6770. namespace {
  6771. struct FindHiddenVirtualMethod {
  6772. Sema *S;
  6773. CXXMethodDecl *Method;
  6774. llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
  6775. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  6776. private:
  6777. /// Check whether any most overridden method from MD in Methods
  6778. static bool CheckMostOverridenMethods(
  6779. const CXXMethodDecl *MD,
  6780. const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
  6781. if (MD->size_overridden_methods() == 0)
  6782. return Methods.count(MD->getCanonicalDecl());
  6783. for (const CXXMethodDecl *O : MD->overridden_methods())
  6784. if (CheckMostOverridenMethods(O, Methods))
  6785. return true;
  6786. return false;
  6787. }
  6788. public:
  6789. /// Member lookup function that determines whether a given C++
  6790. /// method overloads virtual methods in a base class without overriding any,
  6791. /// to be used with CXXRecordDecl::lookupInBases().
  6792. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6793. RecordDecl *BaseRecord =
  6794. Specifier->getType()->getAs<RecordType>()->getDecl();
  6795. DeclarationName Name = Method->getDeclName();
  6796. assert(Name.getNameKind() == DeclarationName::Identifier);
  6797. bool foundSameNameMethod = false;
  6798. SmallVector<CXXMethodDecl *, 8> overloadedMethods;
  6799. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6800. Path.Decls = Path.Decls.slice(1)) {
  6801. NamedDecl *D = Path.Decls.front();
  6802. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6803. MD = MD->getCanonicalDecl();
  6804. foundSameNameMethod = true;
  6805. // Interested only in hidden virtual methods.
  6806. if (!MD->isVirtual())
  6807. continue;
  6808. // If the method we are checking overrides a method from its base
  6809. // don't warn about the other overloaded methods. Clang deviates from
  6810. // GCC by only diagnosing overloads of inherited virtual functions that
  6811. // do not override any other virtual functions in the base. GCC's
  6812. // -Woverloaded-virtual diagnoses any derived function hiding a virtual
  6813. // function from a base class. These cases may be better served by a
  6814. // warning (not specific to virtual functions) on call sites when the
  6815. // call would select a different function from the base class, were it
  6816. // visible.
  6817. // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
  6818. if (!S->IsOverload(Method, MD, false))
  6819. return true;
  6820. // Collect the overload only if its hidden.
  6821. if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
  6822. overloadedMethods.push_back(MD);
  6823. }
  6824. }
  6825. if (foundSameNameMethod)
  6826. OverloadedMethods.append(overloadedMethods.begin(),
  6827. overloadedMethods.end());
  6828. return foundSameNameMethod;
  6829. }
  6830. };
  6831. } // end anonymous namespace
  6832. /// Add the most overriden methods from MD to Methods
  6833. static void AddMostOverridenMethods(const CXXMethodDecl *MD,
  6834. llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
  6835. if (MD->size_overridden_methods() == 0)
  6836. Methods.insert(MD->getCanonicalDecl());
  6837. else
  6838. for (const CXXMethodDecl *O : MD->overridden_methods())
  6839. AddMostOverridenMethods(O, Methods);
  6840. }
  6841. /// Check if a method overloads virtual methods in a base class without
  6842. /// overriding any.
  6843. void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
  6844. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  6845. if (!MD->getDeclName().isIdentifier())
  6846. return;
  6847. CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
  6848. /*bool RecordPaths=*/false,
  6849. /*bool DetectVirtual=*/false);
  6850. FindHiddenVirtualMethod FHVM;
  6851. FHVM.Method = MD;
  6852. FHVM.S = this;
  6853. // Keep the base methods that were overridden or introduced in the subclass
  6854. // by 'using' in a set. A base method not in this set is hidden.
  6855. CXXRecordDecl *DC = MD->getParent();
  6856. DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
  6857. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
  6858. NamedDecl *ND = *I;
  6859. if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
  6860. ND = shad->getTargetDecl();
  6861. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  6862. AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
  6863. }
  6864. if (DC->lookupInBases(FHVM, Paths))
  6865. OverloadedMethods = FHVM.OverloadedMethods;
  6866. }
  6867. void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
  6868. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  6869. for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
  6870. CXXMethodDecl *overloadedMD = OverloadedMethods[i];
  6871. PartialDiagnostic PD = PDiag(
  6872. diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
  6873. HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
  6874. Diag(overloadedMD->getLocation(), PD);
  6875. }
  6876. }
  6877. /// Diagnose methods which overload virtual methods in a base class
  6878. /// without overriding any.
  6879. void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
  6880. if (MD->isInvalidDecl())
  6881. return;
  6882. if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
  6883. return;
  6884. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  6885. FindHiddenVirtualMethods(MD, OverloadedMethods);
  6886. if (!OverloadedMethods.empty()) {
  6887. Diag(MD->getLocation(), diag::warn_overloaded_virtual)
  6888. << MD << (OverloadedMethods.size() > 1);
  6889. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  6890. }
  6891. }
  6892. void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
  6893. auto PrintDiagAndRemoveAttr = [&]() {
  6894. // No diagnostics if this is a template instantiation.
  6895. if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
  6896. Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
  6897. diag::ext_cannot_use_trivial_abi) << &RD;
  6898. RD.dropAttr<TrivialABIAttr>();
  6899. };
  6900. // Ill-formed if the struct has virtual functions.
  6901. if (RD.isPolymorphic()) {
  6902. PrintDiagAndRemoveAttr();
  6903. return;
  6904. }
  6905. for (const auto &B : RD.bases()) {
  6906. // Ill-formed if the base class is non-trivial for the purpose of calls or a
  6907. // virtual base.
  6908. if ((!B.getType()->isDependentType() &&
  6909. !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
  6910. B.isVirtual()) {
  6911. PrintDiagAndRemoveAttr();
  6912. return;
  6913. }
  6914. }
  6915. for (const auto *FD : RD.fields()) {
  6916. // Ill-formed if the field is an ObjectiveC pointer or of a type that is
  6917. // non-trivial for the purpose of calls.
  6918. QualType FT = FD->getType();
  6919. if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
  6920. PrintDiagAndRemoveAttr();
  6921. return;
  6922. }
  6923. if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
  6924. if (!RT->isDependentType() &&
  6925. !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
  6926. PrintDiagAndRemoveAttr();
  6927. return;
  6928. }
  6929. }
  6930. }
  6931. void Sema::ActOnFinishCXXMemberSpecification(
  6932. Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
  6933. SourceLocation RBrac, const ParsedAttributesView &AttrList) {
  6934. if (!TagDecl)
  6935. return;
  6936. AdjustDeclIfTemplate(TagDecl);
  6937. for (const ParsedAttr &AL : AttrList) {
  6938. if (AL.getKind() != ParsedAttr::AT_Visibility)
  6939. continue;
  6940. AL.setInvalid();
  6941. Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
  6942. << AL.getName();
  6943. }
  6944. ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
  6945. // strict aliasing violation!
  6946. reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
  6947. FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
  6948. CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
  6949. }
  6950. /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
  6951. /// special functions, such as the default constructor, copy
  6952. /// constructor, or destructor, to the given C++ class (C++
  6953. /// [special]p1). This routine can only be executed just before the
  6954. /// definition of the class is complete.
  6955. void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
  6956. if (ClassDecl->needsImplicitDefaultConstructor()) {
  6957. ++getASTContext().NumImplicitDefaultConstructors;
  6958. if (ClassDecl->hasInheritedConstructor())
  6959. DeclareImplicitDefaultConstructor(ClassDecl);
  6960. }
  6961. if (ClassDecl->needsImplicitCopyConstructor()) {
  6962. ++getASTContext().NumImplicitCopyConstructors;
  6963. // If the properties or semantics of the copy constructor couldn't be
  6964. // determined while the class was being declared, force a declaration
  6965. // of it now.
  6966. if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
  6967. ClassDecl->hasInheritedConstructor())
  6968. DeclareImplicitCopyConstructor(ClassDecl);
  6969. // For the MS ABI we need to know whether the copy ctor is deleted. A
  6970. // prerequisite for deleting the implicit copy ctor is that the class has a
  6971. // move ctor or move assignment that is either user-declared or whose
  6972. // semantics are inherited from a subobject. FIXME: We should provide a more
  6973. // direct way for CodeGen to ask whether the constructor was deleted.
  6974. else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  6975. (ClassDecl->hasUserDeclaredMoveConstructor() ||
  6976. ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  6977. ClassDecl->hasUserDeclaredMoveAssignment() ||
  6978. ClassDecl->needsOverloadResolutionForMoveAssignment()))
  6979. DeclareImplicitCopyConstructor(ClassDecl);
  6980. }
  6981. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
  6982. ++getASTContext().NumImplicitMoveConstructors;
  6983. if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  6984. ClassDecl->hasInheritedConstructor())
  6985. DeclareImplicitMoveConstructor(ClassDecl);
  6986. }
  6987. if (ClassDecl->needsImplicitCopyAssignment()) {
  6988. ++getASTContext().NumImplicitCopyAssignmentOperators;
  6989. // If we have a dynamic class, then the copy assignment operator may be
  6990. // virtual, so we have to declare it immediately. This ensures that, e.g.,
  6991. // it shows up in the right place in the vtable and that we diagnose
  6992. // problems with the implicit exception specification.
  6993. if (ClassDecl->isDynamicClass() ||
  6994. ClassDecl->needsOverloadResolutionForCopyAssignment() ||
  6995. ClassDecl->hasInheritedAssignment())
  6996. DeclareImplicitCopyAssignment(ClassDecl);
  6997. }
  6998. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
  6999. ++getASTContext().NumImplicitMoveAssignmentOperators;
  7000. // Likewise for the move assignment operator.
  7001. if (ClassDecl->isDynamicClass() ||
  7002. ClassDecl->needsOverloadResolutionForMoveAssignment() ||
  7003. ClassDecl->hasInheritedAssignment())
  7004. DeclareImplicitMoveAssignment(ClassDecl);
  7005. }
  7006. if (ClassDecl->needsImplicitDestructor()) {
  7007. ++getASTContext().NumImplicitDestructors;
  7008. // If we have a dynamic class, then the destructor may be virtual, so we
  7009. // have to declare the destructor immediately. This ensures that, e.g., it
  7010. // shows up in the right place in the vtable and that we diagnose problems
  7011. // with the implicit exception specification.
  7012. if (ClassDecl->isDynamicClass() ||
  7013. ClassDecl->needsOverloadResolutionForDestructor())
  7014. DeclareImplicitDestructor(ClassDecl);
  7015. }
  7016. }
  7017. unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
  7018. if (!D)
  7019. return 0;
  7020. // The order of template parameters is not important here. All names
  7021. // get added to the same scope.
  7022. SmallVector<TemplateParameterList *, 4> ParameterLists;
  7023. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  7024. D = TD->getTemplatedDecl();
  7025. if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
  7026. ParameterLists.push_back(PSD->getTemplateParameters());
  7027. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  7028. for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
  7029. ParameterLists.push_back(DD->getTemplateParameterList(i));
  7030. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  7031. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  7032. ParameterLists.push_back(FTD->getTemplateParameters());
  7033. }
  7034. }
  7035. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  7036. for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
  7037. ParameterLists.push_back(TD->getTemplateParameterList(i));
  7038. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
  7039. if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
  7040. ParameterLists.push_back(CTD->getTemplateParameters());
  7041. }
  7042. }
  7043. unsigned Count = 0;
  7044. for (TemplateParameterList *Params : ParameterLists) {
  7045. if (Params->size() > 0)
  7046. // Ignore explicit specializations; they don't contribute to the template
  7047. // depth.
  7048. ++Count;
  7049. for (NamedDecl *Param : *Params) {
  7050. if (Param->getDeclName()) {
  7051. S->AddDecl(Param);
  7052. IdResolver.AddDecl(Param);
  7053. }
  7054. }
  7055. }
  7056. return Count;
  7057. }
  7058. void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  7059. if (!RecordD) return;
  7060. AdjustDeclIfTemplate(RecordD);
  7061. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
  7062. PushDeclContext(S, Record);
  7063. }
  7064. void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  7065. if (!RecordD) return;
  7066. PopDeclContext();
  7067. }
  7068. /// This is used to implement the constant expression evaluation part of the
  7069. /// attribute enable_if extension. There is nothing in standard C++ which would
  7070. /// require reentering parameters.
  7071. void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
  7072. if (!Param)
  7073. return;
  7074. S->AddDecl(Param);
  7075. if (Param->getDeclName())
  7076. IdResolver.AddDecl(Param);
  7077. }
  7078. /// ActOnStartDelayedCXXMethodDeclaration - We have completed
  7079. /// parsing a top-level (non-nested) C++ class, and we are now
  7080. /// parsing those parts of the given Method declaration that could
  7081. /// not be parsed earlier (C++ [class.mem]p2), such as default
  7082. /// arguments. This action should enter the scope of the given
  7083. /// Method declaration as if we had just parsed the qualified method
  7084. /// name. However, it should not bring the parameters into scope;
  7085. /// that will be performed by ActOnDelayedCXXMethodParameter.
  7086. void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  7087. }
  7088. /// ActOnDelayedCXXMethodParameter - We've already started a delayed
  7089. /// C++ method declaration. We're (re-)introducing the given
  7090. /// function parameter into scope for use in parsing later parts of
  7091. /// the method declaration. For example, we could see an
  7092. /// ActOnParamDefaultArgument event for this parameter.
  7093. void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
  7094. if (!ParamD)
  7095. return;
  7096. ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
  7097. // If this parameter has an unparsed default argument, clear it out
  7098. // to make way for the parsed default argument.
  7099. if (Param->hasUnparsedDefaultArg())
  7100. Param->setDefaultArg(nullptr);
  7101. S->AddDecl(Param);
  7102. if (Param->getDeclName())
  7103. IdResolver.AddDecl(Param);
  7104. }
  7105. /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
  7106. /// processing the delayed method declaration for Method. The method
  7107. /// declaration is now considered finished. There may be a separate
  7108. /// ActOnStartOfFunctionDef action later (not necessarily
  7109. /// immediately!) for this method, if it was also defined inside the
  7110. /// class body.
  7111. void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  7112. if (!MethodD)
  7113. return;
  7114. AdjustDeclIfTemplate(MethodD);
  7115. FunctionDecl *Method = cast<FunctionDecl>(MethodD);
  7116. // Now that we have our default arguments, check the constructor
  7117. // again. It could produce additional diagnostics or affect whether
  7118. // the class has implicitly-declared destructors, among other
  7119. // things.
  7120. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
  7121. CheckConstructor(Constructor);
  7122. // Check the default arguments, which we may have added.
  7123. if (!Method->isInvalidDecl())
  7124. CheckCXXDefaultArguments(Method);
  7125. }
  7126. /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
  7127. /// the well-formedness of the constructor declarator @p D with type @p
  7128. /// R. If there are any errors in the declarator, this routine will
  7129. /// emit diagnostics and set the invalid bit to true. In any case, the type
  7130. /// will be updated to reflect a well-formed type for the constructor and
  7131. /// returned.
  7132. QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
  7133. StorageClass &SC) {
  7134. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7135. // C++ [class.ctor]p3:
  7136. // A constructor shall not be virtual (10.3) or static (9.4). A
  7137. // constructor can be invoked for a const, volatile or const
  7138. // volatile object. A constructor shall not be declared const,
  7139. // volatile, or const volatile (9.3.2).
  7140. if (isVirtual) {
  7141. if (!D.isInvalidType())
  7142. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  7143. << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
  7144. << SourceRange(D.getIdentifierLoc());
  7145. D.setInvalidType();
  7146. }
  7147. if (SC == SC_Static) {
  7148. if (!D.isInvalidType())
  7149. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  7150. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7151. << SourceRange(D.getIdentifierLoc());
  7152. D.setInvalidType();
  7153. SC = SC_None;
  7154. }
  7155. if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  7156. diagnoseIgnoredQualifiers(
  7157. diag::err_constructor_return_type, TypeQuals, SourceLocation(),
  7158. D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
  7159. D.getDeclSpec().getRestrictSpecLoc(),
  7160. D.getDeclSpec().getAtomicSpecLoc());
  7161. D.setInvalidType();
  7162. }
  7163. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7164. if (FTI.hasMethodTypeQualifiers()) {
  7165. bool DiagOccured = false;
  7166. FTI.MethodQualifiers->forEachQualifier(
  7167. [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
  7168. // This diagnostic should be emitted on any qualifier except an addr
  7169. // space qualifier. However, forEachQualifier currently doesn't visit
  7170. // addr space qualifiers, so there's no way to write this condition
  7171. // right now; we just diagnose on everything.
  7172. Diag(SL, diag::err_invalid_qualified_constructor)
  7173. << QualName << SourceRange(SL);
  7174. DiagOccured = true;
  7175. });
  7176. if (DiagOccured)
  7177. D.setInvalidType();
  7178. }
  7179. // C++0x [class.ctor]p4:
  7180. // A constructor shall not be declared with a ref-qualifier.
  7181. if (FTI.hasRefQualifier()) {
  7182. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
  7183. << FTI.RefQualifierIsLValueRef
  7184. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  7185. D.setInvalidType();
  7186. }
  7187. // Rebuild the function type "R" without any type qualifiers (in
  7188. // case any of the errors above fired) and with "void" as the
  7189. // return type, since constructors don't have return types.
  7190. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7191. if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
  7192. return R;
  7193. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  7194. EPI.TypeQuals = Qualifiers();
  7195. EPI.RefQualifier = RQ_None;
  7196. return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
  7197. }
  7198. /// CheckConstructor - Checks a fully-formed constructor for
  7199. /// well-formedness, issuing any diagnostics required. Returns true if
  7200. /// the constructor declarator is invalid.
  7201. void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
  7202. CXXRecordDecl *ClassDecl
  7203. = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
  7204. if (!ClassDecl)
  7205. return Constructor->setInvalidDecl();
  7206. // C++ [class.copy]p3:
  7207. // A declaration of a constructor for a class X is ill-formed if
  7208. // its first parameter is of type (optionally cv-qualified) X and
  7209. // either there are no other parameters or else all other
  7210. // parameters have default arguments.
  7211. if (!Constructor->isInvalidDecl() &&
  7212. ((Constructor->getNumParams() == 1) ||
  7213. (Constructor->getNumParams() > 1 &&
  7214. Constructor->getParamDecl(1)->hasDefaultArg())) &&
  7215. Constructor->getTemplateSpecializationKind()
  7216. != TSK_ImplicitInstantiation) {
  7217. QualType ParamType = Constructor->getParamDecl(0)->getType();
  7218. QualType ClassTy = Context.getTagDeclType(ClassDecl);
  7219. if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
  7220. SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
  7221. const char *ConstRef
  7222. = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
  7223. : " const &";
  7224. Diag(ParamLoc, diag::err_constructor_byvalue_arg)
  7225. << FixItHint::CreateInsertion(ParamLoc, ConstRef);
  7226. // FIXME: Rather that making the constructor invalid, we should endeavor
  7227. // to fix the type.
  7228. Constructor->setInvalidDecl();
  7229. }
  7230. }
  7231. }
  7232. /// CheckDestructor - Checks a fully-formed destructor definition for
  7233. /// well-formedness, issuing any diagnostics required. Returns true
  7234. /// on error.
  7235. bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
  7236. CXXRecordDecl *RD = Destructor->getParent();
  7237. if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
  7238. SourceLocation Loc;
  7239. if (!Destructor->isImplicit())
  7240. Loc = Destructor->getLocation();
  7241. else
  7242. Loc = RD->getLocation();
  7243. // If we have a virtual destructor, look up the deallocation function
  7244. if (FunctionDecl *OperatorDelete =
  7245. FindDeallocationFunctionForDestructor(Loc, RD)) {
  7246. Expr *ThisArg = nullptr;
  7247. // If the notional 'delete this' expression requires a non-trivial
  7248. // conversion from 'this' to the type of a destroying operator delete's
  7249. // first parameter, perform that conversion now.
  7250. if (OperatorDelete->isDestroyingOperatorDelete()) {
  7251. QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
  7252. if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
  7253. // C++ [class.dtor]p13:
  7254. // ... as if for the expression 'delete this' appearing in a
  7255. // non-virtual destructor of the destructor's class.
  7256. ContextRAII SwitchContext(*this, Destructor);
  7257. ExprResult This =
  7258. ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
  7259. assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
  7260. This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
  7261. if (This.isInvalid()) {
  7262. // FIXME: Register this as a context note so that it comes out
  7263. // in the right order.
  7264. Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
  7265. return true;
  7266. }
  7267. ThisArg = This.get();
  7268. }
  7269. }
  7270. DiagnoseUseOfDecl(OperatorDelete, Loc);
  7271. MarkFunctionReferenced(Loc, OperatorDelete);
  7272. Destructor->setOperatorDelete(OperatorDelete, ThisArg);
  7273. }
  7274. }
  7275. return false;
  7276. }
  7277. /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
  7278. /// the well-formednes of the destructor declarator @p D with type @p
  7279. /// R. If there are any errors in the declarator, this routine will
  7280. /// emit diagnostics and set the declarator to invalid. Even if this happens,
  7281. /// will be updated to reflect a well-formed type for the destructor and
  7282. /// returned.
  7283. QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
  7284. StorageClass& SC) {
  7285. // C++ [class.dtor]p1:
  7286. // [...] A typedef-name that names a class is a class-name
  7287. // (7.1.3); however, a typedef-name that names a class shall not
  7288. // be used as the identifier in the declarator for a destructor
  7289. // declaration.
  7290. QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
  7291. if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
  7292. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  7293. << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
  7294. else if (const TemplateSpecializationType *TST =
  7295. DeclaratorType->getAs<TemplateSpecializationType>())
  7296. if (TST->isTypeAlias())
  7297. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  7298. << DeclaratorType << 1;
  7299. // C++ [class.dtor]p2:
  7300. // A destructor is used to destroy objects of its class type. A
  7301. // destructor takes no parameters, and no return type can be
  7302. // specified for it (not even void). The address of a destructor
  7303. // shall not be taken. A destructor shall not be static. A
  7304. // destructor can be invoked for a const, volatile or const
  7305. // volatile object. A destructor shall not be declared const,
  7306. // volatile or const volatile (9.3.2).
  7307. if (SC == SC_Static) {
  7308. if (!D.isInvalidType())
  7309. Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
  7310. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7311. << SourceRange(D.getIdentifierLoc())
  7312. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7313. SC = SC_None;
  7314. }
  7315. if (!D.isInvalidType()) {
  7316. // Destructors don't have return types, but the parser will
  7317. // happily parse something like:
  7318. //
  7319. // class X {
  7320. // float ~X();
  7321. // };
  7322. //
  7323. // The return type will be eliminated later.
  7324. if (D.getDeclSpec().hasTypeSpecifier())
  7325. Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
  7326. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7327. << SourceRange(D.getIdentifierLoc());
  7328. else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  7329. diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
  7330. SourceLocation(),
  7331. D.getDeclSpec().getConstSpecLoc(),
  7332. D.getDeclSpec().getVolatileSpecLoc(),
  7333. D.getDeclSpec().getRestrictSpecLoc(),
  7334. D.getDeclSpec().getAtomicSpecLoc());
  7335. D.setInvalidType();
  7336. }
  7337. }
  7338. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7339. if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
  7340. FTI.MethodQualifiers->forEachQualifier(
  7341. [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
  7342. Diag(SL, diag::err_invalid_qualified_destructor)
  7343. << QualName << SourceRange(SL);
  7344. });
  7345. D.setInvalidType();
  7346. }
  7347. // C++0x [class.dtor]p2:
  7348. // A destructor shall not be declared with a ref-qualifier.
  7349. if (FTI.hasRefQualifier()) {
  7350. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
  7351. << FTI.RefQualifierIsLValueRef
  7352. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  7353. D.setInvalidType();
  7354. }
  7355. // Make sure we don't have any parameters.
  7356. if (FTIHasNonVoidParameters(FTI)) {
  7357. Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
  7358. // Delete the parameters.
  7359. FTI.freeParams();
  7360. D.setInvalidType();
  7361. }
  7362. // Make sure the destructor isn't variadic.
  7363. if (FTI.isVariadic) {
  7364. Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
  7365. D.setInvalidType();
  7366. }
  7367. // Rebuild the function type "R" without any type qualifiers or
  7368. // parameters (in case any of the errors above fired) and with
  7369. // "void" as the return type, since destructors don't have return
  7370. // types.
  7371. if (!D.isInvalidType())
  7372. return R;
  7373. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7374. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  7375. EPI.Variadic = false;
  7376. EPI.TypeQuals = Qualifiers();
  7377. EPI.RefQualifier = RQ_None;
  7378. return Context.getFunctionType(Context.VoidTy, None, EPI);
  7379. }
  7380. static void extendLeft(SourceRange &R, SourceRange Before) {
  7381. if (Before.isInvalid())
  7382. return;
  7383. R.setBegin(Before.getBegin());
  7384. if (R.getEnd().isInvalid())
  7385. R.setEnd(Before.getEnd());
  7386. }
  7387. static void extendRight(SourceRange &R, SourceRange After) {
  7388. if (After.isInvalid())
  7389. return;
  7390. if (R.getBegin().isInvalid())
  7391. R.setBegin(After.getBegin());
  7392. R.setEnd(After.getEnd());
  7393. }
  7394. /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
  7395. /// well-formednes of the conversion function declarator @p D with
  7396. /// type @p R. If there are any errors in the declarator, this routine
  7397. /// will emit diagnostics and return true. Otherwise, it will return
  7398. /// false. Either way, the type @p R will be updated to reflect a
  7399. /// well-formed type for the conversion operator.
  7400. void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
  7401. StorageClass& SC) {
  7402. // C++ [class.conv.fct]p1:
  7403. // Neither parameter types nor return type can be specified. The
  7404. // type of a conversion function (8.3.5) is "function taking no
  7405. // parameter returning conversion-type-id."
  7406. if (SC == SC_Static) {
  7407. if (!D.isInvalidType())
  7408. Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
  7409. << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7410. << D.getName().getSourceRange();
  7411. D.setInvalidType();
  7412. SC = SC_None;
  7413. }
  7414. TypeSourceInfo *ConvTSI = nullptr;
  7415. QualType ConvType =
  7416. GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
  7417. const DeclSpec &DS = D.getDeclSpec();
  7418. if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
  7419. // Conversion functions don't have return types, but the parser will
  7420. // happily parse something like:
  7421. //
  7422. // class X {
  7423. // float operator bool();
  7424. // };
  7425. //
  7426. // The return type will be changed later anyway.
  7427. Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
  7428. << SourceRange(DS.getTypeSpecTypeLoc())
  7429. << SourceRange(D.getIdentifierLoc());
  7430. D.setInvalidType();
  7431. } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
  7432. // It's also plausible that the user writes type qualifiers in the wrong
  7433. // place, such as:
  7434. // struct S { const operator int(); };
  7435. // FIXME: we could provide a fixit to move the qualifiers onto the
  7436. // conversion type.
  7437. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
  7438. << SourceRange(D.getIdentifierLoc()) << 0;
  7439. D.setInvalidType();
  7440. }
  7441. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7442. // Make sure we don't have any parameters.
  7443. if (Proto->getNumParams() > 0) {
  7444. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
  7445. // Delete the parameters.
  7446. D.getFunctionTypeInfo().freeParams();
  7447. D.setInvalidType();
  7448. } else if (Proto->isVariadic()) {
  7449. Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
  7450. D.setInvalidType();
  7451. }
  7452. // Diagnose "&operator bool()" and other such nonsense. This
  7453. // is actually a gcc extension which we don't support.
  7454. if (Proto->getReturnType() != ConvType) {
  7455. bool NeedsTypedef = false;
  7456. SourceRange Before, After;
  7457. // Walk the chunks and extract information on them for our diagnostic.
  7458. bool PastFunctionChunk = false;
  7459. for (auto &Chunk : D.type_objects()) {
  7460. switch (Chunk.Kind) {
  7461. case DeclaratorChunk::Function:
  7462. if (!PastFunctionChunk) {
  7463. if (Chunk.Fun.HasTrailingReturnType) {
  7464. TypeSourceInfo *TRT = nullptr;
  7465. GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
  7466. if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
  7467. }
  7468. PastFunctionChunk = true;
  7469. break;
  7470. }
  7471. LLVM_FALLTHROUGH;
  7472. case DeclaratorChunk::Array:
  7473. NeedsTypedef = true;
  7474. extendRight(After, Chunk.getSourceRange());
  7475. break;
  7476. case DeclaratorChunk::Pointer:
  7477. case DeclaratorChunk::BlockPointer:
  7478. case DeclaratorChunk::Reference:
  7479. case DeclaratorChunk::MemberPointer:
  7480. case DeclaratorChunk::Pipe:
  7481. extendLeft(Before, Chunk.getSourceRange());
  7482. break;
  7483. case DeclaratorChunk::Paren:
  7484. extendLeft(Before, Chunk.Loc);
  7485. extendRight(After, Chunk.EndLoc);
  7486. break;
  7487. }
  7488. }
  7489. SourceLocation Loc = Before.isValid() ? Before.getBegin() :
  7490. After.isValid() ? After.getBegin() :
  7491. D.getIdentifierLoc();
  7492. auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
  7493. DB << Before << After;
  7494. if (!NeedsTypedef) {
  7495. DB << /*don't need a typedef*/0;
  7496. // If we can provide a correct fix-it hint, do so.
  7497. if (After.isInvalid() && ConvTSI) {
  7498. SourceLocation InsertLoc =
  7499. getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
  7500. DB << FixItHint::CreateInsertion(InsertLoc, " ")
  7501. << FixItHint::CreateInsertionFromRange(
  7502. InsertLoc, CharSourceRange::getTokenRange(Before))
  7503. << FixItHint::CreateRemoval(Before);
  7504. }
  7505. } else if (!Proto->getReturnType()->isDependentType()) {
  7506. DB << /*typedef*/1 << Proto->getReturnType();
  7507. } else if (getLangOpts().CPlusPlus11) {
  7508. DB << /*alias template*/2 << Proto->getReturnType();
  7509. } else {
  7510. DB << /*might not be fixable*/3;
  7511. }
  7512. // Recover by incorporating the other type chunks into the result type.
  7513. // Note, this does *not* change the name of the function. This is compatible
  7514. // with the GCC extension:
  7515. // struct S { &operator int(); } s;
  7516. // int &r = s.operator int(); // ok in GCC
  7517. // S::operator int&() {} // error in GCC, function name is 'operator int'.
  7518. ConvType = Proto->getReturnType();
  7519. }
  7520. // C++ [class.conv.fct]p4:
  7521. // The conversion-type-id shall not represent a function type nor
  7522. // an array type.
  7523. if (ConvType->isArrayType()) {
  7524. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
  7525. ConvType = Context.getPointerType(ConvType);
  7526. D.setInvalidType();
  7527. } else if (ConvType->isFunctionType()) {
  7528. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
  7529. ConvType = Context.getPointerType(ConvType);
  7530. D.setInvalidType();
  7531. }
  7532. // Rebuild the function type "R" without any parameters (in case any
  7533. // of the errors above fired) and with the conversion type as the
  7534. // return type.
  7535. if (D.isInvalidType())
  7536. R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
  7537. // C++0x explicit conversion operators.
  7538. if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
  7539. Diag(DS.getExplicitSpecLoc(),
  7540. getLangOpts().CPlusPlus11
  7541. ? diag::warn_cxx98_compat_explicit_conversion_functions
  7542. : diag::ext_explicit_conversion_functions)
  7543. << SourceRange(DS.getExplicitSpecRange());
  7544. }
  7545. /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
  7546. /// the declaration of the given C++ conversion function. This routine
  7547. /// is responsible for recording the conversion function in the C++
  7548. /// class, if possible.
  7549. Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
  7550. assert(Conversion && "Expected to receive a conversion function declaration");
  7551. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
  7552. // Make sure we aren't redeclaring the conversion function.
  7553. QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
  7554. // C++ [class.conv.fct]p1:
  7555. // [...] A conversion function is never used to convert a
  7556. // (possibly cv-qualified) object to the (possibly cv-qualified)
  7557. // same object type (or a reference to it), to a (possibly
  7558. // cv-qualified) base class of that type (or a reference to it),
  7559. // or to (possibly cv-qualified) void.
  7560. // FIXME: Suppress this warning if the conversion function ends up being a
  7561. // virtual function that overrides a virtual function in a base class.
  7562. QualType ClassType
  7563. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  7564. if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
  7565. ConvType = ConvTypeRef->getPointeeType();
  7566. if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
  7567. Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  7568. /* Suppress diagnostics for instantiations. */;
  7569. else if (ConvType->isRecordType()) {
  7570. ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
  7571. if (ConvType == ClassType)
  7572. Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
  7573. << ClassType;
  7574. else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
  7575. Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
  7576. << ClassType << ConvType;
  7577. } else if (ConvType->isVoidType()) {
  7578. Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
  7579. << ClassType << ConvType;
  7580. }
  7581. if (FunctionTemplateDecl *ConversionTemplate
  7582. = Conversion->getDescribedFunctionTemplate())
  7583. return ConversionTemplate;
  7584. return Conversion;
  7585. }
  7586. namespace {
  7587. /// Utility class to accumulate and print a diagnostic listing the invalid
  7588. /// specifier(s) on a declaration.
  7589. struct BadSpecifierDiagnoser {
  7590. BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
  7591. : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
  7592. ~BadSpecifierDiagnoser() {
  7593. Diagnostic << Specifiers;
  7594. }
  7595. template<typename T> void check(SourceLocation SpecLoc, T Spec) {
  7596. return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
  7597. }
  7598. void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
  7599. return check(SpecLoc,
  7600. DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
  7601. }
  7602. void check(SourceLocation SpecLoc, const char *Spec) {
  7603. if (SpecLoc.isInvalid()) return;
  7604. Diagnostic << SourceRange(SpecLoc, SpecLoc);
  7605. if (!Specifiers.empty()) Specifiers += " ";
  7606. Specifiers += Spec;
  7607. }
  7608. Sema &S;
  7609. Sema::SemaDiagnosticBuilder Diagnostic;
  7610. std::string Specifiers;
  7611. };
  7612. }
  7613. /// Check the validity of a declarator that we parsed for a deduction-guide.
  7614. /// These aren't actually declarators in the grammar, so we need to check that
  7615. /// the user didn't specify any pieces that are not part of the deduction-guide
  7616. /// grammar.
  7617. void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
  7618. StorageClass &SC) {
  7619. TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
  7620. TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
  7621. assert(GuidedTemplateDecl && "missing template decl for deduction guide");
  7622. // C++ [temp.deduct.guide]p3:
  7623. // A deduction-gide shall be declared in the same scope as the
  7624. // corresponding class template.
  7625. if (!CurContext->getRedeclContext()->Equals(
  7626. GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
  7627. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
  7628. << GuidedTemplateDecl;
  7629. Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
  7630. }
  7631. auto &DS = D.getMutableDeclSpec();
  7632. // We leave 'friend' and 'virtual' to be rejected in the normal way.
  7633. if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
  7634. DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
  7635. DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
  7636. BadSpecifierDiagnoser Diagnoser(
  7637. *this, D.getIdentifierLoc(),
  7638. diag::err_deduction_guide_invalid_specifier);
  7639. Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
  7640. DS.ClearStorageClassSpecs();
  7641. SC = SC_None;
  7642. // 'explicit' is permitted.
  7643. Diagnoser.check(DS.getInlineSpecLoc(), "inline");
  7644. Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
  7645. Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
  7646. DS.ClearConstexprSpec();
  7647. Diagnoser.check(DS.getConstSpecLoc(), "const");
  7648. Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
  7649. Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
  7650. Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
  7651. Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
  7652. DS.ClearTypeQualifiers();
  7653. Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
  7654. Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
  7655. Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
  7656. Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
  7657. DS.ClearTypeSpecType();
  7658. }
  7659. if (D.isInvalidType())
  7660. return;
  7661. // Check the declarator is simple enough.
  7662. bool FoundFunction = false;
  7663. for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
  7664. if (Chunk.Kind == DeclaratorChunk::Paren)
  7665. continue;
  7666. if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
  7667. Diag(D.getDeclSpec().getBeginLoc(),
  7668. diag::err_deduction_guide_with_complex_decl)
  7669. << D.getSourceRange();
  7670. break;
  7671. }
  7672. if (!Chunk.Fun.hasTrailingReturnType()) {
  7673. Diag(D.getName().getBeginLoc(),
  7674. diag::err_deduction_guide_no_trailing_return_type);
  7675. break;
  7676. }
  7677. // Check that the return type is written as a specialization of
  7678. // the template specified as the deduction-guide's name.
  7679. ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
  7680. TypeSourceInfo *TSI = nullptr;
  7681. QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
  7682. assert(TSI && "deduction guide has valid type but invalid return type?");
  7683. bool AcceptableReturnType = false;
  7684. bool MightInstantiateToSpecialization = false;
  7685. if (auto RetTST =
  7686. TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
  7687. TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
  7688. bool TemplateMatches =
  7689. Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
  7690. if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
  7691. AcceptableReturnType = true;
  7692. else {
  7693. // This could still instantiate to the right type, unless we know it
  7694. // names the wrong class template.
  7695. auto *TD = SpecifiedName.getAsTemplateDecl();
  7696. MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
  7697. !TemplateMatches);
  7698. }
  7699. } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
  7700. MightInstantiateToSpecialization = true;
  7701. }
  7702. if (!AcceptableReturnType) {
  7703. Diag(TSI->getTypeLoc().getBeginLoc(),
  7704. diag::err_deduction_guide_bad_trailing_return_type)
  7705. << GuidedTemplate << TSI->getType()
  7706. << MightInstantiateToSpecialization
  7707. << TSI->getTypeLoc().getSourceRange();
  7708. }
  7709. // Keep going to check that we don't have any inner declarator pieces (we
  7710. // could still have a function returning a pointer to a function).
  7711. FoundFunction = true;
  7712. }
  7713. if (D.isFunctionDefinition())
  7714. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
  7715. }
  7716. //===----------------------------------------------------------------------===//
  7717. // Namespace Handling
  7718. //===----------------------------------------------------------------------===//
  7719. /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
  7720. /// reopened.
  7721. static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
  7722. SourceLocation Loc,
  7723. IdentifierInfo *II, bool *IsInline,
  7724. NamespaceDecl *PrevNS) {
  7725. assert(*IsInline != PrevNS->isInline());
  7726. // HACK: Work around a bug in libstdc++4.6's <atomic>, where
  7727. // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
  7728. // inline namespaces, with the intention of bringing names into namespace std.
  7729. //
  7730. // We support this just well enough to get that case working; this is not
  7731. // sufficient to support reopening namespaces as inline in general.
  7732. if (*IsInline && II && II->getName().startswith("__atomic") &&
  7733. S.getSourceManager().isInSystemHeader(Loc)) {
  7734. // Mark all prior declarations of the namespace as inline.
  7735. for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
  7736. NS = NS->getPreviousDecl())
  7737. NS->setInline(*IsInline);
  7738. // Patch up the lookup table for the containing namespace. This isn't really
  7739. // correct, but it's good enough for this particular case.
  7740. for (auto *I : PrevNS->decls())
  7741. if (auto *ND = dyn_cast<NamedDecl>(I))
  7742. PrevNS->getParent()->makeDeclVisibleInContext(ND);
  7743. return;
  7744. }
  7745. if (PrevNS->isInline())
  7746. // The user probably just forgot the 'inline', so suggest that it
  7747. // be added back.
  7748. S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
  7749. << FixItHint::CreateInsertion(KeywordLoc, "inline ");
  7750. else
  7751. S.Diag(Loc, diag::err_inline_namespace_mismatch);
  7752. S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
  7753. *IsInline = PrevNS->isInline();
  7754. }
  7755. /// ActOnStartNamespaceDef - This is called at the start of a namespace
  7756. /// definition.
  7757. Decl *Sema::ActOnStartNamespaceDef(
  7758. Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
  7759. SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
  7760. const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
  7761. SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
  7762. // For anonymous namespace, take the location of the left brace.
  7763. SourceLocation Loc = II ? IdentLoc : LBrace;
  7764. bool IsInline = InlineLoc.isValid();
  7765. bool IsInvalid = false;
  7766. bool IsStd = false;
  7767. bool AddToKnown = false;
  7768. Scope *DeclRegionScope = NamespcScope->getParent();
  7769. NamespaceDecl *PrevNS = nullptr;
  7770. if (II) {
  7771. // C++ [namespace.def]p2:
  7772. // The identifier in an original-namespace-definition shall not
  7773. // have been previously defined in the declarative region in
  7774. // which the original-namespace-definition appears. The
  7775. // identifier in an original-namespace-definition is the name of
  7776. // the namespace. Subsequently in that declarative region, it is
  7777. // treated as an original-namespace-name.
  7778. //
  7779. // Since namespace names are unique in their scope, and we don't
  7780. // look through using directives, just look for any ordinary names
  7781. // as if by qualified name lookup.
  7782. LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
  7783. ForExternalRedeclaration);
  7784. LookupQualifiedName(R, CurContext->getRedeclContext());
  7785. NamedDecl *PrevDecl =
  7786. R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
  7787. PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
  7788. if (PrevNS) {
  7789. // This is an extended namespace definition.
  7790. if (IsInline != PrevNS->isInline())
  7791. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
  7792. &IsInline, PrevNS);
  7793. } else if (PrevDecl) {
  7794. // This is an invalid name redefinition.
  7795. Diag(Loc, diag::err_redefinition_different_kind)
  7796. << II;
  7797. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  7798. IsInvalid = true;
  7799. // Continue on to push Namespc as current DeclContext and return it.
  7800. } else if (II->isStr("std") &&
  7801. CurContext->getRedeclContext()->isTranslationUnit()) {
  7802. // This is the first "real" definition of the namespace "std", so update
  7803. // our cache of the "std" namespace to point at this definition.
  7804. PrevNS = getStdNamespace();
  7805. IsStd = true;
  7806. AddToKnown = !IsInline;
  7807. } else {
  7808. // We've seen this namespace for the first time.
  7809. AddToKnown = !IsInline;
  7810. }
  7811. } else {
  7812. // Anonymous namespaces.
  7813. // Determine whether the parent already has an anonymous namespace.
  7814. DeclContext *Parent = CurContext->getRedeclContext();
  7815. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  7816. PrevNS = TU->getAnonymousNamespace();
  7817. } else {
  7818. NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
  7819. PrevNS = ND->getAnonymousNamespace();
  7820. }
  7821. if (PrevNS && IsInline != PrevNS->isInline())
  7822. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
  7823. &IsInline, PrevNS);
  7824. }
  7825. NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
  7826. StartLoc, Loc, II, PrevNS);
  7827. if (IsInvalid)
  7828. Namespc->setInvalidDecl();
  7829. ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
  7830. AddPragmaAttributes(DeclRegionScope, Namespc);
  7831. // FIXME: Should we be merging attributes?
  7832. if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
  7833. PushNamespaceVisibilityAttr(Attr, Loc);
  7834. if (IsStd)
  7835. StdNamespace = Namespc;
  7836. if (AddToKnown)
  7837. KnownNamespaces[Namespc] = false;
  7838. if (II) {
  7839. PushOnScopeChains(Namespc, DeclRegionScope);
  7840. } else {
  7841. // Link the anonymous namespace into its parent.
  7842. DeclContext *Parent = CurContext->getRedeclContext();
  7843. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  7844. TU->setAnonymousNamespace(Namespc);
  7845. } else {
  7846. cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
  7847. }
  7848. CurContext->addDecl(Namespc);
  7849. // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
  7850. // behaves as if it were replaced by
  7851. // namespace unique { /* empty body */ }
  7852. // using namespace unique;
  7853. // namespace unique { namespace-body }
  7854. // where all occurrences of 'unique' in a translation unit are
  7855. // replaced by the same identifier and this identifier differs
  7856. // from all other identifiers in the entire program.
  7857. // We just create the namespace with an empty name and then add an
  7858. // implicit using declaration, just like the standard suggests.
  7859. //
  7860. // CodeGen enforces the "universally unique" aspect by giving all
  7861. // declarations semantically contained within an anonymous
  7862. // namespace internal linkage.
  7863. if (!PrevNS) {
  7864. UD = UsingDirectiveDecl::Create(Context, Parent,
  7865. /* 'using' */ LBrace,
  7866. /* 'namespace' */ SourceLocation(),
  7867. /* qualifier */ NestedNameSpecifierLoc(),
  7868. /* identifier */ SourceLocation(),
  7869. Namespc,
  7870. /* Ancestor */ Parent);
  7871. UD->setImplicit();
  7872. Parent->addDecl(UD);
  7873. }
  7874. }
  7875. ActOnDocumentableDecl(Namespc);
  7876. // Although we could have an invalid decl (i.e. the namespace name is a
  7877. // redefinition), push it as current DeclContext and try to continue parsing.
  7878. // FIXME: We should be able to push Namespc here, so that the each DeclContext
  7879. // for the namespace has the declarations that showed up in that particular
  7880. // namespace definition.
  7881. PushDeclContext(NamespcScope, Namespc);
  7882. return Namespc;
  7883. }
  7884. /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
  7885. /// is a namespace alias, returns the namespace it points to.
  7886. static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
  7887. if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
  7888. return AD->getNamespace();
  7889. return dyn_cast_or_null<NamespaceDecl>(D);
  7890. }
  7891. /// ActOnFinishNamespaceDef - This callback is called after a namespace is
  7892. /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
  7893. void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
  7894. NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
  7895. assert(Namespc && "Invalid parameter, expected NamespaceDecl");
  7896. Namespc->setRBraceLoc(RBrace);
  7897. PopDeclContext();
  7898. if (Namespc->hasAttr<VisibilityAttr>())
  7899. PopPragmaVisibility(true, RBrace);
  7900. // If this namespace contains an export-declaration, export it now.
  7901. if (DeferredExportedNamespaces.erase(Namespc))
  7902. Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
  7903. }
  7904. CXXRecordDecl *Sema::getStdBadAlloc() const {
  7905. return cast_or_null<CXXRecordDecl>(
  7906. StdBadAlloc.get(Context.getExternalSource()));
  7907. }
  7908. EnumDecl *Sema::getStdAlignValT() const {
  7909. return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
  7910. }
  7911. NamespaceDecl *Sema::getStdNamespace() const {
  7912. return cast_or_null<NamespaceDecl>(
  7913. StdNamespace.get(Context.getExternalSource()));
  7914. }
  7915. NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
  7916. if (!StdExperimentalNamespaceCache) {
  7917. if (auto Std = getStdNamespace()) {
  7918. LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
  7919. SourceLocation(), LookupNamespaceName);
  7920. if (!LookupQualifiedName(Result, Std) ||
  7921. !(StdExperimentalNamespaceCache =
  7922. Result.getAsSingle<NamespaceDecl>()))
  7923. Result.suppressDiagnostics();
  7924. }
  7925. }
  7926. return StdExperimentalNamespaceCache;
  7927. }
  7928. namespace {
  7929. enum UnsupportedSTLSelect {
  7930. USS_InvalidMember,
  7931. USS_MissingMember,
  7932. USS_NonTrivial,
  7933. USS_Other
  7934. };
  7935. struct InvalidSTLDiagnoser {
  7936. Sema &S;
  7937. SourceLocation Loc;
  7938. QualType TyForDiags;
  7939. QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
  7940. const VarDecl *VD = nullptr) {
  7941. {
  7942. auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
  7943. << TyForDiags << ((int)Sel);
  7944. if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
  7945. assert(!Name.empty());
  7946. D << Name;
  7947. }
  7948. }
  7949. if (Sel == USS_InvalidMember) {
  7950. S.Diag(VD->getLocation(), diag::note_var_declared_here)
  7951. << VD << VD->getSourceRange();
  7952. }
  7953. return QualType();
  7954. }
  7955. };
  7956. } // namespace
  7957. QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
  7958. SourceLocation Loc) {
  7959. assert(getLangOpts().CPlusPlus &&
  7960. "Looking for comparison category type outside of C++.");
  7961. // Check if we've already successfully checked the comparison category type
  7962. // before. If so, skip checking it again.
  7963. ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
  7964. if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
  7965. return Info->getType();
  7966. // If lookup failed
  7967. if (!Info) {
  7968. std::string NameForDiags = "std::";
  7969. NameForDiags += ComparisonCategories::getCategoryString(Kind);
  7970. Diag(Loc, diag::err_implied_comparison_category_type_not_found)
  7971. << NameForDiags;
  7972. return QualType();
  7973. }
  7974. assert(Info->Kind == Kind);
  7975. assert(Info->Record);
  7976. // Update the Record decl in case we encountered a forward declaration on our
  7977. // first pass. FIXME: This is a bit of a hack.
  7978. if (Info->Record->hasDefinition())
  7979. Info->Record = Info->Record->getDefinition();
  7980. // Use an elaborated type for diagnostics which has a name containing the
  7981. // prepended 'std' namespace but not any inline namespace names.
  7982. QualType TyForDiags = [&]() {
  7983. auto *NNS =
  7984. NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
  7985. return Context.getElaboratedType(ETK_None, NNS, Info->getType());
  7986. }();
  7987. if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
  7988. return QualType();
  7989. InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
  7990. if (!Info->Record->isTriviallyCopyable())
  7991. return UnsupportedSTLError(USS_NonTrivial);
  7992. for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
  7993. CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
  7994. // Tolerate empty base classes.
  7995. if (Base->isEmpty())
  7996. continue;
  7997. // Reject STL implementations which have at least one non-empty base.
  7998. return UnsupportedSTLError();
  7999. }
  8000. // Check that the STL has implemented the types using a single integer field.
  8001. // This expectation allows better codegen for builtin operators. We require:
  8002. // (1) The class has exactly one field.
  8003. // (2) The field is an integral or enumeration type.
  8004. auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
  8005. if (std::distance(FIt, FEnd) != 1 ||
  8006. !FIt->getType()->isIntegralOrEnumerationType()) {
  8007. return UnsupportedSTLError();
  8008. }
  8009. // Build each of the require values and store them in Info.
  8010. for (ComparisonCategoryResult CCR :
  8011. ComparisonCategories::getPossibleResultsForType(Kind)) {
  8012. StringRef MemName = ComparisonCategories::getResultString(CCR);
  8013. ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
  8014. if (!ValInfo)
  8015. return UnsupportedSTLError(USS_MissingMember, MemName);
  8016. VarDecl *VD = ValInfo->VD;
  8017. assert(VD && "should not be null!");
  8018. // Attempt to diagnose reasons why the STL definition of this type
  8019. // might be foobar, including it failing to be a constant expression.
  8020. // TODO Handle more ways the lookup or result can be invalid.
  8021. if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
  8022. !VD->checkInitIsICE())
  8023. return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
  8024. // Attempt to evaluate the var decl as a constant expression and extract
  8025. // the value of its first field as a ICE. If this fails, the STL
  8026. // implementation is not supported.
  8027. if (!ValInfo->hasValidIntValue())
  8028. return UnsupportedSTLError();
  8029. MarkVariableReferenced(Loc, VD);
  8030. }
  8031. // We've successfully built the required types and expressions. Update
  8032. // the cache and return the newly cached value.
  8033. FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
  8034. return Info->getType();
  8035. }
  8036. /// Retrieve the special "std" namespace, which may require us to
  8037. /// implicitly define the namespace.
  8038. NamespaceDecl *Sema::getOrCreateStdNamespace() {
  8039. if (!StdNamespace) {
  8040. // The "std" namespace has not yet been defined, so build one implicitly.
  8041. StdNamespace = NamespaceDecl::Create(Context,
  8042. Context.getTranslationUnitDecl(),
  8043. /*Inline=*/false,
  8044. SourceLocation(), SourceLocation(),
  8045. &PP.getIdentifierTable().get("std"),
  8046. /*PrevDecl=*/nullptr);
  8047. getStdNamespace()->setImplicit(true);
  8048. }
  8049. return getStdNamespace();
  8050. }
  8051. bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
  8052. assert(getLangOpts().CPlusPlus &&
  8053. "Looking for std::initializer_list outside of C++.");
  8054. // We're looking for implicit instantiations of
  8055. // template <typename E> class std::initializer_list.
  8056. if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
  8057. return false;
  8058. ClassTemplateDecl *Template = nullptr;
  8059. const TemplateArgument *Arguments = nullptr;
  8060. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  8061. ClassTemplateSpecializationDecl *Specialization =
  8062. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  8063. if (!Specialization)
  8064. return false;
  8065. Template = Specialization->getSpecializedTemplate();
  8066. Arguments = Specialization->getTemplateArgs().data();
  8067. } else if (const TemplateSpecializationType *TST =
  8068. Ty->getAs<TemplateSpecializationType>()) {
  8069. Template = dyn_cast_or_null<ClassTemplateDecl>(
  8070. TST->getTemplateName().getAsTemplateDecl());
  8071. Arguments = TST->getArgs();
  8072. }
  8073. if (!Template)
  8074. return false;
  8075. if (!StdInitializerList) {
  8076. // Haven't recognized std::initializer_list yet, maybe this is it.
  8077. CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
  8078. if (TemplateClass->getIdentifier() !=
  8079. &PP.getIdentifierTable().get("initializer_list") ||
  8080. !getStdNamespace()->InEnclosingNamespaceSetOf(
  8081. TemplateClass->getDeclContext()))
  8082. return false;
  8083. // This is a template called std::initializer_list, but is it the right
  8084. // template?
  8085. TemplateParameterList *Params = Template->getTemplateParameters();
  8086. if (Params->getMinRequiredArguments() != 1)
  8087. return false;
  8088. if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
  8089. return false;
  8090. // It's the right template.
  8091. StdInitializerList = Template;
  8092. }
  8093. if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
  8094. return false;
  8095. // This is an instance of std::initializer_list. Find the argument type.
  8096. if (Element)
  8097. *Element = Arguments[0].getAsType();
  8098. return true;
  8099. }
  8100. static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
  8101. NamespaceDecl *Std = S.getStdNamespace();
  8102. if (!Std) {
  8103. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  8104. return nullptr;
  8105. }
  8106. LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
  8107. Loc, Sema::LookupOrdinaryName);
  8108. if (!S.LookupQualifiedName(Result, Std)) {
  8109. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  8110. return nullptr;
  8111. }
  8112. ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
  8113. if (!Template) {
  8114. Result.suppressDiagnostics();
  8115. // We found something weird. Complain about the first thing we found.
  8116. NamedDecl *Found = *Result.begin();
  8117. S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
  8118. return nullptr;
  8119. }
  8120. // We found some template called std::initializer_list. Now verify that it's
  8121. // correct.
  8122. TemplateParameterList *Params = Template->getTemplateParameters();
  8123. if (Params->getMinRequiredArguments() != 1 ||
  8124. !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  8125. S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
  8126. return nullptr;
  8127. }
  8128. return Template;
  8129. }
  8130. QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
  8131. if (!StdInitializerList) {
  8132. StdInitializerList = LookupStdInitializerList(*this, Loc);
  8133. if (!StdInitializerList)
  8134. return QualType();
  8135. }
  8136. TemplateArgumentListInfo Args(Loc, Loc);
  8137. Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
  8138. Context.getTrivialTypeSourceInfo(Element,
  8139. Loc)));
  8140. return Context.getCanonicalType(
  8141. CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
  8142. }
  8143. bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
  8144. // C++ [dcl.init.list]p2:
  8145. // A constructor is an initializer-list constructor if its first parameter
  8146. // is of type std::initializer_list<E> or reference to possibly cv-qualified
  8147. // std::initializer_list<E> for some type E, and either there are no other
  8148. // parameters or else all other parameters have default arguments.
  8149. if (Ctor->getNumParams() < 1 ||
  8150. (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
  8151. return false;
  8152. QualType ArgType = Ctor->getParamDecl(0)->getType();
  8153. if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
  8154. ArgType = RT->getPointeeType().getUnqualifiedType();
  8155. return isStdInitializerList(ArgType, nullptr);
  8156. }
  8157. /// Determine whether a using statement is in a context where it will be
  8158. /// apply in all contexts.
  8159. static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
  8160. switch (CurContext->getDeclKind()) {
  8161. case Decl::TranslationUnit:
  8162. return true;
  8163. case Decl::LinkageSpec:
  8164. return IsUsingDirectiveInToplevelContext(CurContext->getParent());
  8165. default:
  8166. return false;
  8167. }
  8168. }
  8169. namespace {
  8170. // Callback to only accept typo corrections that are namespaces.
  8171. class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
  8172. public:
  8173. bool ValidateCandidate(const TypoCorrection &candidate) override {
  8174. if (NamedDecl *ND = candidate.getCorrectionDecl())
  8175. return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
  8176. return false;
  8177. }
  8178. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  8179. return llvm::make_unique<NamespaceValidatorCCC>(*this);
  8180. }
  8181. };
  8182. }
  8183. static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
  8184. CXXScopeSpec &SS,
  8185. SourceLocation IdentLoc,
  8186. IdentifierInfo *Ident) {
  8187. R.clear();
  8188. NamespaceValidatorCCC CCC{};
  8189. if (TypoCorrection Corrected =
  8190. S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
  8191. Sema::CTK_ErrorRecovery)) {
  8192. if (DeclContext *DC = S.computeDeclContext(SS, false)) {
  8193. std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
  8194. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  8195. Ident->getName().equals(CorrectedStr);
  8196. S.diagnoseTypo(Corrected,
  8197. S.PDiag(diag::err_using_directive_member_suggest)
  8198. << Ident << DC << DroppedSpecifier << SS.getRange(),
  8199. S.PDiag(diag::note_namespace_defined_here));
  8200. } else {
  8201. S.diagnoseTypo(Corrected,
  8202. S.PDiag(diag::err_using_directive_suggest) << Ident,
  8203. S.PDiag(diag::note_namespace_defined_here));
  8204. }
  8205. R.addDecl(Corrected.getFoundDecl());
  8206. return true;
  8207. }
  8208. return false;
  8209. }
  8210. Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
  8211. SourceLocation NamespcLoc, CXXScopeSpec &SS,
  8212. SourceLocation IdentLoc,
  8213. IdentifierInfo *NamespcName,
  8214. const ParsedAttributesView &AttrList) {
  8215. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  8216. assert(NamespcName && "Invalid NamespcName.");
  8217. assert(IdentLoc.isValid() && "Invalid NamespceName location.");
  8218. // This can only happen along a recovery path.
  8219. while (S->isTemplateParamScope())
  8220. S = S->getParent();
  8221. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  8222. UsingDirectiveDecl *UDir = nullptr;
  8223. NestedNameSpecifier *Qualifier = nullptr;
  8224. if (SS.isSet())
  8225. Qualifier = SS.getScopeRep();
  8226. // Lookup namespace name.
  8227. LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
  8228. LookupParsedName(R, S, &SS);
  8229. if (R.isAmbiguous())
  8230. return nullptr;
  8231. if (R.empty()) {
  8232. R.clear();
  8233. // Allow "using namespace std;" or "using namespace ::std;" even if
  8234. // "std" hasn't been defined yet, for GCC compatibility.
  8235. if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
  8236. NamespcName->isStr("std")) {
  8237. Diag(IdentLoc, diag::ext_using_undefined_std);
  8238. R.addDecl(getOrCreateStdNamespace());
  8239. R.resolveKind();
  8240. }
  8241. // Otherwise, attempt typo correction.
  8242. else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
  8243. }
  8244. if (!R.empty()) {
  8245. NamedDecl *Named = R.getRepresentativeDecl();
  8246. NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
  8247. assert(NS && "expected namespace decl");
  8248. // The use of a nested name specifier may trigger deprecation warnings.
  8249. DiagnoseUseOfDecl(Named, IdentLoc);
  8250. // C++ [namespace.udir]p1:
  8251. // A using-directive specifies that the names in the nominated
  8252. // namespace can be used in the scope in which the
  8253. // using-directive appears after the using-directive. During
  8254. // unqualified name lookup (3.4.1), the names appear as if they
  8255. // were declared in the nearest enclosing namespace which
  8256. // contains both the using-directive and the nominated
  8257. // namespace. [Note: in this context, "contains" means "contains
  8258. // directly or indirectly". ]
  8259. // Find enclosing context containing both using-directive and
  8260. // nominated namespace.
  8261. DeclContext *CommonAncestor = NS;
  8262. while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
  8263. CommonAncestor = CommonAncestor->getParent();
  8264. UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
  8265. SS.getWithLocInContext(Context),
  8266. IdentLoc, Named, CommonAncestor);
  8267. if (IsUsingDirectiveInToplevelContext(CurContext) &&
  8268. !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
  8269. Diag(IdentLoc, diag::warn_using_directive_in_header);
  8270. }
  8271. PushUsingDirective(S, UDir);
  8272. } else {
  8273. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  8274. }
  8275. if (UDir)
  8276. ProcessDeclAttributeList(S, UDir, AttrList);
  8277. return UDir;
  8278. }
  8279. void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
  8280. // If the scope has an associated entity and the using directive is at
  8281. // namespace or translation unit scope, add the UsingDirectiveDecl into
  8282. // its lookup structure so qualified name lookup can find it.
  8283. DeclContext *Ctx = S->getEntity();
  8284. if (Ctx && !Ctx->isFunctionOrMethod())
  8285. Ctx->addDecl(UDir);
  8286. else
  8287. // Otherwise, it is at block scope. The using-directives will affect lookup
  8288. // only to the end of the scope.
  8289. S->PushUsingDirective(UDir);
  8290. }
  8291. Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
  8292. SourceLocation UsingLoc,
  8293. SourceLocation TypenameLoc, CXXScopeSpec &SS,
  8294. UnqualifiedId &Name,
  8295. SourceLocation EllipsisLoc,
  8296. const ParsedAttributesView &AttrList) {
  8297. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  8298. if (SS.isEmpty()) {
  8299. Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
  8300. return nullptr;
  8301. }
  8302. switch (Name.getKind()) {
  8303. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  8304. case UnqualifiedIdKind::IK_Identifier:
  8305. case UnqualifiedIdKind::IK_OperatorFunctionId:
  8306. case UnqualifiedIdKind::IK_LiteralOperatorId:
  8307. case UnqualifiedIdKind::IK_ConversionFunctionId:
  8308. break;
  8309. case UnqualifiedIdKind::IK_ConstructorName:
  8310. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  8311. // C++11 inheriting constructors.
  8312. Diag(Name.getBeginLoc(),
  8313. getLangOpts().CPlusPlus11
  8314. ? diag::warn_cxx98_compat_using_decl_constructor
  8315. : diag::err_using_decl_constructor)
  8316. << SS.getRange();
  8317. if (getLangOpts().CPlusPlus11) break;
  8318. return nullptr;
  8319. case UnqualifiedIdKind::IK_DestructorName:
  8320. Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
  8321. return nullptr;
  8322. case UnqualifiedIdKind::IK_TemplateId:
  8323. Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
  8324. << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
  8325. return nullptr;
  8326. case UnqualifiedIdKind::IK_DeductionGuideName:
  8327. llvm_unreachable("cannot parse qualified deduction guide name");
  8328. }
  8329. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  8330. DeclarationName TargetName = TargetNameInfo.getName();
  8331. if (!TargetName)
  8332. return nullptr;
  8333. // Warn about access declarations.
  8334. if (UsingLoc.isInvalid()) {
  8335. Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
  8336. ? diag::err_access_decl
  8337. : diag::warn_access_decl_deprecated)
  8338. << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
  8339. }
  8340. if (EllipsisLoc.isInvalid()) {
  8341. if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
  8342. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
  8343. return nullptr;
  8344. } else {
  8345. if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
  8346. !TargetNameInfo.containsUnexpandedParameterPack()) {
  8347. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  8348. << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
  8349. EllipsisLoc = SourceLocation();
  8350. }
  8351. }
  8352. NamedDecl *UD =
  8353. BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
  8354. SS, TargetNameInfo, EllipsisLoc, AttrList,
  8355. /*IsInstantiation*/false);
  8356. if (UD)
  8357. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  8358. return UD;
  8359. }
  8360. /// Determine whether a using declaration considers the given
  8361. /// declarations as "equivalent", e.g., if they are redeclarations of
  8362. /// the same entity or are both typedefs of the same type.
  8363. static bool
  8364. IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
  8365. if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
  8366. return true;
  8367. if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
  8368. if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
  8369. return Context.hasSameType(TD1->getUnderlyingType(),
  8370. TD2->getUnderlyingType());
  8371. return false;
  8372. }
  8373. /// Determines whether to create a using shadow decl for a particular
  8374. /// decl, given the set of decls existing prior to this using lookup.
  8375. bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
  8376. const LookupResult &Previous,
  8377. UsingShadowDecl *&PrevShadow) {
  8378. // Diagnose finding a decl which is not from a base class of the
  8379. // current class. We do this now because there are cases where this
  8380. // function will silently decide not to build a shadow decl, which
  8381. // will pre-empt further diagnostics.
  8382. //
  8383. // We don't need to do this in C++11 because we do the check once on
  8384. // the qualifier.
  8385. //
  8386. // FIXME: diagnose the following if we care enough:
  8387. // struct A { int foo; };
  8388. // struct B : A { using A::foo; };
  8389. // template <class T> struct C : A {};
  8390. // template <class T> struct D : C<T> { using B::foo; } // <---
  8391. // This is invalid (during instantiation) in C++03 because B::foo
  8392. // resolves to the using decl in B, which is not a base class of D<T>.
  8393. // We can't diagnose it immediately because C<T> is an unknown
  8394. // specialization. The UsingShadowDecl in D<T> then points directly
  8395. // to A::foo, which will look well-formed when we instantiate.
  8396. // The right solution is to not collapse the shadow-decl chain.
  8397. if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
  8398. DeclContext *OrigDC = Orig->getDeclContext();
  8399. // Handle enums and anonymous structs.
  8400. if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
  8401. CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
  8402. while (OrigRec->isAnonymousStructOrUnion())
  8403. OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
  8404. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
  8405. if (OrigDC == CurContext) {
  8406. Diag(Using->getLocation(),
  8407. diag::err_using_decl_nested_name_specifier_is_current_class)
  8408. << Using->getQualifierLoc().getSourceRange();
  8409. Diag(Orig->getLocation(), diag::note_using_decl_target);
  8410. Using->setInvalidDecl();
  8411. return true;
  8412. }
  8413. Diag(Using->getQualifierLoc().getBeginLoc(),
  8414. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  8415. << Using->getQualifier()
  8416. << cast<CXXRecordDecl>(CurContext)
  8417. << Using->getQualifierLoc().getSourceRange();
  8418. Diag(Orig->getLocation(), diag::note_using_decl_target);
  8419. Using->setInvalidDecl();
  8420. return true;
  8421. }
  8422. }
  8423. if (Previous.empty()) return false;
  8424. NamedDecl *Target = Orig;
  8425. if (isa<UsingShadowDecl>(Target))
  8426. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  8427. // If the target happens to be one of the previous declarations, we
  8428. // don't have a conflict.
  8429. //
  8430. // FIXME: but we might be increasing its access, in which case we
  8431. // should redeclare it.
  8432. NamedDecl *NonTag = nullptr, *Tag = nullptr;
  8433. bool FoundEquivalentDecl = false;
  8434. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  8435. I != E; ++I) {
  8436. NamedDecl *D = (*I)->getUnderlyingDecl();
  8437. // We can have UsingDecls in our Previous results because we use the same
  8438. // LookupResult for checking whether the UsingDecl itself is a valid
  8439. // redeclaration.
  8440. if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
  8441. continue;
  8442. if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  8443. // C++ [class.mem]p19:
  8444. // If T is the name of a class, then [every named member other than
  8445. // a non-static data member] shall have a name different from T
  8446. if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
  8447. !isa<IndirectFieldDecl>(Target) &&
  8448. !isa<UnresolvedUsingValueDecl>(Target) &&
  8449. DiagnoseClassNameShadow(
  8450. CurContext,
  8451. DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
  8452. return true;
  8453. }
  8454. if (IsEquivalentForUsingDecl(Context, D, Target)) {
  8455. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
  8456. PrevShadow = Shadow;
  8457. FoundEquivalentDecl = true;
  8458. } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
  8459. // We don't conflict with an existing using shadow decl of an equivalent
  8460. // declaration, but we're not a redeclaration of it.
  8461. FoundEquivalentDecl = true;
  8462. }
  8463. if (isVisible(D))
  8464. (isa<TagDecl>(D) ? Tag : NonTag) = D;
  8465. }
  8466. if (FoundEquivalentDecl)
  8467. return false;
  8468. if (FunctionDecl *FD = Target->getAsFunction()) {
  8469. NamedDecl *OldDecl = nullptr;
  8470. switch (CheckOverload(nullptr, FD, Previous, OldDecl,
  8471. /*IsForUsingDecl*/ true)) {
  8472. case Ovl_Overload:
  8473. return false;
  8474. case Ovl_NonFunction:
  8475. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8476. break;
  8477. // We found a decl with the exact signature.
  8478. case Ovl_Match:
  8479. // If we're in a record, we want to hide the target, so we
  8480. // return true (without a diagnostic) to tell the caller not to
  8481. // build a shadow decl.
  8482. if (CurContext->isRecord())
  8483. return true;
  8484. // If we're not in a record, this is an error.
  8485. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8486. break;
  8487. }
  8488. Diag(Target->getLocation(), diag::note_using_decl_target);
  8489. Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
  8490. Using->setInvalidDecl();
  8491. return true;
  8492. }
  8493. // Target is not a function.
  8494. if (isa<TagDecl>(Target)) {
  8495. // No conflict between a tag and a non-tag.
  8496. if (!Tag) return false;
  8497. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8498. Diag(Target->getLocation(), diag::note_using_decl_target);
  8499. Diag(Tag->getLocation(), diag::note_using_decl_conflict);
  8500. Using->setInvalidDecl();
  8501. return true;
  8502. }
  8503. // No conflict between a tag and a non-tag.
  8504. if (!NonTag) return false;
  8505. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8506. Diag(Target->getLocation(), diag::note_using_decl_target);
  8507. Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
  8508. Using->setInvalidDecl();
  8509. return true;
  8510. }
  8511. /// Determine whether a direct base class is a virtual base class.
  8512. static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
  8513. if (!Derived->getNumVBases())
  8514. return false;
  8515. for (auto &B : Derived->bases())
  8516. if (B.getType()->getAsCXXRecordDecl() == Base)
  8517. return B.isVirtual();
  8518. llvm_unreachable("not a direct base class");
  8519. }
  8520. /// Builds a shadow declaration corresponding to a 'using' declaration.
  8521. UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
  8522. UsingDecl *UD,
  8523. NamedDecl *Orig,
  8524. UsingShadowDecl *PrevDecl) {
  8525. // If we resolved to another shadow declaration, just coalesce them.
  8526. NamedDecl *Target = Orig;
  8527. if (isa<UsingShadowDecl>(Target)) {
  8528. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  8529. assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
  8530. }
  8531. NamedDecl *NonTemplateTarget = Target;
  8532. if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
  8533. NonTemplateTarget = TargetTD->getTemplatedDecl();
  8534. UsingShadowDecl *Shadow;
  8535. if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
  8536. bool IsVirtualBase =
  8537. isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
  8538. UD->getQualifier()->getAsRecordDecl());
  8539. Shadow = ConstructorUsingShadowDecl::Create(
  8540. Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
  8541. } else {
  8542. Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
  8543. Target);
  8544. }
  8545. UD->addShadowDecl(Shadow);
  8546. Shadow->setAccess(UD->getAccess());
  8547. if (Orig->isInvalidDecl() || UD->isInvalidDecl())
  8548. Shadow->setInvalidDecl();
  8549. Shadow->setPreviousDecl(PrevDecl);
  8550. if (S)
  8551. PushOnScopeChains(Shadow, S);
  8552. else
  8553. CurContext->addDecl(Shadow);
  8554. return Shadow;
  8555. }
  8556. /// Hides a using shadow declaration. This is required by the current
  8557. /// using-decl implementation when a resolvable using declaration in a
  8558. /// class is followed by a declaration which would hide or override
  8559. /// one or more of the using decl's targets; for example:
  8560. ///
  8561. /// struct Base { void foo(int); };
  8562. /// struct Derived : Base {
  8563. /// using Base::foo;
  8564. /// void foo(int);
  8565. /// };
  8566. ///
  8567. /// The governing language is C++03 [namespace.udecl]p12:
  8568. ///
  8569. /// When a using-declaration brings names from a base class into a
  8570. /// derived class scope, member functions in the derived class
  8571. /// override and/or hide member functions with the same name and
  8572. /// parameter types in a base class (rather than conflicting).
  8573. ///
  8574. /// There are two ways to implement this:
  8575. /// (1) optimistically create shadow decls when they're not hidden
  8576. /// by existing declarations, or
  8577. /// (2) don't create any shadow decls (or at least don't make them
  8578. /// visible) until we've fully parsed/instantiated the class.
  8579. /// The problem with (1) is that we might have to retroactively remove
  8580. /// a shadow decl, which requires several O(n) operations because the
  8581. /// decl structures are (very reasonably) not designed for removal.
  8582. /// (2) avoids this but is very fiddly and phase-dependent.
  8583. void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
  8584. if (Shadow->getDeclName().getNameKind() ==
  8585. DeclarationName::CXXConversionFunctionName)
  8586. cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
  8587. // Remove it from the DeclContext...
  8588. Shadow->getDeclContext()->removeDecl(Shadow);
  8589. // ...and the scope, if applicable...
  8590. if (S) {
  8591. S->RemoveDecl(Shadow);
  8592. IdResolver.RemoveDecl(Shadow);
  8593. }
  8594. // ...and the using decl.
  8595. Shadow->getUsingDecl()->removeShadowDecl(Shadow);
  8596. // TODO: complain somehow if Shadow was used. It shouldn't
  8597. // be possible for this to happen, because...?
  8598. }
  8599. /// Find the base specifier for a base class with the given type.
  8600. static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
  8601. QualType DesiredBase,
  8602. bool &AnyDependentBases) {
  8603. // Check whether the named type is a direct base class.
  8604. CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
  8605. for (auto &Base : Derived->bases()) {
  8606. CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
  8607. if (CanonicalDesiredBase == BaseType)
  8608. return &Base;
  8609. if (BaseType->isDependentType())
  8610. AnyDependentBases = true;
  8611. }
  8612. return nullptr;
  8613. }
  8614. namespace {
  8615. class UsingValidatorCCC final : public CorrectionCandidateCallback {
  8616. public:
  8617. UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
  8618. NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
  8619. : HasTypenameKeyword(HasTypenameKeyword),
  8620. IsInstantiation(IsInstantiation), OldNNS(NNS),
  8621. RequireMemberOf(RequireMemberOf) {}
  8622. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  8623. NamedDecl *ND = Candidate.getCorrectionDecl();
  8624. // Keywords are not valid here.
  8625. if (!ND || isa<NamespaceDecl>(ND))
  8626. return false;
  8627. // Completely unqualified names are invalid for a 'using' declaration.
  8628. if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
  8629. return false;
  8630. // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
  8631. // reject.
  8632. if (RequireMemberOf) {
  8633. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  8634. if (FoundRecord && FoundRecord->isInjectedClassName()) {
  8635. // No-one ever wants a using-declaration to name an injected-class-name
  8636. // of a base class, unless they're declaring an inheriting constructor.
  8637. ASTContext &Ctx = ND->getASTContext();
  8638. if (!Ctx.getLangOpts().CPlusPlus11)
  8639. return false;
  8640. QualType FoundType = Ctx.getRecordType(FoundRecord);
  8641. // Check that the injected-class-name is named as a member of its own
  8642. // type; we don't want to suggest 'using Derived::Base;', since that
  8643. // means something else.
  8644. NestedNameSpecifier *Specifier =
  8645. Candidate.WillReplaceSpecifier()
  8646. ? Candidate.getCorrectionSpecifier()
  8647. : OldNNS;
  8648. if (!Specifier->getAsType() ||
  8649. !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
  8650. return false;
  8651. // Check that this inheriting constructor declaration actually names a
  8652. // direct base class of the current class.
  8653. bool AnyDependentBases = false;
  8654. if (!findDirectBaseWithType(RequireMemberOf,
  8655. Ctx.getRecordType(FoundRecord),
  8656. AnyDependentBases) &&
  8657. !AnyDependentBases)
  8658. return false;
  8659. } else {
  8660. auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
  8661. if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
  8662. return false;
  8663. // FIXME: Check that the base class member is accessible?
  8664. }
  8665. } else {
  8666. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  8667. if (FoundRecord && FoundRecord->isInjectedClassName())
  8668. return false;
  8669. }
  8670. if (isa<TypeDecl>(ND))
  8671. return HasTypenameKeyword || !IsInstantiation;
  8672. return !HasTypenameKeyword;
  8673. }
  8674. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  8675. return llvm::make_unique<UsingValidatorCCC>(*this);
  8676. }
  8677. private:
  8678. bool HasTypenameKeyword;
  8679. bool IsInstantiation;
  8680. NestedNameSpecifier *OldNNS;
  8681. CXXRecordDecl *RequireMemberOf;
  8682. };
  8683. } // end anonymous namespace
  8684. /// Builds a using declaration.
  8685. ///
  8686. /// \param IsInstantiation - Whether this call arises from an
  8687. /// instantiation of an unresolved using declaration. We treat
  8688. /// the lookup differently for these declarations.
  8689. NamedDecl *Sema::BuildUsingDeclaration(
  8690. Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
  8691. bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
  8692. DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
  8693. const ParsedAttributesView &AttrList, bool IsInstantiation) {
  8694. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  8695. SourceLocation IdentLoc = NameInfo.getLoc();
  8696. assert(IdentLoc.isValid() && "Invalid TargetName location.");
  8697. // FIXME: We ignore attributes for now.
  8698. // For an inheriting constructor declaration, the name of the using
  8699. // declaration is the name of a constructor in this class, not in the
  8700. // base class.
  8701. DeclarationNameInfo UsingName = NameInfo;
  8702. if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
  8703. if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
  8704. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  8705. Context.getCanonicalType(Context.getRecordType(RD))));
  8706. // Do the redeclaration lookup in the current scope.
  8707. LookupResult Previous(*this, UsingName, LookupUsingDeclName,
  8708. ForVisibleRedeclaration);
  8709. Previous.setHideTags(false);
  8710. if (S) {
  8711. LookupName(Previous, S);
  8712. // It is really dumb that we have to do this.
  8713. LookupResult::Filter F = Previous.makeFilter();
  8714. while (F.hasNext()) {
  8715. NamedDecl *D = F.next();
  8716. if (!isDeclInScope(D, CurContext, S))
  8717. F.erase();
  8718. // If we found a local extern declaration that's not ordinarily visible,
  8719. // and this declaration is being added to a non-block scope, ignore it.
  8720. // We're only checking for scope conflicts here, not also for violations
  8721. // of the linkage rules.
  8722. else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
  8723. !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
  8724. F.erase();
  8725. }
  8726. F.done();
  8727. } else {
  8728. assert(IsInstantiation && "no scope in non-instantiation");
  8729. if (CurContext->isRecord())
  8730. LookupQualifiedName(Previous, CurContext);
  8731. else {
  8732. // No redeclaration check is needed here; in non-member contexts we
  8733. // diagnosed all possible conflicts with other using-declarations when
  8734. // building the template:
  8735. //
  8736. // For a dependent non-type using declaration, the only valid case is
  8737. // if we instantiate to a single enumerator. We check for conflicts
  8738. // between shadow declarations we introduce, and we check in the template
  8739. // definition for conflicts between a non-type using declaration and any
  8740. // other declaration, which together covers all cases.
  8741. //
  8742. // A dependent typename using declaration will never successfully
  8743. // instantiate, since it will always name a class member, so we reject
  8744. // that in the template definition.
  8745. }
  8746. }
  8747. // Check for invalid redeclarations.
  8748. if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
  8749. SS, IdentLoc, Previous))
  8750. return nullptr;
  8751. // Check for bad qualifiers.
  8752. if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
  8753. IdentLoc))
  8754. return nullptr;
  8755. DeclContext *LookupContext = computeDeclContext(SS);
  8756. NamedDecl *D;
  8757. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  8758. if (!LookupContext || EllipsisLoc.isValid()) {
  8759. if (HasTypenameKeyword) {
  8760. // FIXME: not all declaration name kinds are legal here
  8761. D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
  8762. UsingLoc, TypenameLoc,
  8763. QualifierLoc,
  8764. IdentLoc, NameInfo.getName(),
  8765. EllipsisLoc);
  8766. } else {
  8767. D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
  8768. QualifierLoc, NameInfo, EllipsisLoc);
  8769. }
  8770. D->setAccess(AS);
  8771. CurContext->addDecl(D);
  8772. return D;
  8773. }
  8774. auto Build = [&](bool Invalid) {
  8775. UsingDecl *UD =
  8776. UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
  8777. UsingName, HasTypenameKeyword);
  8778. UD->setAccess(AS);
  8779. CurContext->addDecl(UD);
  8780. UD->setInvalidDecl(Invalid);
  8781. return UD;
  8782. };
  8783. auto BuildInvalid = [&]{ return Build(true); };
  8784. auto BuildValid = [&]{ return Build(false); };
  8785. if (RequireCompleteDeclContext(SS, LookupContext))
  8786. return BuildInvalid();
  8787. // Look up the target name.
  8788. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  8789. // Unlike most lookups, we don't always want to hide tag
  8790. // declarations: tag names are visible through the using declaration
  8791. // even if hidden by ordinary names, *except* in a dependent context
  8792. // where it's important for the sanity of two-phase lookup.
  8793. if (!IsInstantiation)
  8794. R.setHideTags(false);
  8795. // For the purposes of this lookup, we have a base object type
  8796. // equal to that of the current context.
  8797. if (CurContext->isRecord()) {
  8798. R.setBaseObjectType(
  8799. Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
  8800. }
  8801. LookupQualifiedName(R, LookupContext);
  8802. // Try to correct typos if possible. If constructor name lookup finds no
  8803. // results, that means the named class has no explicit constructors, and we
  8804. // suppressed declaring implicit ones (probably because it's dependent or
  8805. // invalid).
  8806. if (R.empty() &&
  8807. NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
  8808. // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
  8809. // it will believe that glibc provides a ::gets in cases where it does not,
  8810. // and will try to pull it into namespace std with a using-declaration.
  8811. // Just ignore the using-declaration in that case.
  8812. auto *II = NameInfo.getName().getAsIdentifierInfo();
  8813. if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
  8814. CurContext->isStdNamespace() &&
  8815. isa<TranslationUnitDecl>(LookupContext) &&
  8816. getSourceManager().isInSystemHeader(UsingLoc))
  8817. return nullptr;
  8818. UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
  8819. dyn_cast<CXXRecordDecl>(CurContext));
  8820. if (TypoCorrection Corrected =
  8821. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
  8822. CTK_ErrorRecovery)) {
  8823. // We reject candidates where DroppedSpecifier == true, hence the
  8824. // literal '0' below.
  8825. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  8826. << NameInfo.getName() << LookupContext << 0
  8827. << SS.getRange());
  8828. // If we picked a correction with no attached Decl we can't do anything
  8829. // useful with it, bail out.
  8830. NamedDecl *ND = Corrected.getCorrectionDecl();
  8831. if (!ND)
  8832. return BuildInvalid();
  8833. // If we corrected to an inheriting constructor, handle it as one.
  8834. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  8835. if (RD && RD->isInjectedClassName()) {
  8836. // The parent of the injected class name is the class itself.
  8837. RD = cast<CXXRecordDecl>(RD->getParent());
  8838. // Fix up the information we'll use to build the using declaration.
  8839. if (Corrected.WillReplaceSpecifier()) {
  8840. NestedNameSpecifierLocBuilder Builder;
  8841. Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  8842. QualifierLoc.getSourceRange());
  8843. QualifierLoc = Builder.getWithLocInContext(Context);
  8844. }
  8845. // In this case, the name we introduce is the name of a derived class
  8846. // constructor.
  8847. auto *CurClass = cast<CXXRecordDecl>(CurContext);
  8848. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  8849. Context.getCanonicalType(Context.getRecordType(CurClass))));
  8850. UsingName.setNamedTypeInfo(nullptr);
  8851. for (auto *Ctor : LookupConstructors(RD))
  8852. R.addDecl(Ctor);
  8853. R.resolveKind();
  8854. } else {
  8855. // FIXME: Pick up all the declarations if we found an overloaded
  8856. // function.
  8857. UsingName.setName(ND->getDeclName());
  8858. R.addDecl(ND);
  8859. }
  8860. } else {
  8861. Diag(IdentLoc, diag::err_no_member)
  8862. << NameInfo.getName() << LookupContext << SS.getRange();
  8863. return BuildInvalid();
  8864. }
  8865. }
  8866. if (R.isAmbiguous())
  8867. return BuildInvalid();
  8868. if (HasTypenameKeyword) {
  8869. // If we asked for a typename and got a non-type decl, error out.
  8870. if (!R.getAsSingle<TypeDecl>()) {
  8871. Diag(IdentLoc, diag::err_using_typename_non_type);
  8872. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  8873. Diag((*I)->getUnderlyingDecl()->getLocation(),
  8874. diag::note_using_decl_target);
  8875. return BuildInvalid();
  8876. }
  8877. } else {
  8878. // If we asked for a non-typename and we got a type, error out,
  8879. // but only if this is an instantiation of an unresolved using
  8880. // decl. Otherwise just silently find the type name.
  8881. if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
  8882. Diag(IdentLoc, diag::err_using_dependent_value_is_type);
  8883. Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
  8884. return BuildInvalid();
  8885. }
  8886. }
  8887. // C++14 [namespace.udecl]p6:
  8888. // A using-declaration shall not name a namespace.
  8889. if (R.getAsSingle<NamespaceDecl>()) {
  8890. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
  8891. << SS.getRange();
  8892. return BuildInvalid();
  8893. }
  8894. // C++14 [namespace.udecl]p7:
  8895. // A using-declaration shall not name a scoped enumerator.
  8896. if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
  8897. if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
  8898. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
  8899. << SS.getRange();
  8900. return BuildInvalid();
  8901. }
  8902. }
  8903. UsingDecl *UD = BuildValid();
  8904. // Some additional rules apply to inheriting constructors.
  8905. if (UsingName.getName().getNameKind() ==
  8906. DeclarationName::CXXConstructorName) {
  8907. // Suppress access diagnostics; the access check is instead performed at the
  8908. // point of use for an inheriting constructor.
  8909. R.suppressDiagnostics();
  8910. if (CheckInheritingConstructorUsingDecl(UD))
  8911. return UD;
  8912. }
  8913. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  8914. UsingShadowDecl *PrevDecl = nullptr;
  8915. if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
  8916. BuildUsingShadowDecl(S, UD, *I, PrevDecl);
  8917. }
  8918. return UD;
  8919. }
  8920. NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
  8921. ArrayRef<NamedDecl *> Expansions) {
  8922. assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
  8923. isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
  8924. isa<UsingPackDecl>(InstantiatedFrom));
  8925. auto *UPD =
  8926. UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
  8927. UPD->setAccess(InstantiatedFrom->getAccess());
  8928. CurContext->addDecl(UPD);
  8929. return UPD;
  8930. }
  8931. /// Additional checks for a using declaration referring to a constructor name.
  8932. bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
  8933. assert(!UD->hasTypename() && "expecting a constructor name");
  8934. const Type *SourceType = UD->getQualifier()->getAsType();
  8935. assert(SourceType &&
  8936. "Using decl naming constructor doesn't have type in scope spec.");
  8937. CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
  8938. // Check whether the named type is a direct base class.
  8939. bool AnyDependentBases = false;
  8940. auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
  8941. AnyDependentBases);
  8942. if (!Base && !AnyDependentBases) {
  8943. Diag(UD->getUsingLoc(),
  8944. diag::err_using_decl_constructor_not_in_direct_base)
  8945. << UD->getNameInfo().getSourceRange()
  8946. << QualType(SourceType, 0) << TargetClass;
  8947. UD->setInvalidDecl();
  8948. return true;
  8949. }
  8950. if (Base)
  8951. Base->setInheritConstructors();
  8952. return false;
  8953. }
  8954. /// Checks that the given using declaration is not an invalid
  8955. /// redeclaration. Note that this is checking only for the using decl
  8956. /// itself, not for any ill-formedness among the UsingShadowDecls.
  8957. bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
  8958. bool HasTypenameKeyword,
  8959. const CXXScopeSpec &SS,
  8960. SourceLocation NameLoc,
  8961. const LookupResult &Prev) {
  8962. NestedNameSpecifier *Qual = SS.getScopeRep();
  8963. // C++03 [namespace.udecl]p8:
  8964. // C++0x [namespace.udecl]p10:
  8965. // A using-declaration is a declaration and can therefore be used
  8966. // repeatedly where (and only where) multiple declarations are
  8967. // allowed.
  8968. //
  8969. // That's in non-member contexts.
  8970. if (!CurContext->getRedeclContext()->isRecord()) {
  8971. // A dependent qualifier outside a class can only ever resolve to an
  8972. // enumeration type. Therefore it conflicts with any other non-type
  8973. // declaration in the same scope.
  8974. // FIXME: How should we check for dependent type-type conflicts at block
  8975. // scope?
  8976. if (Qual->isDependent() && !HasTypenameKeyword) {
  8977. for (auto *D : Prev) {
  8978. if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
  8979. bool OldCouldBeEnumerator =
  8980. isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
  8981. Diag(NameLoc,
  8982. OldCouldBeEnumerator ? diag::err_redefinition
  8983. : diag::err_redefinition_different_kind)
  8984. << Prev.getLookupName();
  8985. Diag(D->getLocation(), diag::note_previous_definition);
  8986. return true;
  8987. }
  8988. }
  8989. }
  8990. return false;
  8991. }
  8992. for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
  8993. NamedDecl *D = *I;
  8994. bool DTypename;
  8995. NestedNameSpecifier *DQual;
  8996. if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
  8997. DTypename = UD->hasTypename();
  8998. DQual = UD->getQualifier();
  8999. } else if (UnresolvedUsingValueDecl *UD
  9000. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  9001. DTypename = false;
  9002. DQual = UD->getQualifier();
  9003. } else if (UnresolvedUsingTypenameDecl *UD
  9004. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  9005. DTypename = true;
  9006. DQual = UD->getQualifier();
  9007. } else continue;
  9008. // using decls differ if one says 'typename' and the other doesn't.
  9009. // FIXME: non-dependent using decls?
  9010. if (HasTypenameKeyword != DTypename) continue;
  9011. // using decls differ if they name different scopes (but note that
  9012. // template instantiation can cause this check to trigger when it
  9013. // didn't before instantiation).
  9014. if (Context.getCanonicalNestedNameSpecifier(Qual) !=
  9015. Context.getCanonicalNestedNameSpecifier(DQual))
  9016. continue;
  9017. Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
  9018. Diag(D->getLocation(), diag::note_using_decl) << 1;
  9019. return true;
  9020. }
  9021. return false;
  9022. }
  9023. /// Checks that the given nested-name qualifier used in a using decl
  9024. /// in the current context is appropriately related to the current
  9025. /// scope. If an error is found, diagnoses it and returns true.
  9026. bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
  9027. bool HasTypename,
  9028. const CXXScopeSpec &SS,
  9029. const DeclarationNameInfo &NameInfo,
  9030. SourceLocation NameLoc) {
  9031. DeclContext *NamedContext = computeDeclContext(SS);
  9032. if (!CurContext->isRecord()) {
  9033. // C++03 [namespace.udecl]p3:
  9034. // C++0x [namespace.udecl]p8:
  9035. // A using-declaration for a class member shall be a member-declaration.
  9036. // If we weren't able to compute a valid scope, it might validly be a
  9037. // dependent class scope or a dependent enumeration unscoped scope. If
  9038. // we have a 'typename' keyword, the scope must resolve to a class type.
  9039. if ((HasTypename && !NamedContext) ||
  9040. (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
  9041. auto *RD = NamedContext
  9042. ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
  9043. : nullptr;
  9044. if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
  9045. RD = nullptr;
  9046. Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
  9047. << SS.getRange();
  9048. // If we have a complete, non-dependent source type, try to suggest a
  9049. // way to get the same effect.
  9050. if (!RD)
  9051. return true;
  9052. // Find what this using-declaration was referring to.
  9053. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  9054. R.setHideTags(false);
  9055. R.suppressDiagnostics();
  9056. LookupQualifiedName(R, RD);
  9057. if (R.getAsSingle<TypeDecl>()) {
  9058. if (getLangOpts().CPlusPlus11) {
  9059. // Convert 'using X::Y;' to 'using Y = X::Y;'.
  9060. Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
  9061. << 0 // alias declaration
  9062. << FixItHint::CreateInsertion(SS.getBeginLoc(),
  9063. NameInfo.getName().getAsString() +
  9064. " = ");
  9065. } else {
  9066. // Convert 'using X::Y;' to 'typedef X::Y Y;'.
  9067. SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
  9068. Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
  9069. << 1 // typedef declaration
  9070. << FixItHint::CreateReplacement(UsingLoc, "typedef")
  9071. << FixItHint::CreateInsertion(
  9072. InsertLoc, " " + NameInfo.getName().getAsString());
  9073. }
  9074. } else if (R.getAsSingle<VarDecl>()) {
  9075. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  9076. // repeating the type of the static data member here.
  9077. FixItHint FixIt;
  9078. if (getLangOpts().CPlusPlus11) {
  9079. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  9080. FixIt = FixItHint::CreateReplacement(
  9081. UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
  9082. }
  9083. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  9084. << 2 // reference declaration
  9085. << FixIt;
  9086. } else if (R.getAsSingle<EnumConstantDecl>()) {
  9087. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  9088. // repeating the type of the enumeration here, and we can't do so if
  9089. // the type is anonymous.
  9090. FixItHint FixIt;
  9091. if (getLangOpts().CPlusPlus11) {
  9092. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  9093. FixIt = FixItHint::CreateReplacement(
  9094. UsingLoc,
  9095. "constexpr auto " + NameInfo.getName().getAsString() + " = ");
  9096. }
  9097. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  9098. << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
  9099. << FixIt;
  9100. }
  9101. return true;
  9102. }
  9103. // Otherwise, this might be valid.
  9104. return false;
  9105. }
  9106. // The current scope is a record.
  9107. // If the named context is dependent, we can't decide much.
  9108. if (!NamedContext) {
  9109. // FIXME: in C++0x, we can diagnose if we can prove that the
  9110. // nested-name-specifier does not refer to a base class, which is
  9111. // still possible in some cases.
  9112. // Otherwise we have to conservatively report that things might be
  9113. // okay.
  9114. return false;
  9115. }
  9116. if (!NamedContext->isRecord()) {
  9117. // Ideally this would point at the last name in the specifier,
  9118. // but we don't have that level of source info.
  9119. Diag(SS.getRange().getBegin(),
  9120. diag::err_using_decl_nested_name_specifier_is_not_class)
  9121. << SS.getScopeRep() << SS.getRange();
  9122. return true;
  9123. }
  9124. if (!NamedContext->isDependentContext() &&
  9125. RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
  9126. return true;
  9127. if (getLangOpts().CPlusPlus11) {
  9128. // C++11 [namespace.udecl]p3:
  9129. // In a using-declaration used as a member-declaration, the
  9130. // nested-name-specifier shall name a base class of the class
  9131. // being defined.
  9132. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
  9133. cast<CXXRecordDecl>(NamedContext))) {
  9134. if (CurContext == NamedContext) {
  9135. Diag(NameLoc,
  9136. diag::err_using_decl_nested_name_specifier_is_current_class)
  9137. << SS.getRange();
  9138. return true;
  9139. }
  9140. if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
  9141. Diag(SS.getRange().getBegin(),
  9142. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  9143. << SS.getScopeRep()
  9144. << cast<CXXRecordDecl>(CurContext)
  9145. << SS.getRange();
  9146. }
  9147. return true;
  9148. }
  9149. return false;
  9150. }
  9151. // C++03 [namespace.udecl]p4:
  9152. // A using-declaration used as a member-declaration shall refer
  9153. // to a member of a base class of the class being defined [etc.].
  9154. // Salient point: SS doesn't have to name a base class as long as
  9155. // lookup only finds members from base classes. Therefore we can
  9156. // diagnose here only if we can prove that that can't happen,
  9157. // i.e. if the class hierarchies provably don't intersect.
  9158. // TODO: it would be nice if "definitely valid" results were cached
  9159. // in the UsingDecl and UsingShadowDecl so that these checks didn't
  9160. // need to be repeated.
  9161. llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
  9162. auto Collect = [&Bases](const CXXRecordDecl *Base) {
  9163. Bases.insert(Base);
  9164. return true;
  9165. };
  9166. // Collect all bases. Return false if we find a dependent base.
  9167. if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
  9168. return false;
  9169. // Returns true if the base is dependent or is one of the accumulated base
  9170. // classes.
  9171. auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
  9172. return !Bases.count(Base);
  9173. };
  9174. // Return false if the class has a dependent base or if it or one
  9175. // of its bases is present in the base set of the current context.
  9176. if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
  9177. !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
  9178. return false;
  9179. Diag(SS.getRange().getBegin(),
  9180. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  9181. << SS.getScopeRep()
  9182. << cast<CXXRecordDecl>(CurContext)
  9183. << SS.getRange();
  9184. return true;
  9185. }
  9186. Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
  9187. MultiTemplateParamsArg TemplateParamLists,
  9188. SourceLocation UsingLoc, UnqualifiedId &Name,
  9189. const ParsedAttributesView &AttrList,
  9190. TypeResult Type, Decl *DeclFromDeclSpec) {
  9191. // Skip up to the relevant declaration scope.
  9192. while (S->isTemplateParamScope())
  9193. S = S->getParent();
  9194. assert((S->getFlags() & Scope::DeclScope) &&
  9195. "got alias-declaration outside of declaration scope");
  9196. if (Type.isInvalid())
  9197. return nullptr;
  9198. bool Invalid = false;
  9199. DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
  9200. TypeSourceInfo *TInfo = nullptr;
  9201. GetTypeFromParser(Type.get(), &TInfo);
  9202. if (DiagnoseClassNameShadow(CurContext, NameInfo))
  9203. return nullptr;
  9204. if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
  9205. UPPC_DeclarationType)) {
  9206. Invalid = true;
  9207. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  9208. TInfo->getTypeLoc().getBeginLoc());
  9209. }
  9210. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  9211. TemplateParamLists.size()
  9212. ? forRedeclarationInCurContext()
  9213. : ForVisibleRedeclaration);
  9214. LookupName(Previous, S);
  9215. // Warn about shadowing the name of a template parameter.
  9216. if (Previous.isSingleResult() &&
  9217. Previous.getFoundDecl()->isTemplateParameter()) {
  9218. DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
  9219. Previous.clear();
  9220. }
  9221. assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
  9222. "name in alias declaration must be an identifier");
  9223. TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
  9224. Name.StartLocation,
  9225. Name.Identifier, TInfo);
  9226. NewTD->setAccess(AS);
  9227. if (Invalid)
  9228. NewTD->setInvalidDecl();
  9229. ProcessDeclAttributeList(S, NewTD, AttrList);
  9230. AddPragmaAttributes(S, NewTD);
  9231. CheckTypedefForVariablyModifiedType(S, NewTD);
  9232. Invalid |= NewTD->isInvalidDecl();
  9233. bool Redeclaration = false;
  9234. NamedDecl *NewND;
  9235. if (TemplateParamLists.size()) {
  9236. TypeAliasTemplateDecl *OldDecl = nullptr;
  9237. TemplateParameterList *OldTemplateParams = nullptr;
  9238. if (TemplateParamLists.size() != 1) {
  9239. Diag(UsingLoc, diag::err_alias_template_extra_headers)
  9240. << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
  9241. TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
  9242. }
  9243. TemplateParameterList *TemplateParams = TemplateParamLists[0];
  9244. // Check that we can declare a template here.
  9245. if (CheckTemplateDeclScope(S, TemplateParams))
  9246. return nullptr;
  9247. // Only consider previous declarations in the same scope.
  9248. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
  9249. /*ExplicitInstantiationOrSpecialization*/false);
  9250. if (!Previous.empty()) {
  9251. Redeclaration = true;
  9252. OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
  9253. if (!OldDecl && !Invalid) {
  9254. Diag(UsingLoc, diag::err_redefinition_different_kind)
  9255. << Name.Identifier;
  9256. NamedDecl *OldD = Previous.getRepresentativeDecl();
  9257. if (OldD->getLocation().isValid())
  9258. Diag(OldD->getLocation(), diag::note_previous_definition);
  9259. Invalid = true;
  9260. }
  9261. if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
  9262. if (TemplateParameterListsAreEqual(TemplateParams,
  9263. OldDecl->getTemplateParameters(),
  9264. /*Complain=*/true,
  9265. TPL_TemplateMatch))
  9266. OldTemplateParams =
  9267. OldDecl->getMostRecentDecl()->getTemplateParameters();
  9268. else
  9269. Invalid = true;
  9270. TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
  9271. if (!Invalid &&
  9272. !Context.hasSameType(OldTD->getUnderlyingType(),
  9273. NewTD->getUnderlyingType())) {
  9274. // FIXME: The C++0x standard does not clearly say this is ill-formed,
  9275. // but we can't reasonably accept it.
  9276. Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
  9277. << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
  9278. if (OldTD->getLocation().isValid())
  9279. Diag(OldTD->getLocation(), diag::note_previous_definition);
  9280. Invalid = true;
  9281. }
  9282. }
  9283. }
  9284. // Merge any previous default template arguments into our parameters,
  9285. // and check the parameter list.
  9286. if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
  9287. TPC_TypeAliasTemplate))
  9288. return nullptr;
  9289. TypeAliasTemplateDecl *NewDecl =
  9290. TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
  9291. Name.Identifier, TemplateParams,
  9292. NewTD);
  9293. NewTD->setDescribedAliasTemplate(NewDecl);
  9294. NewDecl->setAccess(AS);
  9295. if (Invalid)
  9296. NewDecl->setInvalidDecl();
  9297. else if (OldDecl) {
  9298. NewDecl->setPreviousDecl(OldDecl);
  9299. CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
  9300. }
  9301. NewND = NewDecl;
  9302. } else {
  9303. if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
  9304. setTagNameForLinkagePurposes(TD, NewTD);
  9305. handleTagNumbering(TD, S);
  9306. }
  9307. ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
  9308. NewND = NewTD;
  9309. }
  9310. PushOnScopeChains(NewND, S);
  9311. ActOnDocumentableDecl(NewND);
  9312. return NewND;
  9313. }
  9314. Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
  9315. SourceLocation AliasLoc,
  9316. IdentifierInfo *Alias, CXXScopeSpec &SS,
  9317. SourceLocation IdentLoc,
  9318. IdentifierInfo *Ident) {
  9319. // Lookup the namespace name.
  9320. LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
  9321. LookupParsedName(R, S, &SS);
  9322. if (R.isAmbiguous())
  9323. return nullptr;
  9324. if (R.empty()) {
  9325. if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
  9326. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  9327. return nullptr;
  9328. }
  9329. }
  9330. assert(!R.isAmbiguous() && !R.empty());
  9331. NamedDecl *ND = R.getRepresentativeDecl();
  9332. // Check if we have a previous declaration with the same name.
  9333. LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
  9334. ForVisibleRedeclaration);
  9335. LookupName(PrevR, S);
  9336. // Check we're not shadowing a template parameter.
  9337. if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
  9338. DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
  9339. PrevR.clear();
  9340. }
  9341. // Filter out any other lookup result from an enclosing scope.
  9342. FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
  9343. /*AllowInlineNamespace*/false);
  9344. // Find the previous declaration and check that we can redeclare it.
  9345. NamespaceAliasDecl *Prev = nullptr;
  9346. if (PrevR.isSingleResult()) {
  9347. NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
  9348. if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
  9349. // We already have an alias with the same name that points to the same
  9350. // namespace; check that it matches.
  9351. if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
  9352. Prev = AD;
  9353. } else if (isVisible(PrevDecl)) {
  9354. Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
  9355. << Alias;
  9356. Diag(AD->getLocation(), diag::note_previous_namespace_alias)
  9357. << AD->getNamespace();
  9358. return nullptr;
  9359. }
  9360. } else if (isVisible(PrevDecl)) {
  9361. unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
  9362. ? diag::err_redefinition
  9363. : diag::err_redefinition_different_kind;
  9364. Diag(AliasLoc, DiagID) << Alias;
  9365. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  9366. return nullptr;
  9367. }
  9368. }
  9369. // The use of a nested name specifier may trigger deprecation warnings.
  9370. DiagnoseUseOfDecl(ND, IdentLoc);
  9371. NamespaceAliasDecl *AliasDecl =
  9372. NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
  9373. Alias, SS.getWithLocInContext(Context),
  9374. IdentLoc, ND);
  9375. if (Prev)
  9376. AliasDecl->setPreviousDecl(Prev);
  9377. PushOnScopeChains(AliasDecl, S);
  9378. return AliasDecl;
  9379. }
  9380. namespace {
  9381. struct SpecialMemberExceptionSpecInfo
  9382. : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
  9383. SourceLocation Loc;
  9384. Sema::ImplicitExceptionSpecification ExceptSpec;
  9385. SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
  9386. Sema::CXXSpecialMember CSM,
  9387. Sema::InheritedConstructorInfo *ICI,
  9388. SourceLocation Loc)
  9389. : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
  9390. bool visitBase(CXXBaseSpecifier *Base);
  9391. bool visitField(FieldDecl *FD);
  9392. void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  9393. unsigned Quals);
  9394. void visitSubobjectCall(Subobject Subobj,
  9395. Sema::SpecialMemberOverloadResult SMOR);
  9396. };
  9397. }
  9398. bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
  9399. auto *RT = Base->getType()->getAs<RecordType>();
  9400. if (!RT)
  9401. return false;
  9402. auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
  9403. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  9404. if (auto *BaseCtor = SMOR.getMethod()) {
  9405. visitSubobjectCall(Base, BaseCtor);
  9406. return false;
  9407. }
  9408. visitClassSubobject(BaseClass, Base, 0);
  9409. return false;
  9410. }
  9411. bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
  9412. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
  9413. Expr *E = FD->getInClassInitializer();
  9414. if (!E)
  9415. // FIXME: It's a little wasteful to build and throw away a
  9416. // CXXDefaultInitExpr here.
  9417. // FIXME: We should have a single context note pointing at Loc, and
  9418. // this location should be MD->getLocation() instead, since that's
  9419. // the location where we actually use the default init expression.
  9420. E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
  9421. if (E)
  9422. ExceptSpec.CalledExpr(E);
  9423. } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
  9424. ->getAs<RecordType>()) {
  9425. visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
  9426. FD->getType().getCVRQualifiers());
  9427. }
  9428. return false;
  9429. }
  9430. void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
  9431. Subobject Subobj,
  9432. unsigned Quals) {
  9433. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  9434. bool IsMutable = Field && Field->isMutable();
  9435. visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
  9436. }
  9437. void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
  9438. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
  9439. // Note, if lookup fails, it doesn't matter what exception specification we
  9440. // choose because the special member will be deleted.
  9441. if (CXXMethodDecl *MD = SMOR.getMethod())
  9442. ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
  9443. }
  9444. namespace {
  9445. /// RAII object to register a special member as being currently declared.
  9446. struct ComputingExceptionSpec {
  9447. Sema &S;
  9448. ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
  9449. : S(S) {
  9450. Sema::CodeSynthesisContext Ctx;
  9451. Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
  9452. Ctx.PointOfInstantiation = Loc;
  9453. Ctx.Entity = MD;
  9454. S.pushCodeSynthesisContext(Ctx);
  9455. }
  9456. ~ComputingExceptionSpec() {
  9457. S.popCodeSynthesisContext();
  9458. }
  9459. };
  9460. }
  9461. bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
  9462. llvm::APSInt Result;
  9463. ExprResult Converted = CheckConvertedConstantExpression(
  9464. ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
  9465. ExplicitSpec.setExpr(Converted.get());
  9466. if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
  9467. ExplicitSpec.setKind(Result.getBoolValue()
  9468. ? ExplicitSpecKind::ResolvedTrue
  9469. : ExplicitSpecKind::ResolvedFalse);
  9470. return true;
  9471. }
  9472. ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
  9473. return false;
  9474. }
  9475. ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
  9476. ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
  9477. if (!ExplicitExpr->isTypeDependent())
  9478. tryResolveExplicitSpecifier(ES);
  9479. return ES;
  9480. }
  9481. static Sema::ImplicitExceptionSpecification
  9482. ComputeDefaultedSpecialMemberExceptionSpec(
  9483. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  9484. Sema::InheritedConstructorInfo *ICI) {
  9485. ComputingExceptionSpec CES(S, MD, Loc);
  9486. CXXRecordDecl *ClassDecl = MD->getParent();
  9487. // C++ [except.spec]p14:
  9488. // An implicitly declared special member function (Clause 12) shall have an
  9489. // exception-specification. [...]
  9490. SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
  9491. if (ClassDecl->isInvalidDecl())
  9492. return Info.ExceptSpec;
  9493. // FIXME: If this diagnostic fires, we're probably missing a check for
  9494. // attempting to resolve an exception specification before it's known
  9495. // at a higher level.
  9496. if (S.RequireCompleteType(MD->getLocation(),
  9497. S.Context.getRecordType(ClassDecl),
  9498. diag::err_exception_spec_incomplete_type))
  9499. return Info.ExceptSpec;
  9500. // C++1z [except.spec]p7:
  9501. // [Look for exceptions thrown by] a constructor selected [...] to
  9502. // initialize a potentially constructed subobject,
  9503. // C++1z [except.spec]p8:
  9504. // The exception specification for an implicitly-declared destructor, or a
  9505. // destructor without a noexcept-specifier, is potentially-throwing if and
  9506. // only if any of the destructors for any of its potentially constructed
  9507. // subojects is potentially throwing.
  9508. // FIXME: We respect the first rule but ignore the "potentially constructed"
  9509. // in the second rule to resolve a core issue (no number yet) that would have
  9510. // us reject:
  9511. // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
  9512. // struct B : A {};
  9513. // struct C : B { void f(); };
  9514. // ... due to giving B::~B() a non-throwing exception specification.
  9515. Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
  9516. : Info.VisitAllBases);
  9517. return Info.ExceptSpec;
  9518. }
  9519. namespace {
  9520. /// RAII object to register a special member as being currently declared.
  9521. struct DeclaringSpecialMember {
  9522. Sema &S;
  9523. Sema::SpecialMemberDecl D;
  9524. Sema::ContextRAII SavedContext;
  9525. bool WasAlreadyBeingDeclared;
  9526. DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
  9527. : S(S), D(RD, CSM), SavedContext(S, RD) {
  9528. WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
  9529. if (WasAlreadyBeingDeclared)
  9530. // This almost never happens, but if it does, ensure that our cache
  9531. // doesn't contain a stale result.
  9532. S.SpecialMemberCache.clear();
  9533. else {
  9534. // Register a note to be produced if we encounter an error while
  9535. // declaring the special member.
  9536. Sema::CodeSynthesisContext Ctx;
  9537. Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
  9538. // FIXME: We don't have a location to use here. Using the class's
  9539. // location maintains the fiction that we declare all special members
  9540. // with the class, but (1) it's not clear that lying about that helps our
  9541. // users understand what's going on, and (2) there may be outer contexts
  9542. // on the stack (some of which are relevant) and printing them exposes
  9543. // our lies.
  9544. Ctx.PointOfInstantiation = RD->getLocation();
  9545. Ctx.Entity = RD;
  9546. Ctx.SpecialMember = CSM;
  9547. S.pushCodeSynthesisContext(Ctx);
  9548. }
  9549. }
  9550. ~DeclaringSpecialMember() {
  9551. if (!WasAlreadyBeingDeclared) {
  9552. S.SpecialMembersBeingDeclared.erase(D);
  9553. S.popCodeSynthesisContext();
  9554. }
  9555. }
  9556. /// Are we already trying to declare this special member?
  9557. bool isAlreadyBeingDeclared() const {
  9558. return WasAlreadyBeingDeclared;
  9559. }
  9560. };
  9561. }
  9562. void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
  9563. // Look up any existing declarations, but don't trigger declaration of all
  9564. // implicit special members with this name.
  9565. DeclarationName Name = FD->getDeclName();
  9566. LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
  9567. ForExternalRedeclaration);
  9568. for (auto *D : FD->getParent()->lookup(Name))
  9569. if (auto *Acceptable = R.getAcceptableDecl(D))
  9570. R.addDecl(Acceptable);
  9571. R.resolveKind();
  9572. R.suppressDiagnostics();
  9573. CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
  9574. }
  9575. void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
  9576. QualType ResultTy,
  9577. ArrayRef<QualType> Args) {
  9578. // Build an exception specification pointing back at this constructor.
  9579. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
  9580. if (getLangOpts().OpenCLCPlusPlus) {
  9581. // OpenCL: Implicitly defaulted special member are of the generic address
  9582. // space.
  9583. EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
  9584. }
  9585. auto QT = Context.getFunctionType(ResultTy, Args, EPI);
  9586. SpecialMem->setType(QT);
  9587. }
  9588. CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
  9589. CXXRecordDecl *ClassDecl) {
  9590. // C++ [class.ctor]p5:
  9591. // A default constructor for a class X is a constructor of class X
  9592. // that can be called without an argument. If there is no
  9593. // user-declared constructor for class X, a default constructor is
  9594. // implicitly declared. An implicitly-declared default constructor
  9595. // is an inline public member of its class.
  9596. assert(ClassDecl->needsImplicitDefaultConstructor() &&
  9597. "Should not build implicit default constructor!");
  9598. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
  9599. if (DSM.isAlreadyBeingDeclared())
  9600. return nullptr;
  9601. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  9602. CXXDefaultConstructor,
  9603. false);
  9604. // Create the actual constructor declaration.
  9605. CanQualType ClassType
  9606. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  9607. SourceLocation ClassLoc = ClassDecl->getLocation();
  9608. DeclarationName Name
  9609. = Context.DeclarationNames.getCXXConstructorName(ClassType);
  9610. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9611. CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
  9612. Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
  9613. /*TInfo=*/nullptr, ExplicitSpecifier(),
  9614. /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  9615. Constexpr ? CSK_constexpr : CSK_unspecified);
  9616. DefaultCon->setAccess(AS_public);
  9617. DefaultCon->setDefaulted();
  9618. if (getLangOpts().CUDA) {
  9619. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
  9620. DefaultCon,
  9621. /* ConstRHS */ false,
  9622. /* Diagnose */ false);
  9623. }
  9624. setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
  9625. // We don't need to use SpecialMemberIsTrivial here; triviality for default
  9626. // constructors is easy to compute.
  9627. DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
  9628. // Note that we have declared this constructor.
  9629. ++getASTContext().NumImplicitDefaultConstructorsDeclared;
  9630. Scope *S = getScopeForContext(ClassDecl);
  9631. CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
  9632. if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
  9633. SetDeclDeleted(DefaultCon, ClassLoc);
  9634. if (S)
  9635. PushOnScopeChains(DefaultCon, S, false);
  9636. ClassDecl->addDecl(DefaultCon);
  9637. return DefaultCon;
  9638. }
  9639. void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
  9640. CXXConstructorDecl *Constructor) {
  9641. assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  9642. !Constructor->doesThisDeclarationHaveABody() &&
  9643. !Constructor->isDeleted()) &&
  9644. "DefineImplicitDefaultConstructor - call it for implicit default ctor");
  9645. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  9646. return;
  9647. CXXRecordDecl *ClassDecl = Constructor->getParent();
  9648. assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
  9649. SynthesizedFunctionScope Scope(*this, Constructor);
  9650. // The exception specification is needed because we are defining the
  9651. // function.
  9652. ResolveExceptionSpec(CurrentLocation,
  9653. Constructor->getType()->castAs<FunctionProtoType>());
  9654. MarkVTableUsed(CurrentLocation, ClassDecl);
  9655. // Add a context note for diagnostics produced after this point.
  9656. Scope.addContextNote(CurrentLocation);
  9657. if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
  9658. Constructor->setInvalidDecl();
  9659. return;
  9660. }
  9661. SourceLocation Loc = Constructor->getEndLoc().isValid()
  9662. ? Constructor->getEndLoc()
  9663. : Constructor->getLocation();
  9664. Constructor->setBody(new (Context) CompoundStmt(Loc));
  9665. Constructor->markUsed(Context);
  9666. if (ASTMutationListener *L = getASTMutationListener()) {
  9667. L->CompletedImplicitDefinition(Constructor);
  9668. }
  9669. DiagnoseUninitializedFields(*this, Constructor);
  9670. }
  9671. void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
  9672. // Perform any delayed checks on exception specifications.
  9673. CheckDelayedMemberExceptionSpecs();
  9674. }
  9675. /// Find or create the fake constructor we synthesize to model constructing an
  9676. /// object of a derived class via a constructor of a base class.
  9677. CXXConstructorDecl *
  9678. Sema::findInheritingConstructor(SourceLocation Loc,
  9679. CXXConstructorDecl *BaseCtor,
  9680. ConstructorUsingShadowDecl *Shadow) {
  9681. CXXRecordDecl *Derived = Shadow->getParent();
  9682. SourceLocation UsingLoc = Shadow->getLocation();
  9683. // FIXME: Add a new kind of DeclarationName for an inherited constructor.
  9684. // For now we use the name of the base class constructor as a member of the
  9685. // derived class to indicate a (fake) inherited constructor name.
  9686. DeclarationName Name = BaseCtor->getDeclName();
  9687. // Check to see if we already have a fake constructor for this inherited
  9688. // constructor call.
  9689. for (NamedDecl *Ctor : Derived->lookup(Name))
  9690. if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
  9691. ->getInheritedConstructor()
  9692. .getConstructor(),
  9693. BaseCtor))
  9694. return cast<CXXConstructorDecl>(Ctor);
  9695. DeclarationNameInfo NameInfo(Name, UsingLoc);
  9696. TypeSourceInfo *TInfo =
  9697. Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
  9698. FunctionProtoTypeLoc ProtoLoc =
  9699. TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
  9700. // Check the inherited constructor is valid and find the list of base classes
  9701. // from which it was inherited.
  9702. InheritedConstructorInfo ICI(*this, Loc, Shadow);
  9703. bool Constexpr =
  9704. BaseCtor->isConstexpr() &&
  9705. defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
  9706. false, BaseCtor, &ICI);
  9707. CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
  9708. Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
  9709. BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
  9710. /*isImplicitlyDeclared=*/true,
  9711. Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
  9712. InheritedConstructor(Shadow, BaseCtor));
  9713. if (Shadow->isInvalidDecl())
  9714. DerivedCtor->setInvalidDecl();
  9715. // Build an unevaluated exception specification for this fake constructor.
  9716. const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
  9717. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9718. EPI.ExceptionSpec.Type = EST_Unevaluated;
  9719. EPI.ExceptionSpec.SourceDecl = DerivedCtor;
  9720. DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
  9721. FPT->getParamTypes(), EPI));
  9722. // Build the parameter declarations.
  9723. SmallVector<ParmVarDecl *, 16> ParamDecls;
  9724. for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
  9725. TypeSourceInfo *TInfo =
  9726. Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
  9727. ParmVarDecl *PD = ParmVarDecl::Create(
  9728. Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
  9729. FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
  9730. PD->setScopeInfo(0, I);
  9731. PD->setImplicit();
  9732. // Ensure attributes are propagated onto parameters (this matters for
  9733. // format, pass_object_size, ...).
  9734. mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
  9735. ParamDecls.push_back(PD);
  9736. ProtoLoc.setParam(I, PD);
  9737. }
  9738. // Set up the new constructor.
  9739. assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
  9740. DerivedCtor->setAccess(BaseCtor->getAccess());
  9741. DerivedCtor->setParams(ParamDecls);
  9742. Derived->addDecl(DerivedCtor);
  9743. if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
  9744. SetDeclDeleted(DerivedCtor, UsingLoc);
  9745. return DerivedCtor;
  9746. }
  9747. void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
  9748. InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
  9749. Ctor->getInheritedConstructor().getShadowDecl());
  9750. ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
  9751. /*Diagnose*/true);
  9752. }
  9753. void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
  9754. CXXConstructorDecl *Constructor) {
  9755. CXXRecordDecl *ClassDecl = Constructor->getParent();
  9756. assert(Constructor->getInheritedConstructor() &&
  9757. !Constructor->doesThisDeclarationHaveABody() &&
  9758. !Constructor->isDeleted());
  9759. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  9760. return;
  9761. // Initializations are performed "as if by a defaulted default constructor",
  9762. // so enter the appropriate scope.
  9763. SynthesizedFunctionScope Scope(*this, Constructor);
  9764. // The exception specification is needed because we are defining the
  9765. // function.
  9766. ResolveExceptionSpec(CurrentLocation,
  9767. Constructor->getType()->castAs<FunctionProtoType>());
  9768. MarkVTableUsed(CurrentLocation, ClassDecl);
  9769. // Add a context note for diagnostics produced after this point.
  9770. Scope.addContextNote(CurrentLocation);
  9771. ConstructorUsingShadowDecl *Shadow =
  9772. Constructor->getInheritedConstructor().getShadowDecl();
  9773. CXXConstructorDecl *InheritedCtor =
  9774. Constructor->getInheritedConstructor().getConstructor();
  9775. // [class.inhctor.init]p1:
  9776. // initialization proceeds as if a defaulted default constructor is used to
  9777. // initialize the D object and each base class subobject from which the
  9778. // constructor was inherited
  9779. InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
  9780. CXXRecordDecl *RD = Shadow->getParent();
  9781. SourceLocation InitLoc = Shadow->getLocation();
  9782. // Build explicit initializers for all base classes from which the
  9783. // constructor was inherited.
  9784. SmallVector<CXXCtorInitializer*, 8> Inits;
  9785. for (bool VBase : {false, true}) {
  9786. for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
  9787. if (B.isVirtual() != VBase)
  9788. continue;
  9789. auto *BaseRD = B.getType()->getAsCXXRecordDecl();
  9790. if (!BaseRD)
  9791. continue;
  9792. auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
  9793. if (!BaseCtor.first)
  9794. continue;
  9795. MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
  9796. ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
  9797. InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
  9798. auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
  9799. Inits.push_back(new (Context) CXXCtorInitializer(
  9800. Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
  9801. SourceLocation()));
  9802. }
  9803. }
  9804. // We now proceed as if for a defaulted default constructor, with the relevant
  9805. // initializers replaced.
  9806. if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
  9807. Constructor->setInvalidDecl();
  9808. return;
  9809. }
  9810. Constructor->setBody(new (Context) CompoundStmt(InitLoc));
  9811. Constructor->markUsed(Context);
  9812. if (ASTMutationListener *L = getASTMutationListener()) {
  9813. L->CompletedImplicitDefinition(Constructor);
  9814. }
  9815. DiagnoseUninitializedFields(*this, Constructor);
  9816. }
  9817. CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
  9818. // C++ [class.dtor]p2:
  9819. // If a class has no user-declared destructor, a destructor is
  9820. // declared implicitly. An implicitly-declared destructor is an
  9821. // inline public member of its class.
  9822. assert(ClassDecl->needsImplicitDestructor());
  9823. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
  9824. if (DSM.isAlreadyBeingDeclared())
  9825. return nullptr;
  9826. // Create the actual destructor declaration.
  9827. CanQualType ClassType
  9828. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  9829. SourceLocation ClassLoc = ClassDecl->getLocation();
  9830. DeclarationName Name
  9831. = Context.DeclarationNames.getCXXDestructorName(ClassType);
  9832. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9833. CXXDestructorDecl *Destructor
  9834. = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
  9835. QualType(), nullptr, /*isInline=*/true,
  9836. /*isImplicitlyDeclared=*/true);
  9837. Destructor->setAccess(AS_public);
  9838. Destructor->setDefaulted();
  9839. if (getLangOpts().CUDA) {
  9840. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
  9841. Destructor,
  9842. /* ConstRHS */ false,
  9843. /* Diagnose */ false);
  9844. }
  9845. setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
  9846. // We don't need to use SpecialMemberIsTrivial here; triviality for
  9847. // destructors is easy to compute.
  9848. Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
  9849. Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
  9850. ClassDecl->hasTrivialDestructorForCall());
  9851. // Note that we have declared this destructor.
  9852. ++getASTContext().NumImplicitDestructorsDeclared;
  9853. Scope *S = getScopeForContext(ClassDecl);
  9854. CheckImplicitSpecialMemberDeclaration(S, Destructor);
  9855. // We can't check whether an implicit destructor is deleted before we complete
  9856. // the definition of the class, because its validity depends on the alignment
  9857. // of the class. We'll check this from ActOnFields once the class is complete.
  9858. if (ClassDecl->isCompleteDefinition() &&
  9859. ShouldDeleteSpecialMember(Destructor, CXXDestructor))
  9860. SetDeclDeleted(Destructor, ClassLoc);
  9861. // Introduce this destructor into its scope.
  9862. if (S)
  9863. PushOnScopeChains(Destructor, S, false);
  9864. ClassDecl->addDecl(Destructor);
  9865. return Destructor;
  9866. }
  9867. void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
  9868. CXXDestructorDecl *Destructor) {
  9869. assert((Destructor->isDefaulted() &&
  9870. !Destructor->doesThisDeclarationHaveABody() &&
  9871. !Destructor->isDeleted()) &&
  9872. "DefineImplicitDestructor - call it for implicit default dtor");
  9873. if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
  9874. return;
  9875. CXXRecordDecl *ClassDecl = Destructor->getParent();
  9876. assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
  9877. SynthesizedFunctionScope Scope(*this, Destructor);
  9878. // The exception specification is needed because we are defining the
  9879. // function.
  9880. ResolveExceptionSpec(CurrentLocation,
  9881. Destructor->getType()->castAs<FunctionProtoType>());
  9882. MarkVTableUsed(CurrentLocation, ClassDecl);
  9883. // Add a context note for diagnostics produced after this point.
  9884. Scope.addContextNote(CurrentLocation);
  9885. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  9886. Destructor->getParent());
  9887. if (CheckDestructor(Destructor)) {
  9888. Destructor->setInvalidDecl();
  9889. return;
  9890. }
  9891. SourceLocation Loc = Destructor->getEndLoc().isValid()
  9892. ? Destructor->getEndLoc()
  9893. : Destructor->getLocation();
  9894. Destructor->setBody(new (Context) CompoundStmt(Loc));
  9895. Destructor->markUsed(Context);
  9896. if (ASTMutationListener *L = getASTMutationListener()) {
  9897. L->CompletedImplicitDefinition(Destructor);
  9898. }
  9899. }
  9900. /// Perform any semantic analysis which needs to be delayed until all
  9901. /// pending class member declarations have been parsed.
  9902. void Sema::ActOnFinishCXXMemberDecls() {
  9903. // If the context is an invalid C++ class, just suppress these checks.
  9904. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
  9905. if (Record->isInvalidDecl()) {
  9906. DelayedOverridingExceptionSpecChecks.clear();
  9907. DelayedEquivalentExceptionSpecChecks.clear();
  9908. return;
  9909. }
  9910. checkForMultipleExportedDefaultConstructors(*this, Record);
  9911. }
  9912. }
  9913. void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
  9914. referenceDLLExportedClassMethods();
  9915. }
  9916. void Sema::referenceDLLExportedClassMethods() {
  9917. if (!DelayedDllExportClasses.empty()) {
  9918. // Calling ReferenceDllExportedMembers might cause the current function to
  9919. // be called again, so use a local copy of DelayedDllExportClasses.
  9920. SmallVector<CXXRecordDecl *, 4> WorkList;
  9921. std::swap(DelayedDllExportClasses, WorkList);
  9922. for (CXXRecordDecl *Class : WorkList)
  9923. ReferenceDllExportedMembers(*this, Class);
  9924. }
  9925. }
  9926. void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
  9927. assert(getLangOpts().CPlusPlus11 &&
  9928. "adjusting dtor exception specs was introduced in c++11");
  9929. if (Destructor->isDependentContext())
  9930. return;
  9931. // C++11 [class.dtor]p3:
  9932. // A declaration of a destructor that does not have an exception-
  9933. // specification is implicitly considered to have the same exception-
  9934. // specification as an implicit declaration.
  9935. const FunctionProtoType *DtorType = Destructor->getType()->
  9936. getAs<FunctionProtoType>();
  9937. if (DtorType->hasExceptionSpec())
  9938. return;
  9939. // Replace the destructor's type, building off the existing one. Fortunately,
  9940. // the only thing of interest in the destructor type is its extended info.
  9941. // The return and arguments are fixed.
  9942. FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
  9943. EPI.ExceptionSpec.Type = EST_Unevaluated;
  9944. EPI.ExceptionSpec.SourceDecl = Destructor;
  9945. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  9946. // FIXME: If the destructor has a body that could throw, and the newly created
  9947. // spec doesn't allow exceptions, we should emit a warning, because this
  9948. // change in behavior can break conforming C++03 programs at runtime.
  9949. // However, we don't have a body or an exception specification yet, so it
  9950. // needs to be done somewhere else.
  9951. }
  9952. namespace {
  9953. /// An abstract base class for all helper classes used in building the
  9954. // copy/move operators. These classes serve as factory functions and help us
  9955. // avoid using the same Expr* in the AST twice.
  9956. class ExprBuilder {
  9957. ExprBuilder(const ExprBuilder&) = delete;
  9958. ExprBuilder &operator=(const ExprBuilder&) = delete;
  9959. protected:
  9960. static Expr *assertNotNull(Expr *E) {
  9961. assert(E && "Expression construction must not fail.");
  9962. return E;
  9963. }
  9964. public:
  9965. ExprBuilder() {}
  9966. virtual ~ExprBuilder() {}
  9967. virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
  9968. };
  9969. class RefBuilder: public ExprBuilder {
  9970. VarDecl *Var;
  9971. QualType VarType;
  9972. public:
  9973. Expr *build(Sema &S, SourceLocation Loc) const override {
  9974. return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
  9975. }
  9976. RefBuilder(VarDecl *Var, QualType VarType)
  9977. : Var(Var), VarType(VarType) {}
  9978. };
  9979. class ThisBuilder: public ExprBuilder {
  9980. public:
  9981. Expr *build(Sema &S, SourceLocation Loc) const override {
  9982. return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
  9983. }
  9984. };
  9985. class CastBuilder: public ExprBuilder {
  9986. const ExprBuilder &Builder;
  9987. QualType Type;
  9988. ExprValueKind Kind;
  9989. const CXXCastPath &Path;
  9990. public:
  9991. Expr *build(Sema &S, SourceLocation Loc) const override {
  9992. return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
  9993. CK_UncheckedDerivedToBase, Kind,
  9994. &Path).get());
  9995. }
  9996. CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
  9997. const CXXCastPath &Path)
  9998. : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
  9999. };
  10000. class DerefBuilder: public ExprBuilder {
  10001. const ExprBuilder &Builder;
  10002. public:
  10003. Expr *build(Sema &S, SourceLocation Loc) const override {
  10004. return assertNotNull(
  10005. S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
  10006. }
  10007. DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  10008. };
  10009. class MemberBuilder: public ExprBuilder {
  10010. const ExprBuilder &Builder;
  10011. QualType Type;
  10012. CXXScopeSpec SS;
  10013. bool IsArrow;
  10014. LookupResult &MemberLookup;
  10015. public:
  10016. Expr *build(Sema &S, SourceLocation Loc) const override {
  10017. return assertNotNull(S.BuildMemberReferenceExpr(
  10018. Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
  10019. nullptr, MemberLookup, nullptr, nullptr).get());
  10020. }
  10021. MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
  10022. LookupResult &MemberLookup)
  10023. : Builder(Builder), Type(Type), IsArrow(IsArrow),
  10024. MemberLookup(MemberLookup) {}
  10025. };
  10026. class MoveCastBuilder: public ExprBuilder {
  10027. const ExprBuilder &Builder;
  10028. public:
  10029. Expr *build(Sema &S, SourceLocation Loc) const override {
  10030. return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
  10031. }
  10032. MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  10033. };
  10034. class LvalueConvBuilder: public ExprBuilder {
  10035. const ExprBuilder &Builder;
  10036. public:
  10037. Expr *build(Sema &S, SourceLocation Loc) const override {
  10038. return assertNotNull(
  10039. S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
  10040. }
  10041. LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  10042. };
  10043. class SubscriptBuilder: public ExprBuilder {
  10044. const ExprBuilder &Base;
  10045. const ExprBuilder &Index;
  10046. public:
  10047. Expr *build(Sema &S, SourceLocation Loc) const override {
  10048. return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
  10049. Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
  10050. }
  10051. SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
  10052. : Base(Base), Index(Index) {}
  10053. };
  10054. } // end anonymous namespace
  10055. /// When generating a defaulted copy or move assignment operator, if a field
  10056. /// should be copied with __builtin_memcpy rather than via explicit assignments,
  10057. /// do so. This optimization only applies for arrays of scalars, and for arrays
  10058. /// of class type where the selected copy/move-assignment operator is trivial.
  10059. static StmtResult
  10060. buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
  10061. const ExprBuilder &ToB, const ExprBuilder &FromB) {
  10062. // Compute the size of the memory buffer to be copied.
  10063. QualType SizeType = S.Context.getSizeType();
  10064. llvm::APInt Size(S.Context.getTypeSize(SizeType),
  10065. S.Context.getTypeSizeInChars(T).getQuantity());
  10066. // Take the address of the field references for "from" and "to". We
  10067. // directly construct UnaryOperators here because semantic analysis
  10068. // does not permit us to take the address of an xvalue.
  10069. Expr *From = FromB.build(S, Loc);
  10070. From = new (S.Context) UnaryOperator(From, UO_AddrOf,
  10071. S.Context.getPointerType(From->getType()),
  10072. VK_RValue, OK_Ordinary, Loc, false);
  10073. Expr *To = ToB.build(S, Loc);
  10074. To = new (S.Context) UnaryOperator(To, UO_AddrOf,
  10075. S.Context.getPointerType(To->getType()),
  10076. VK_RValue, OK_Ordinary, Loc, false);
  10077. const Type *E = T->getBaseElementTypeUnsafe();
  10078. bool NeedsCollectableMemCpy =
  10079. E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
  10080. // Create a reference to the __builtin_objc_memmove_collectable function
  10081. StringRef MemCpyName = NeedsCollectableMemCpy ?
  10082. "__builtin_objc_memmove_collectable" :
  10083. "__builtin_memcpy";
  10084. LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
  10085. Sema::LookupOrdinaryName);
  10086. S.LookupName(R, S.TUScope, true);
  10087. FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
  10088. if (!MemCpy)
  10089. // Something went horribly wrong earlier, and we will have complained
  10090. // about it.
  10091. return StmtError();
  10092. ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
  10093. VK_RValue, Loc, nullptr);
  10094. assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
  10095. Expr *CallArgs[] = {
  10096. To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
  10097. };
  10098. ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
  10099. Loc, CallArgs, Loc);
  10100. assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
  10101. return Call.getAs<Stmt>();
  10102. }
  10103. /// Builds a statement that copies/moves the given entity from \p From to
  10104. /// \c To.
  10105. ///
  10106. /// This routine is used to copy/move the members of a class with an
  10107. /// implicitly-declared copy/move assignment operator. When the entities being
  10108. /// copied are arrays, this routine builds for loops to copy them.
  10109. ///
  10110. /// \param S The Sema object used for type-checking.
  10111. ///
  10112. /// \param Loc The location where the implicit copy/move is being generated.
  10113. ///
  10114. /// \param T The type of the expressions being copied/moved. Both expressions
  10115. /// must have this type.
  10116. ///
  10117. /// \param To The expression we are copying/moving to.
  10118. ///
  10119. /// \param From The expression we are copying/moving from.
  10120. ///
  10121. /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
  10122. /// Otherwise, it's a non-static member subobject.
  10123. ///
  10124. /// \param Copying Whether we're copying or moving.
  10125. ///
  10126. /// \param Depth Internal parameter recording the depth of the recursion.
  10127. ///
  10128. /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
  10129. /// if a memcpy should be used instead.
  10130. static StmtResult
  10131. buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
  10132. const ExprBuilder &To, const ExprBuilder &From,
  10133. bool CopyingBaseSubobject, bool Copying,
  10134. unsigned Depth = 0) {
  10135. // C++11 [class.copy]p28:
  10136. // Each subobject is assigned in the manner appropriate to its type:
  10137. //
  10138. // - if the subobject is of class type, as if by a call to operator= with
  10139. // the subobject as the object expression and the corresponding
  10140. // subobject of x as a single function argument (as if by explicit
  10141. // qualification; that is, ignoring any possible virtual overriding
  10142. // functions in more derived classes);
  10143. //
  10144. // C++03 [class.copy]p13:
  10145. // - if the subobject is of class type, the copy assignment operator for
  10146. // the class is used (as if by explicit qualification; that is,
  10147. // ignoring any possible virtual overriding functions in more derived
  10148. // classes);
  10149. if (const RecordType *RecordTy = T->getAs<RecordType>()) {
  10150. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  10151. // Look for operator=.
  10152. DeclarationName Name
  10153. = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10154. LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
  10155. S.LookupQualifiedName(OpLookup, ClassDecl, false);
  10156. // Prior to C++11, filter out any result that isn't a copy/move-assignment
  10157. // operator.
  10158. if (!S.getLangOpts().CPlusPlus11) {
  10159. LookupResult::Filter F = OpLookup.makeFilter();
  10160. while (F.hasNext()) {
  10161. NamedDecl *D = F.next();
  10162. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  10163. if (Method->isCopyAssignmentOperator() ||
  10164. (!Copying && Method->isMoveAssignmentOperator()))
  10165. continue;
  10166. F.erase();
  10167. }
  10168. F.done();
  10169. }
  10170. // Suppress the protected check (C++ [class.protected]) for each of the
  10171. // assignment operators we found. This strange dance is required when
  10172. // we're assigning via a base classes's copy-assignment operator. To
  10173. // ensure that we're getting the right base class subobject (without
  10174. // ambiguities), we need to cast "this" to that subobject type; to
  10175. // ensure that we don't go through the virtual call mechanism, we need
  10176. // to qualify the operator= name with the base class (see below). However,
  10177. // this means that if the base class has a protected copy assignment
  10178. // operator, the protected member access check will fail. So, we
  10179. // rewrite "protected" access to "public" access in this case, since we
  10180. // know by construction that we're calling from a derived class.
  10181. if (CopyingBaseSubobject) {
  10182. for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
  10183. L != LEnd; ++L) {
  10184. if (L.getAccess() == AS_protected)
  10185. L.setAccess(AS_public);
  10186. }
  10187. }
  10188. // Create the nested-name-specifier that will be used to qualify the
  10189. // reference to operator=; this is required to suppress the virtual
  10190. // call mechanism.
  10191. CXXScopeSpec SS;
  10192. const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
  10193. SS.MakeTrivial(S.Context,
  10194. NestedNameSpecifier::Create(S.Context, nullptr, false,
  10195. CanonicalT),
  10196. Loc);
  10197. // Create the reference to operator=.
  10198. ExprResult OpEqualRef
  10199. = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
  10200. SS, /*TemplateKWLoc=*/SourceLocation(),
  10201. /*FirstQualifierInScope=*/nullptr,
  10202. OpLookup,
  10203. /*TemplateArgs=*/nullptr, /*S*/nullptr,
  10204. /*SuppressQualifierCheck=*/true);
  10205. if (OpEqualRef.isInvalid())
  10206. return StmtError();
  10207. // Build the call to the assignment operator.
  10208. Expr *FromInst = From.build(S, Loc);
  10209. ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
  10210. OpEqualRef.getAs<Expr>(),
  10211. Loc, FromInst, Loc);
  10212. if (Call.isInvalid())
  10213. return StmtError();
  10214. // If we built a call to a trivial 'operator=' while copying an array,
  10215. // bail out. We'll replace the whole shebang with a memcpy.
  10216. CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
  10217. if (CE && CE->getMethodDecl()->isTrivial() && Depth)
  10218. return StmtResult((Stmt*)nullptr);
  10219. // Convert to an expression-statement, and clean up any produced
  10220. // temporaries.
  10221. return S.ActOnExprStmt(Call);
  10222. }
  10223. // - if the subobject is of scalar type, the built-in assignment
  10224. // operator is used.
  10225. const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
  10226. if (!ArrayTy) {
  10227. ExprResult Assignment = S.CreateBuiltinBinOp(
  10228. Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
  10229. if (Assignment.isInvalid())
  10230. return StmtError();
  10231. return S.ActOnExprStmt(Assignment);
  10232. }
  10233. // - if the subobject is an array, each element is assigned, in the
  10234. // manner appropriate to the element type;
  10235. // Construct a loop over the array bounds, e.g.,
  10236. //
  10237. // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
  10238. //
  10239. // that will copy each of the array elements.
  10240. QualType SizeType = S.Context.getSizeType();
  10241. // Create the iteration variable.
  10242. IdentifierInfo *IterationVarName = nullptr;
  10243. {
  10244. SmallString<8> Str;
  10245. llvm::raw_svector_ostream OS(Str);
  10246. OS << "__i" << Depth;
  10247. IterationVarName = &S.Context.Idents.get(OS.str());
  10248. }
  10249. VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  10250. IterationVarName, SizeType,
  10251. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  10252. SC_None);
  10253. // Initialize the iteration variable to zero.
  10254. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  10255. IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  10256. // Creates a reference to the iteration variable.
  10257. RefBuilder IterationVarRef(IterationVar, SizeType);
  10258. LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
  10259. // Create the DeclStmt that holds the iteration variable.
  10260. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
  10261. // Subscript the "from" and "to" expressions with the iteration variable.
  10262. SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
  10263. MoveCastBuilder FromIndexMove(FromIndexCopy);
  10264. const ExprBuilder *FromIndex;
  10265. if (Copying)
  10266. FromIndex = &FromIndexCopy;
  10267. else
  10268. FromIndex = &FromIndexMove;
  10269. SubscriptBuilder ToIndex(To, IterationVarRefRVal);
  10270. // Build the copy/move for an individual element of the array.
  10271. StmtResult Copy =
  10272. buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
  10273. ToIndex, *FromIndex, CopyingBaseSubobject,
  10274. Copying, Depth + 1);
  10275. // Bail out if copying fails or if we determined that we should use memcpy.
  10276. if (Copy.isInvalid() || !Copy.get())
  10277. return Copy;
  10278. // Create the comparison against the array bound.
  10279. llvm::APInt Upper
  10280. = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
  10281. Expr *Comparison
  10282. = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
  10283. IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
  10284. BO_NE, S.Context.BoolTy,
  10285. VK_RValue, OK_Ordinary, Loc, FPOptions());
  10286. // Create the pre-increment of the iteration variable. We can determine
  10287. // whether the increment will overflow based on the value of the array
  10288. // bound.
  10289. Expr *Increment = new (S.Context)
  10290. UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
  10291. VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
  10292. // Construct the loop that copies all elements of this array.
  10293. return S.ActOnForStmt(
  10294. Loc, Loc, InitStmt,
  10295. S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
  10296. S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
  10297. }
  10298. static StmtResult
  10299. buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
  10300. const ExprBuilder &To, const ExprBuilder &From,
  10301. bool CopyingBaseSubobject, bool Copying) {
  10302. // Maybe we should use a memcpy?
  10303. if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
  10304. T.isTriviallyCopyableType(S.Context))
  10305. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  10306. StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
  10307. CopyingBaseSubobject,
  10308. Copying, 0));
  10309. // If we ended up picking a trivial assignment operator for an array of a
  10310. // non-trivially-copyable class type, just emit a memcpy.
  10311. if (!Result.isInvalid() && !Result.get())
  10312. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  10313. return Result;
  10314. }
  10315. CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
  10316. // Note: The following rules are largely analoguous to the copy
  10317. // constructor rules. Note that virtual bases are not taken into account
  10318. // for determining the argument type of the operator. Note also that
  10319. // operators taking an object instead of a reference are allowed.
  10320. assert(ClassDecl->needsImplicitCopyAssignment());
  10321. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
  10322. if (DSM.isAlreadyBeingDeclared())
  10323. return nullptr;
  10324. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  10325. if (Context.getLangOpts().OpenCLCPlusPlus)
  10326. ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
  10327. QualType RetType = Context.getLValueReferenceType(ArgType);
  10328. bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
  10329. if (Const)
  10330. ArgType = ArgType.withConst();
  10331. ArgType = Context.getLValueReferenceType(ArgType);
  10332. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10333. CXXCopyAssignment,
  10334. Const);
  10335. // An implicitly-declared copy assignment operator is an inline public
  10336. // member of its class.
  10337. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10338. SourceLocation ClassLoc = ClassDecl->getLocation();
  10339. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10340. CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
  10341. Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  10342. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  10343. /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
  10344. SourceLocation());
  10345. CopyAssignment->setAccess(AS_public);
  10346. CopyAssignment->setDefaulted();
  10347. CopyAssignment->setImplicit();
  10348. if (getLangOpts().CUDA) {
  10349. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
  10350. CopyAssignment,
  10351. /* ConstRHS */ Const,
  10352. /* Diagnose */ false);
  10353. }
  10354. setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
  10355. // Add the parameter to the operator.
  10356. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
  10357. ClassLoc, ClassLoc,
  10358. /*Id=*/nullptr, ArgType,
  10359. /*TInfo=*/nullptr, SC_None,
  10360. nullptr);
  10361. CopyAssignment->setParams(FromParam);
  10362. CopyAssignment->setTrivial(
  10363. ClassDecl->needsOverloadResolutionForCopyAssignment()
  10364. ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
  10365. : ClassDecl->hasTrivialCopyAssignment());
  10366. // Note that we have added this copy-assignment operator.
  10367. ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
  10368. Scope *S = getScopeForContext(ClassDecl);
  10369. CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
  10370. if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
  10371. SetDeclDeleted(CopyAssignment, ClassLoc);
  10372. if (S)
  10373. PushOnScopeChains(CopyAssignment, S, false);
  10374. ClassDecl->addDecl(CopyAssignment);
  10375. return CopyAssignment;
  10376. }
  10377. /// Diagnose an implicit copy operation for a class which is odr-used, but
  10378. /// which is deprecated because the class has a user-declared copy constructor,
  10379. /// copy assignment operator, or destructor.
  10380. static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
  10381. assert(CopyOp->isImplicit());
  10382. CXXRecordDecl *RD = CopyOp->getParent();
  10383. CXXMethodDecl *UserDeclaredOperation = nullptr;
  10384. // In Microsoft mode, assignment operations don't affect constructors and
  10385. // vice versa.
  10386. if (RD->hasUserDeclaredDestructor()) {
  10387. UserDeclaredOperation = RD->getDestructor();
  10388. } else if (!isa<CXXConstructorDecl>(CopyOp) &&
  10389. RD->hasUserDeclaredCopyConstructor() &&
  10390. !S.getLangOpts().MSVCCompat) {
  10391. // Find any user-declared copy constructor.
  10392. for (auto *I : RD->ctors()) {
  10393. if (I->isCopyConstructor()) {
  10394. UserDeclaredOperation = I;
  10395. break;
  10396. }
  10397. }
  10398. assert(UserDeclaredOperation);
  10399. } else if (isa<CXXConstructorDecl>(CopyOp) &&
  10400. RD->hasUserDeclaredCopyAssignment() &&
  10401. !S.getLangOpts().MSVCCompat) {
  10402. // Find any user-declared move assignment operator.
  10403. for (auto *I : RD->methods()) {
  10404. if (I->isCopyAssignmentOperator()) {
  10405. UserDeclaredOperation = I;
  10406. break;
  10407. }
  10408. }
  10409. assert(UserDeclaredOperation);
  10410. }
  10411. if (UserDeclaredOperation) {
  10412. S.Diag(UserDeclaredOperation->getLocation(),
  10413. diag::warn_deprecated_copy_operation)
  10414. << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
  10415. << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
  10416. }
  10417. }
  10418. void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
  10419. CXXMethodDecl *CopyAssignOperator) {
  10420. assert((CopyAssignOperator->isDefaulted() &&
  10421. CopyAssignOperator->isOverloadedOperator() &&
  10422. CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
  10423. !CopyAssignOperator->doesThisDeclarationHaveABody() &&
  10424. !CopyAssignOperator->isDeleted()) &&
  10425. "DefineImplicitCopyAssignment called for wrong function");
  10426. if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
  10427. return;
  10428. CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
  10429. if (ClassDecl->isInvalidDecl()) {
  10430. CopyAssignOperator->setInvalidDecl();
  10431. return;
  10432. }
  10433. SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
  10434. // The exception specification is needed because we are defining the
  10435. // function.
  10436. ResolveExceptionSpec(CurrentLocation,
  10437. CopyAssignOperator->getType()->castAs<FunctionProtoType>());
  10438. // Add a context note for diagnostics produced after this point.
  10439. Scope.addContextNote(CurrentLocation);
  10440. // C++11 [class.copy]p18:
  10441. // The [definition of an implicitly declared copy assignment operator] is
  10442. // deprecated if the class has a user-declared copy constructor or a
  10443. // user-declared destructor.
  10444. if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
  10445. diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
  10446. // C++0x [class.copy]p30:
  10447. // The implicitly-defined or explicitly-defaulted copy assignment operator
  10448. // for a non-union class X performs memberwise copy assignment of its
  10449. // subobjects. The direct base classes of X are assigned first, in the
  10450. // order of their declaration in the base-specifier-list, and then the
  10451. // immediate non-static data members of X are assigned, in the order in
  10452. // which they were declared in the class definition.
  10453. // The statements that form the synthesized function body.
  10454. SmallVector<Stmt*, 8> Statements;
  10455. // The parameter for the "other" object, which we are copying from.
  10456. ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
  10457. Qualifiers OtherQuals = Other->getType().getQualifiers();
  10458. QualType OtherRefType = Other->getType();
  10459. if (const LValueReferenceType *OtherRef
  10460. = OtherRefType->getAs<LValueReferenceType>()) {
  10461. OtherRefType = OtherRef->getPointeeType();
  10462. OtherQuals = OtherRefType.getQualifiers();
  10463. }
  10464. // Our location for everything implicitly-generated.
  10465. SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
  10466. ? CopyAssignOperator->getEndLoc()
  10467. : CopyAssignOperator->getLocation();
  10468. // Builds a DeclRefExpr for the "other" object.
  10469. RefBuilder OtherRef(Other, OtherRefType);
  10470. // Builds the "this" pointer.
  10471. ThisBuilder This;
  10472. // Assign base classes.
  10473. bool Invalid = false;
  10474. for (auto &Base : ClassDecl->bases()) {
  10475. // Form the assignment:
  10476. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
  10477. QualType BaseType = Base.getType().getUnqualifiedType();
  10478. if (!BaseType->isRecordType()) {
  10479. Invalid = true;
  10480. continue;
  10481. }
  10482. CXXCastPath BasePath;
  10483. BasePath.push_back(&Base);
  10484. // Construct the "from" expression, which is an implicit cast to the
  10485. // appropriately-qualified base type.
  10486. CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
  10487. VK_LValue, BasePath);
  10488. // Dereference "this".
  10489. DerefBuilder DerefThis(This);
  10490. CastBuilder To(DerefThis,
  10491. Context.getQualifiedType(
  10492. BaseType, CopyAssignOperator->getMethodQualifiers()),
  10493. VK_LValue, BasePath);
  10494. // Build the copy.
  10495. StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
  10496. To, From,
  10497. /*CopyingBaseSubobject=*/true,
  10498. /*Copying=*/true);
  10499. if (Copy.isInvalid()) {
  10500. CopyAssignOperator->setInvalidDecl();
  10501. return;
  10502. }
  10503. // Success! Record the copy.
  10504. Statements.push_back(Copy.getAs<Expr>());
  10505. }
  10506. // Assign non-static members.
  10507. for (auto *Field : ClassDecl->fields()) {
  10508. // FIXME: We should form some kind of AST representation for the implied
  10509. // memcpy in a union copy operation.
  10510. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  10511. continue;
  10512. if (Field->isInvalidDecl()) {
  10513. Invalid = true;
  10514. continue;
  10515. }
  10516. // Check for members of reference type; we can't copy those.
  10517. if (Field->getType()->isReferenceType()) {
  10518. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10519. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  10520. Diag(Field->getLocation(), diag::note_declared_at);
  10521. Invalid = true;
  10522. continue;
  10523. }
  10524. // Check for members of const-qualified, non-class type.
  10525. QualType BaseType = Context.getBaseElementType(Field->getType());
  10526. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  10527. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10528. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  10529. Diag(Field->getLocation(), diag::note_declared_at);
  10530. Invalid = true;
  10531. continue;
  10532. }
  10533. // Suppress assigning zero-width bitfields.
  10534. if (Field->isZeroLengthBitField(Context))
  10535. continue;
  10536. QualType FieldType = Field->getType().getNonReferenceType();
  10537. if (FieldType->isIncompleteArrayType()) {
  10538. assert(ClassDecl->hasFlexibleArrayMember() &&
  10539. "Incomplete array type is not valid");
  10540. continue;
  10541. }
  10542. // Build references to the field in the object we're copying from and to.
  10543. CXXScopeSpec SS; // Intentionally empty
  10544. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  10545. LookupMemberName);
  10546. MemberLookup.addDecl(Field);
  10547. MemberLookup.resolveKind();
  10548. MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
  10549. MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
  10550. // Build the copy of this field.
  10551. StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
  10552. To, From,
  10553. /*CopyingBaseSubobject=*/false,
  10554. /*Copying=*/true);
  10555. if (Copy.isInvalid()) {
  10556. CopyAssignOperator->setInvalidDecl();
  10557. return;
  10558. }
  10559. // Success! Record the copy.
  10560. Statements.push_back(Copy.getAs<Stmt>());
  10561. }
  10562. if (!Invalid) {
  10563. // Add a "return *this;"
  10564. ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  10565. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  10566. if (Return.isInvalid())
  10567. Invalid = true;
  10568. else
  10569. Statements.push_back(Return.getAs<Stmt>());
  10570. }
  10571. if (Invalid) {
  10572. CopyAssignOperator->setInvalidDecl();
  10573. return;
  10574. }
  10575. StmtResult Body;
  10576. {
  10577. CompoundScopeRAII CompoundScope(*this);
  10578. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  10579. /*isStmtExpr=*/false);
  10580. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  10581. }
  10582. CopyAssignOperator->setBody(Body.getAs<Stmt>());
  10583. CopyAssignOperator->markUsed(Context);
  10584. if (ASTMutationListener *L = getASTMutationListener()) {
  10585. L->CompletedImplicitDefinition(CopyAssignOperator);
  10586. }
  10587. }
  10588. CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
  10589. assert(ClassDecl->needsImplicitMoveAssignment());
  10590. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
  10591. if (DSM.isAlreadyBeingDeclared())
  10592. return nullptr;
  10593. // Note: The following rules are largely analoguous to the move
  10594. // constructor rules.
  10595. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  10596. if (Context.getLangOpts().OpenCLCPlusPlus)
  10597. ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
  10598. QualType RetType = Context.getLValueReferenceType(ArgType);
  10599. ArgType = Context.getRValueReferenceType(ArgType);
  10600. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10601. CXXMoveAssignment,
  10602. false);
  10603. // An implicitly-declared move assignment operator is an inline public
  10604. // member of its class.
  10605. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10606. SourceLocation ClassLoc = ClassDecl->getLocation();
  10607. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10608. CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
  10609. Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  10610. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  10611. /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
  10612. SourceLocation());
  10613. MoveAssignment->setAccess(AS_public);
  10614. MoveAssignment->setDefaulted();
  10615. MoveAssignment->setImplicit();
  10616. if (getLangOpts().CUDA) {
  10617. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
  10618. MoveAssignment,
  10619. /* ConstRHS */ false,
  10620. /* Diagnose */ false);
  10621. }
  10622. // Build an exception specification pointing back at this member.
  10623. FunctionProtoType::ExtProtoInfo EPI =
  10624. getImplicitMethodEPI(*this, MoveAssignment);
  10625. MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
  10626. // Add the parameter to the operator.
  10627. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
  10628. ClassLoc, ClassLoc,
  10629. /*Id=*/nullptr, ArgType,
  10630. /*TInfo=*/nullptr, SC_None,
  10631. nullptr);
  10632. MoveAssignment->setParams(FromParam);
  10633. MoveAssignment->setTrivial(
  10634. ClassDecl->needsOverloadResolutionForMoveAssignment()
  10635. ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
  10636. : ClassDecl->hasTrivialMoveAssignment());
  10637. // Note that we have added this copy-assignment operator.
  10638. ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
  10639. Scope *S = getScopeForContext(ClassDecl);
  10640. CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
  10641. if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
  10642. ClassDecl->setImplicitMoveAssignmentIsDeleted();
  10643. SetDeclDeleted(MoveAssignment, ClassLoc);
  10644. }
  10645. if (S)
  10646. PushOnScopeChains(MoveAssignment, S, false);
  10647. ClassDecl->addDecl(MoveAssignment);
  10648. return MoveAssignment;
  10649. }
  10650. /// Check if we're implicitly defining a move assignment operator for a class
  10651. /// with virtual bases. Such a move assignment might move-assign the virtual
  10652. /// base multiple times.
  10653. static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
  10654. SourceLocation CurrentLocation) {
  10655. assert(!Class->isDependentContext() && "should not define dependent move");
  10656. // Only a virtual base could get implicitly move-assigned multiple times.
  10657. // Only a non-trivial move assignment can observe this. We only want to
  10658. // diagnose if we implicitly define an assignment operator that assigns
  10659. // two base classes, both of which move-assign the same virtual base.
  10660. if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
  10661. Class->getNumBases() < 2)
  10662. return;
  10663. llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
  10664. typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
  10665. VBaseMap VBases;
  10666. for (auto &BI : Class->bases()) {
  10667. Worklist.push_back(&BI);
  10668. while (!Worklist.empty()) {
  10669. CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
  10670. CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
  10671. // If the base has no non-trivial move assignment operators,
  10672. // we don't care about moves from it.
  10673. if (!Base->hasNonTrivialMoveAssignment())
  10674. continue;
  10675. // If there's nothing virtual here, skip it.
  10676. if (!BaseSpec->isVirtual() && !Base->getNumVBases())
  10677. continue;
  10678. // If we're not actually going to call a move assignment for this base,
  10679. // or the selected move assignment is trivial, skip it.
  10680. Sema::SpecialMemberOverloadResult SMOR =
  10681. S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
  10682. /*ConstArg*/false, /*VolatileArg*/false,
  10683. /*RValueThis*/true, /*ConstThis*/false,
  10684. /*VolatileThis*/false);
  10685. if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
  10686. !SMOR.getMethod()->isMoveAssignmentOperator())
  10687. continue;
  10688. if (BaseSpec->isVirtual()) {
  10689. // We're going to move-assign this virtual base, and its move
  10690. // assignment operator is not trivial. If this can happen for
  10691. // multiple distinct direct bases of Class, diagnose it. (If it
  10692. // only happens in one base, we'll diagnose it when synthesizing
  10693. // that base class's move assignment operator.)
  10694. CXXBaseSpecifier *&Existing =
  10695. VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
  10696. .first->second;
  10697. if (Existing && Existing != &BI) {
  10698. S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
  10699. << Class << Base;
  10700. S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
  10701. << (Base->getCanonicalDecl() ==
  10702. Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10703. << Base << Existing->getType() << Existing->getSourceRange();
  10704. S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
  10705. << (Base->getCanonicalDecl() ==
  10706. BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10707. << Base << BI.getType() << BaseSpec->getSourceRange();
  10708. // Only diagnose each vbase once.
  10709. Existing = nullptr;
  10710. }
  10711. } else {
  10712. // Only walk over bases that have defaulted move assignment operators.
  10713. // We assume that any user-provided move assignment operator handles
  10714. // the multiple-moves-of-vbase case itself somehow.
  10715. if (!SMOR.getMethod()->isDefaulted())
  10716. continue;
  10717. // We're going to move the base classes of Base. Add them to the list.
  10718. for (auto &BI : Base->bases())
  10719. Worklist.push_back(&BI);
  10720. }
  10721. }
  10722. }
  10723. }
  10724. void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
  10725. CXXMethodDecl *MoveAssignOperator) {
  10726. assert((MoveAssignOperator->isDefaulted() &&
  10727. MoveAssignOperator->isOverloadedOperator() &&
  10728. MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
  10729. !MoveAssignOperator->doesThisDeclarationHaveABody() &&
  10730. !MoveAssignOperator->isDeleted()) &&
  10731. "DefineImplicitMoveAssignment called for wrong function");
  10732. if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
  10733. return;
  10734. CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
  10735. if (ClassDecl->isInvalidDecl()) {
  10736. MoveAssignOperator->setInvalidDecl();
  10737. return;
  10738. }
  10739. // C++0x [class.copy]p28:
  10740. // The implicitly-defined or move assignment operator for a non-union class
  10741. // X performs memberwise move assignment of its subobjects. The direct base
  10742. // classes of X are assigned first, in the order of their declaration in the
  10743. // base-specifier-list, and then the immediate non-static data members of X
  10744. // are assigned, in the order in which they were declared in the class
  10745. // definition.
  10746. // Issue a warning if our implicit move assignment operator will move
  10747. // from a virtual base more than once.
  10748. checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
  10749. SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
  10750. // The exception specification is needed because we are defining the
  10751. // function.
  10752. ResolveExceptionSpec(CurrentLocation,
  10753. MoveAssignOperator->getType()->castAs<FunctionProtoType>());
  10754. // Add a context note for diagnostics produced after this point.
  10755. Scope.addContextNote(CurrentLocation);
  10756. // The statements that form the synthesized function body.
  10757. SmallVector<Stmt*, 8> Statements;
  10758. // The parameter for the "other" object, which we are move from.
  10759. ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
  10760. QualType OtherRefType = Other->getType()->
  10761. getAs<RValueReferenceType>()->getPointeeType();
  10762. // Our location for everything implicitly-generated.
  10763. SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
  10764. ? MoveAssignOperator->getEndLoc()
  10765. : MoveAssignOperator->getLocation();
  10766. // Builds a reference to the "other" object.
  10767. RefBuilder OtherRef(Other, OtherRefType);
  10768. // Cast to rvalue.
  10769. MoveCastBuilder MoveOther(OtherRef);
  10770. // Builds the "this" pointer.
  10771. ThisBuilder This;
  10772. // Assign base classes.
  10773. bool Invalid = false;
  10774. for (auto &Base : ClassDecl->bases()) {
  10775. // C++11 [class.copy]p28:
  10776. // It is unspecified whether subobjects representing virtual base classes
  10777. // are assigned more than once by the implicitly-defined copy assignment
  10778. // operator.
  10779. // FIXME: Do not assign to a vbase that will be assigned by some other base
  10780. // class. For a move-assignment, this can result in the vbase being moved
  10781. // multiple times.
  10782. // Form the assignment:
  10783. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
  10784. QualType BaseType = Base.getType().getUnqualifiedType();
  10785. if (!BaseType->isRecordType()) {
  10786. Invalid = true;
  10787. continue;
  10788. }
  10789. CXXCastPath BasePath;
  10790. BasePath.push_back(&Base);
  10791. // Construct the "from" expression, which is an implicit cast to the
  10792. // appropriately-qualified base type.
  10793. CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
  10794. // Dereference "this".
  10795. DerefBuilder DerefThis(This);
  10796. // Implicitly cast "this" to the appropriately-qualified base type.
  10797. CastBuilder To(DerefThis,
  10798. Context.getQualifiedType(
  10799. BaseType, MoveAssignOperator->getMethodQualifiers()),
  10800. VK_LValue, BasePath);
  10801. // Build the move.
  10802. StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
  10803. To, From,
  10804. /*CopyingBaseSubobject=*/true,
  10805. /*Copying=*/false);
  10806. if (Move.isInvalid()) {
  10807. MoveAssignOperator->setInvalidDecl();
  10808. return;
  10809. }
  10810. // Success! Record the move.
  10811. Statements.push_back(Move.getAs<Expr>());
  10812. }
  10813. // Assign non-static members.
  10814. for (auto *Field : ClassDecl->fields()) {
  10815. // FIXME: We should form some kind of AST representation for the implied
  10816. // memcpy in a union copy operation.
  10817. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  10818. continue;
  10819. if (Field->isInvalidDecl()) {
  10820. Invalid = true;
  10821. continue;
  10822. }
  10823. // Check for members of reference type; we can't move those.
  10824. if (Field->getType()->isReferenceType()) {
  10825. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10826. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  10827. Diag(Field->getLocation(), diag::note_declared_at);
  10828. Invalid = true;
  10829. continue;
  10830. }
  10831. // Check for members of const-qualified, non-class type.
  10832. QualType BaseType = Context.getBaseElementType(Field->getType());
  10833. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  10834. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10835. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  10836. Diag(Field->getLocation(), diag::note_declared_at);
  10837. Invalid = true;
  10838. continue;
  10839. }
  10840. // Suppress assigning zero-width bitfields.
  10841. if (Field->isZeroLengthBitField(Context))
  10842. continue;
  10843. QualType FieldType = Field->getType().getNonReferenceType();
  10844. if (FieldType->isIncompleteArrayType()) {
  10845. assert(ClassDecl->hasFlexibleArrayMember() &&
  10846. "Incomplete array type is not valid");
  10847. continue;
  10848. }
  10849. // Build references to the field in the object we're copying from and to.
  10850. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  10851. LookupMemberName);
  10852. MemberLookup.addDecl(Field);
  10853. MemberLookup.resolveKind();
  10854. MemberBuilder From(MoveOther, OtherRefType,
  10855. /*IsArrow=*/false, MemberLookup);
  10856. MemberBuilder To(This, getCurrentThisType(),
  10857. /*IsArrow=*/true, MemberLookup);
  10858. assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
  10859. "Member reference with rvalue base must be rvalue except for reference "
  10860. "members, which aren't allowed for move assignment.");
  10861. // Build the move of this field.
  10862. StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
  10863. To, From,
  10864. /*CopyingBaseSubobject=*/false,
  10865. /*Copying=*/false);
  10866. if (Move.isInvalid()) {
  10867. MoveAssignOperator->setInvalidDecl();
  10868. return;
  10869. }
  10870. // Success! Record the copy.
  10871. Statements.push_back(Move.getAs<Stmt>());
  10872. }
  10873. if (!Invalid) {
  10874. // Add a "return *this;"
  10875. ExprResult ThisObj =
  10876. CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  10877. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  10878. if (Return.isInvalid())
  10879. Invalid = true;
  10880. else
  10881. Statements.push_back(Return.getAs<Stmt>());
  10882. }
  10883. if (Invalid) {
  10884. MoveAssignOperator->setInvalidDecl();
  10885. return;
  10886. }
  10887. StmtResult Body;
  10888. {
  10889. CompoundScopeRAII CompoundScope(*this);
  10890. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  10891. /*isStmtExpr=*/false);
  10892. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  10893. }
  10894. MoveAssignOperator->setBody(Body.getAs<Stmt>());
  10895. MoveAssignOperator->markUsed(Context);
  10896. if (ASTMutationListener *L = getASTMutationListener()) {
  10897. L->CompletedImplicitDefinition(MoveAssignOperator);
  10898. }
  10899. }
  10900. CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
  10901. CXXRecordDecl *ClassDecl) {
  10902. // C++ [class.copy]p4:
  10903. // If the class definition does not explicitly declare a copy
  10904. // constructor, one is declared implicitly.
  10905. assert(ClassDecl->needsImplicitCopyConstructor());
  10906. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
  10907. if (DSM.isAlreadyBeingDeclared())
  10908. return nullptr;
  10909. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  10910. QualType ArgType = ClassType;
  10911. bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
  10912. if (Const)
  10913. ArgType = ArgType.withConst();
  10914. if (Context.getLangOpts().OpenCLCPlusPlus)
  10915. ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
  10916. ArgType = Context.getLValueReferenceType(ArgType);
  10917. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10918. CXXCopyConstructor,
  10919. Const);
  10920. DeclarationName Name
  10921. = Context.DeclarationNames.getCXXConstructorName(
  10922. Context.getCanonicalType(ClassType));
  10923. SourceLocation ClassLoc = ClassDecl->getLocation();
  10924. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10925. // An implicitly-declared copy constructor is an inline public
  10926. // member of its class.
  10927. CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
  10928. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  10929. ExplicitSpecifier(),
  10930. /*isInline=*/true,
  10931. /*isImplicitlyDeclared=*/true,
  10932. Constexpr ? CSK_constexpr : CSK_unspecified);
  10933. CopyConstructor->setAccess(AS_public);
  10934. CopyConstructor->setDefaulted();
  10935. if (getLangOpts().CUDA) {
  10936. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
  10937. CopyConstructor,
  10938. /* ConstRHS */ Const,
  10939. /* Diagnose */ false);
  10940. }
  10941. setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
  10942. // Add the parameter to the constructor.
  10943. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
  10944. ClassLoc, ClassLoc,
  10945. /*IdentifierInfo=*/nullptr,
  10946. ArgType, /*TInfo=*/nullptr,
  10947. SC_None, nullptr);
  10948. CopyConstructor->setParams(FromParam);
  10949. CopyConstructor->setTrivial(
  10950. ClassDecl->needsOverloadResolutionForCopyConstructor()
  10951. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
  10952. : ClassDecl->hasTrivialCopyConstructor());
  10953. CopyConstructor->setTrivialForCall(
  10954. ClassDecl->hasAttr<TrivialABIAttr>() ||
  10955. (ClassDecl->needsOverloadResolutionForCopyConstructor()
  10956. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
  10957. TAH_ConsiderTrivialABI)
  10958. : ClassDecl->hasTrivialCopyConstructorForCall()));
  10959. // Note that we have declared this constructor.
  10960. ++getASTContext().NumImplicitCopyConstructorsDeclared;
  10961. Scope *S = getScopeForContext(ClassDecl);
  10962. CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
  10963. if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
  10964. ClassDecl->setImplicitCopyConstructorIsDeleted();
  10965. SetDeclDeleted(CopyConstructor, ClassLoc);
  10966. }
  10967. if (S)
  10968. PushOnScopeChains(CopyConstructor, S, false);
  10969. ClassDecl->addDecl(CopyConstructor);
  10970. return CopyConstructor;
  10971. }
  10972. void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
  10973. CXXConstructorDecl *CopyConstructor) {
  10974. assert((CopyConstructor->isDefaulted() &&
  10975. CopyConstructor->isCopyConstructor() &&
  10976. !CopyConstructor->doesThisDeclarationHaveABody() &&
  10977. !CopyConstructor->isDeleted()) &&
  10978. "DefineImplicitCopyConstructor - call it for implicit copy ctor");
  10979. if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
  10980. return;
  10981. CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
  10982. assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
  10983. SynthesizedFunctionScope Scope(*this, CopyConstructor);
  10984. // The exception specification is needed because we are defining the
  10985. // function.
  10986. ResolveExceptionSpec(CurrentLocation,
  10987. CopyConstructor->getType()->castAs<FunctionProtoType>());
  10988. MarkVTableUsed(CurrentLocation, ClassDecl);
  10989. // Add a context note for diagnostics produced after this point.
  10990. Scope.addContextNote(CurrentLocation);
  10991. // C++11 [class.copy]p7:
  10992. // The [definition of an implicitly declared copy constructor] is
  10993. // deprecated if the class has a user-declared copy assignment operator
  10994. // or a user-declared destructor.
  10995. if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
  10996. diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
  10997. if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
  10998. CopyConstructor->setInvalidDecl();
  10999. } else {
  11000. SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
  11001. ? CopyConstructor->getEndLoc()
  11002. : CopyConstructor->getLocation();
  11003. Sema::CompoundScopeRAII CompoundScope(*this);
  11004. CopyConstructor->setBody(
  11005. ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
  11006. CopyConstructor->markUsed(Context);
  11007. }
  11008. if (ASTMutationListener *L = getASTMutationListener()) {
  11009. L->CompletedImplicitDefinition(CopyConstructor);
  11010. }
  11011. }
  11012. CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
  11013. CXXRecordDecl *ClassDecl) {
  11014. assert(ClassDecl->needsImplicitMoveConstructor());
  11015. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
  11016. if (DSM.isAlreadyBeingDeclared())
  11017. return nullptr;
  11018. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  11019. QualType ArgType = ClassType;
  11020. if (Context.getLangOpts().OpenCLCPlusPlus)
  11021. ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
  11022. ArgType = Context.getRValueReferenceType(ArgType);
  11023. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  11024. CXXMoveConstructor,
  11025. false);
  11026. DeclarationName Name
  11027. = Context.DeclarationNames.getCXXConstructorName(
  11028. Context.getCanonicalType(ClassType));
  11029. SourceLocation ClassLoc = ClassDecl->getLocation();
  11030. DeclarationNameInfo NameInfo(Name, ClassLoc);
  11031. // C++11 [class.copy]p11:
  11032. // An implicitly-declared copy/move constructor is an inline public
  11033. // member of its class.
  11034. CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
  11035. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  11036. ExplicitSpecifier(),
  11037. /*isInline=*/true,
  11038. /*isImplicitlyDeclared=*/true,
  11039. Constexpr ? CSK_constexpr : CSK_unspecified);
  11040. MoveConstructor->setAccess(AS_public);
  11041. MoveConstructor->setDefaulted();
  11042. if (getLangOpts().CUDA) {
  11043. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
  11044. MoveConstructor,
  11045. /* ConstRHS */ false,
  11046. /* Diagnose */ false);
  11047. }
  11048. setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
  11049. // Add the parameter to the constructor.
  11050. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
  11051. ClassLoc, ClassLoc,
  11052. /*IdentifierInfo=*/nullptr,
  11053. ArgType, /*TInfo=*/nullptr,
  11054. SC_None, nullptr);
  11055. MoveConstructor->setParams(FromParam);
  11056. MoveConstructor->setTrivial(
  11057. ClassDecl->needsOverloadResolutionForMoveConstructor()
  11058. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
  11059. : ClassDecl->hasTrivialMoveConstructor());
  11060. MoveConstructor->setTrivialForCall(
  11061. ClassDecl->hasAttr<TrivialABIAttr>() ||
  11062. (ClassDecl->needsOverloadResolutionForMoveConstructor()
  11063. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
  11064. TAH_ConsiderTrivialABI)
  11065. : ClassDecl->hasTrivialMoveConstructorForCall()));
  11066. // Note that we have declared this constructor.
  11067. ++getASTContext().NumImplicitMoveConstructorsDeclared;
  11068. Scope *S = getScopeForContext(ClassDecl);
  11069. CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
  11070. if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
  11071. ClassDecl->setImplicitMoveConstructorIsDeleted();
  11072. SetDeclDeleted(MoveConstructor, ClassLoc);
  11073. }
  11074. if (S)
  11075. PushOnScopeChains(MoveConstructor, S, false);
  11076. ClassDecl->addDecl(MoveConstructor);
  11077. return MoveConstructor;
  11078. }
  11079. void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
  11080. CXXConstructorDecl *MoveConstructor) {
  11081. assert((MoveConstructor->isDefaulted() &&
  11082. MoveConstructor->isMoveConstructor() &&
  11083. !MoveConstructor->doesThisDeclarationHaveABody() &&
  11084. !MoveConstructor->isDeleted()) &&
  11085. "DefineImplicitMoveConstructor - call it for implicit move ctor");
  11086. if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
  11087. return;
  11088. CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
  11089. assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
  11090. SynthesizedFunctionScope Scope(*this, MoveConstructor);
  11091. // The exception specification is needed because we are defining the
  11092. // function.
  11093. ResolveExceptionSpec(CurrentLocation,
  11094. MoveConstructor->getType()->castAs<FunctionProtoType>());
  11095. MarkVTableUsed(CurrentLocation, ClassDecl);
  11096. // Add a context note for diagnostics produced after this point.
  11097. Scope.addContextNote(CurrentLocation);
  11098. if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
  11099. MoveConstructor->setInvalidDecl();
  11100. } else {
  11101. SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
  11102. ? MoveConstructor->getEndLoc()
  11103. : MoveConstructor->getLocation();
  11104. Sema::CompoundScopeRAII CompoundScope(*this);
  11105. MoveConstructor->setBody(ActOnCompoundStmt(
  11106. Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
  11107. MoveConstructor->markUsed(Context);
  11108. }
  11109. if (ASTMutationListener *L = getASTMutationListener()) {
  11110. L->CompletedImplicitDefinition(MoveConstructor);
  11111. }
  11112. }
  11113. bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
  11114. return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
  11115. }
  11116. void Sema::DefineImplicitLambdaToFunctionPointerConversion(
  11117. SourceLocation CurrentLocation,
  11118. CXXConversionDecl *Conv) {
  11119. SynthesizedFunctionScope Scope(*this, Conv);
  11120. assert(!Conv->getReturnType()->isUndeducedType());
  11121. CXXRecordDecl *Lambda = Conv->getParent();
  11122. FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
  11123. FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
  11124. if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
  11125. CallOp = InstantiateFunctionDeclaration(
  11126. CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  11127. if (!CallOp)
  11128. return;
  11129. Invoker = InstantiateFunctionDeclaration(
  11130. Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  11131. if (!Invoker)
  11132. return;
  11133. }
  11134. if (CallOp->isInvalidDecl())
  11135. return;
  11136. // Mark the call operator referenced (and add to pending instantiations
  11137. // if necessary).
  11138. // For both the conversion and static-invoker template specializations
  11139. // we construct their body's in this function, so no need to add them
  11140. // to the PendingInstantiations.
  11141. MarkFunctionReferenced(CurrentLocation, CallOp);
  11142. // Fill in the __invoke function with a dummy implementation. IR generation
  11143. // will fill in the actual details. Update its type in case it contained
  11144. // an 'auto'.
  11145. Invoker->markUsed(Context);
  11146. Invoker->setReferenced();
  11147. Invoker->setType(Conv->getReturnType()->getPointeeType());
  11148. Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
  11149. // Construct the body of the conversion function { return __invoke; }.
  11150. Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
  11151. VK_LValue, Conv->getLocation());
  11152. assert(FunctionRef && "Can't refer to __invoke function?");
  11153. Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
  11154. Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
  11155. Conv->getLocation()));
  11156. Conv->markUsed(Context);
  11157. Conv->setReferenced();
  11158. if (ASTMutationListener *L = getASTMutationListener()) {
  11159. L->CompletedImplicitDefinition(Conv);
  11160. L->CompletedImplicitDefinition(Invoker);
  11161. }
  11162. }
  11163. void Sema::DefineImplicitLambdaToBlockPointerConversion(
  11164. SourceLocation CurrentLocation,
  11165. CXXConversionDecl *Conv)
  11166. {
  11167. assert(!Conv->getParent()->isGenericLambda());
  11168. SynthesizedFunctionScope Scope(*this, Conv);
  11169. // Copy-initialize the lambda object as needed to capture it.
  11170. Expr *This = ActOnCXXThis(CurrentLocation).get();
  11171. Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
  11172. ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
  11173. Conv->getLocation(),
  11174. Conv, DerefThis);
  11175. // If we're not under ARC, make sure we still get the _Block_copy/autorelease
  11176. // behavior. Note that only the general conversion function does this
  11177. // (since it's unusable otherwise); in the case where we inline the
  11178. // block literal, it has block literal lifetime semantics.
  11179. if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
  11180. BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
  11181. CK_CopyAndAutoreleaseBlockObject,
  11182. BuildBlock.get(), nullptr, VK_RValue);
  11183. if (BuildBlock.isInvalid()) {
  11184. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  11185. Conv->setInvalidDecl();
  11186. return;
  11187. }
  11188. // Create the return statement that returns the block from the conversion
  11189. // function.
  11190. StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
  11191. if (Return.isInvalid()) {
  11192. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  11193. Conv->setInvalidDecl();
  11194. return;
  11195. }
  11196. // Set the body of the conversion function.
  11197. Stmt *ReturnS = Return.get();
  11198. Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
  11199. Conv->getLocation()));
  11200. Conv->markUsed(Context);
  11201. // We're done; notify the mutation listener, if any.
  11202. if (ASTMutationListener *L = getASTMutationListener()) {
  11203. L->CompletedImplicitDefinition(Conv);
  11204. }
  11205. }
  11206. /// Determine whether the given list arguments contains exactly one
  11207. /// "real" (non-default) argument.
  11208. static bool hasOneRealArgument(MultiExprArg Args) {
  11209. switch (Args.size()) {
  11210. case 0:
  11211. return false;
  11212. default:
  11213. if (!Args[1]->isDefaultArgument())
  11214. return false;
  11215. LLVM_FALLTHROUGH;
  11216. case 1:
  11217. return !Args[0]->isDefaultArgument();
  11218. }
  11219. return false;
  11220. }
  11221. ExprResult
  11222. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11223. NamedDecl *FoundDecl,
  11224. CXXConstructorDecl *Constructor,
  11225. MultiExprArg ExprArgs,
  11226. bool HadMultipleCandidates,
  11227. bool IsListInitialization,
  11228. bool IsStdInitListInitialization,
  11229. bool RequiresZeroInit,
  11230. unsigned ConstructKind,
  11231. SourceRange ParenRange) {
  11232. bool Elidable = false;
  11233. // C++0x [class.copy]p34:
  11234. // When certain criteria are met, an implementation is allowed to
  11235. // omit the copy/move construction of a class object, even if the
  11236. // copy/move constructor and/or destructor for the object have
  11237. // side effects. [...]
  11238. // - when a temporary class object that has not been bound to a
  11239. // reference (12.2) would be copied/moved to a class object
  11240. // with the same cv-unqualified type, the copy/move operation
  11241. // can be omitted by constructing the temporary object
  11242. // directly into the target of the omitted copy/move
  11243. if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
  11244. Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
  11245. Expr *SubExpr = ExprArgs[0];
  11246. Elidable = SubExpr->isTemporaryObject(
  11247. Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  11248. }
  11249. return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
  11250. FoundDecl, Constructor,
  11251. Elidable, ExprArgs, HadMultipleCandidates,
  11252. IsListInitialization,
  11253. IsStdInitListInitialization, RequiresZeroInit,
  11254. ConstructKind, ParenRange);
  11255. }
  11256. ExprResult
  11257. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11258. NamedDecl *FoundDecl,
  11259. CXXConstructorDecl *Constructor,
  11260. bool Elidable,
  11261. MultiExprArg ExprArgs,
  11262. bool HadMultipleCandidates,
  11263. bool IsListInitialization,
  11264. bool IsStdInitListInitialization,
  11265. bool RequiresZeroInit,
  11266. unsigned ConstructKind,
  11267. SourceRange ParenRange) {
  11268. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
  11269. Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
  11270. if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
  11271. return ExprError();
  11272. }
  11273. return BuildCXXConstructExpr(
  11274. ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
  11275. HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
  11276. RequiresZeroInit, ConstructKind, ParenRange);
  11277. }
  11278. /// BuildCXXConstructExpr - Creates a complete call to a constructor,
  11279. /// including handling of its default argument expressions.
  11280. ExprResult
  11281. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11282. CXXConstructorDecl *Constructor,
  11283. bool Elidable,
  11284. MultiExprArg ExprArgs,
  11285. bool HadMultipleCandidates,
  11286. bool IsListInitialization,
  11287. bool IsStdInitListInitialization,
  11288. bool RequiresZeroInit,
  11289. unsigned ConstructKind,
  11290. SourceRange ParenRange) {
  11291. assert(declaresSameEntity(
  11292. Constructor->getParent(),
  11293. DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
  11294. "given constructor for wrong type");
  11295. MarkFunctionReferenced(ConstructLoc, Constructor);
  11296. if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
  11297. return ExprError();
  11298. return CXXConstructExpr::Create(
  11299. Context, DeclInitType, ConstructLoc, Constructor, Elidable,
  11300. ExprArgs, HadMultipleCandidates, IsListInitialization,
  11301. IsStdInitListInitialization, RequiresZeroInit,
  11302. static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
  11303. ParenRange);
  11304. }
  11305. ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
  11306. assert(Field->hasInClassInitializer());
  11307. // If we already have the in-class initializer nothing needs to be done.
  11308. if (Field->getInClassInitializer())
  11309. return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
  11310. // If we might have already tried and failed to instantiate, don't try again.
  11311. if (Field->isInvalidDecl())
  11312. return ExprError();
  11313. // Maybe we haven't instantiated the in-class initializer. Go check the
  11314. // pattern FieldDecl to see if it has one.
  11315. CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
  11316. if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
  11317. CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
  11318. DeclContext::lookup_result Lookup =
  11319. ClassPattern->lookup(Field->getDeclName());
  11320. // Lookup can return at most two results: the pattern for the field, or the
  11321. // injected class name of the parent record. No other member can have the
  11322. // same name as the field.
  11323. // In modules mode, lookup can return multiple results (coming from
  11324. // different modules).
  11325. assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
  11326. "more than two lookup results for field name");
  11327. FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
  11328. if (!Pattern) {
  11329. assert(isa<CXXRecordDecl>(Lookup[0]) &&
  11330. "cannot have other non-field member with same name");
  11331. for (auto L : Lookup)
  11332. if (isa<FieldDecl>(L)) {
  11333. Pattern = cast<FieldDecl>(L);
  11334. break;
  11335. }
  11336. assert(Pattern && "We must have set the Pattern!");
  11337. }
  11338. if (!Pattern->hasInClassInitializer() ||
  11339. InstantiateInClassInitializer(Loc, Field, Pattern,
  11340. getTemplateInstantiationArgs(Field))) {
  11341. // Don't diagnose this again.
  11342. Field->setInvalidDecl();
  11343. return ExprError();
  11344. }
  11345. return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
  11346. }
  11347. // DR1351:
  11348. // If the brace-or-equal-initializer of a non-static data member
  11349. // invokes a defaulted default constructor of its class or of an
  11350. // enclosing class in a potentially evaluated subexpression, the
  11351. // program is ill-formed.
  11352. //
  11353. // This resolution is unworkable: the exception specification of the
  11354. // default constructor can be needed in an unevaluated context, in
  11355. // particular, in the operand of a noexcept-expression, and we can be
  11356. // unable to compute an exception specification for an enclosed class.
  11357. //
  11358. // Any attempt to resolve the exception specification of a defaulted default
  11359. // constructor before the initializer is lexically complete will ultimately
  11360. // come here at which point we can diagnose it.
  11361. RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
  11362. Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
  11363. << OutermostClass << Field;
  11364. Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
  11365. // Recover by marking the field invalid, unless we're in a SFINAE context.
  11366. if (!isSFINAEContext())
  11367. Field->setInvalidDecl();
  11368. return ExprError();
  11369. }
  11370. void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
  11371. if (VD->isInvalidDecl()) return;
  11372. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
  11373. if (ClassDecl->isInvalidDecl()) return;
  11374. if (ClassDecl->hasIrrelevantDestructor()) return;
  11375. if (ClassDecl->isDependentContext()) return;
  11376. if (VD->isNoDestroy(getASTContext()))
  11377. return;
  11378. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  11379. // If this is an array, we'll require the destructor during initialization, so
  11380. // we can skip over this. We still want to emit exit-time destructor warnings
  11381. // though.
  11382. if (!VD->getType()->isArrayType()) {
  11383. MarkFunctionReferenced(VD->getLocation(), Destructor);
  11384. CheckDestructorAccess(VD->getLocation(), Destructor,
  11385. PDiag(diag::err_access_dtor_var)
  11386. << VD->getDeclName() << VD->getType());
  11387. DiagnoseUseOfDecl(Destructor, VD->getLocation());
  11388. }
  11389. if (Destructor->isTrivial()) return;
  11390. if (!VD->hasGlobalStorage()) return;
  11391. // Emit warning for non-trivial dtor in global scope (a real global,
  11392. // class-static, function-static).
  11393. Diag(VD->getLocation(), diag::warn_exit_time_destructor);
  11394. // TODO: this should be re-enabled for static locals by !CXAAtExit
  11395. if (!VD->isStaticLocal())
  11396. Diag(VD->getLocation(), diag::warn_global_destructor);
  11397. }
  11398. /// Given a constructor and the set of arguments provided for the
  11399. /// constructor, convert the arguments and add any required default arguments
  11400. /// to form a proper call to this constructor.
  11401. ///
  11402. /// \returns true if an error occurred, false otherwise.
  11403. bool
  11404. Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
  11405. MultiExprArg ArgsPtr,
  11406. SourceLocation Loc,
  11407. SmallVectorImpl<Expr*> &ConvertedArgs,
  11408. bool AllowExplicit,
  11409. bool IsListInitialization) {
  11410. // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
  11411. unsigned NumArgs = ArgsPtr.size();
  11412. Expr **Args = ArgsPtr.data();
  11413. const FunctionProtoType *Proto
  11414. = Constructor->getType()->getAs<FunctionProtoType>();
  11415. assert(Proto && "Constructor without a prototype?");
  11416. unsigned NumParams = Proto->getNumParams();
  11417. // If too few arguments are available, we'll fill in the rest with defaults.
  11418. if (NumArgs < NumParams)
  11419. ConvertedArgs.reserve(NumParams);
  11420. else
  11421. ConvertedArgs.reserve(NumArgs);
  11422. VariadicCallType CallType =
  11423. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  11424. SmallVector<Expr *, 8> AllArgs;
  11425. bool Invalid = GatherArgumentsForCall(Loc, Constructor,
  11426. Proto, 0,
  11427. llvm::makeArrayRef(Args, NumArgs),
  11428. AllArgs,
  11429. CallType, AllowExplicit,
  11430. IsListInitialization);
  11431. ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
  11432. DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
  11433. CheckConstructorCall(Constructor,
  11434. llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
  11435. Proto, Loc);
  11436. return Invalid;
  11437. }
  11438. static inline bool
  11439. CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
  11440. const FunctionDecl *FnDecl) {
  11441. const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
  11442. if (isa<NamespaceDecl>(DC)) {
  11443. return SemaRef.Diag(FnDecl->getLocation(),
  11444. diag::err_operator_new_delete_declared_in_namespace)
  11445. << FnDecl->getDeclName();
  11446. }
  11447. if (isa<TranslationUnitDecl>(DC) &&
  11448. FnDecl->getStorageClass() == SC_Static) {
  11449. return SemaRef.Diag(FnDecl->getLocation(),
  11450. diag::err_operator_new_delete_declared_static)
  11451. << FnDecl->getDeclName();
  11452. }
  11453. return false;
  11454. }
  11455. static QualType
  11456. RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
  11457. QualType QTy = PtrTy->getPointeeType();
  11458. QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
  11459. return SemaRef.Context.getPointerType(QTy);
  11460. }
  11461. static inline bool
  11462. CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
  11463. CanQualType ExpectedResultType,
  11464. CanQualType ExpectedFirstParamType,
  11465. unsigned DependentParamTypeDiag,
  11466. unsigned InvalidParamTypeDiag) {
  11467. QualType ResultType =
  11468. FnDecl->getType()->getAs<FunctionType>()->getReturnType();
  11469. // Check that the result type is not dependent.
  11470. if (ResultType->isDependentType())
  11471. return SemaRef.Diag(FnDecl->getLocation(),
  11472. diag::err_operator_new_delete_dependent_result_type)
  11473. << FnDecl->getDeclName() << ExpectedResultType;
  11474. // OpenCL C++: the operator is valid on any address space.
  11475. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  11476. if (auto *PtrTy = ResultType->getAs<PointerType>()) {
  11477. ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  11478. }
  11479. }
  11480. // Check that the result type is what we expect.
  11481. if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
  11482. return SemaRef.Diag(FnDecl->getLocation(),
  11483. diag::err_operator_new_delete_invalid_result_type)
  11484. << FnDecl->getDeclName() << ExpectedResultType;
  11485. // A function template must have at least 2 parameters.
  11486. if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
  11487. return SemaRef.Diag(FnDecl->getLocation(),
  11488. diag::err_operator_new_delete_template_too_few_parameters)
  11489. << FnDecl->getDeclName();
  11490. // The function decl must have at least 1 parameter.
  11491. if (FnDecl->getNumParams() == 0)
  11492. return SemaRef.Diag(FnDecl->getLocation(),
  11493. diag::err_operator_new_delete_too_few_parameters)
  11494. << FnDecl->getDeclName();
  11495. // Check the first parameter type is not dependent.
  11496. QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
  11497. if (FirstParamType->isDependentType())
  11498. return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
  11499. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11500. // Check that the first parameter type is what we expect.
  11501. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  11502. // OpenCL C++: the operator is valid on any address space.
  11503. if (auto *PtrTy =
  11504. FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
  11505. FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  11506. }
  11507. }
  11508. if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
  11509. ExpectedFirstParamType)
  11510. return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
  11511. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11512. return false;
  11513. }
  11514. static bool
  11515. CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
  11516. // C++ [basic.stc.dynamic.allocation]p1:
  11517. // A program is ill-formed if an allocation function is declared in a
  11518. // namespace scope other than global scope or declared static in global
  11519. // scope.
  11520. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11521. return true;
  11522. CanQualType SizeTy =
  11523. SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
  11524. // C++ [basic.stc.dynamic.allocation]p1:
  11525. // The return type shall be void*. The first parameter shall have type
  11526. // std::size_t.
  11527. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
  11528. SizeTy,
  11529. diag::err_operator_new_dependent_param_type,
  11530. diag::err_operator_new_param_type))
  11531. return true;
  11532. // C++ [basic.stc.dynamic.allocation]p1:
  11533. // The first parameter shall not have an associated default argument.
  11534. if (FnDecl->getParamDecl(0)->hasDefaultArg())
  11535. return SemaRef.Diag(FnDecl->getLocation(),
  11536. diag::err_operator_new_default_arg)
  11537. << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
  11538. return false;
  11539. }
  11540. static bool
  11541. CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
  11542. // C++ [basic.stc.dynamic.deallocation]p1:
  11543. // A program is ill-formed if deallocation functions are declared in a
  11544. // namespace scope other than global scope or declared static in global
  11545. // scope.
  11546. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11547. return true;
  11548. auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
  11549. // C++ P0722:
  11550. // Within a class C, the first parameter of a destroying operator delete
  11551. // shall be of type C *. The first parameter of any other deallocation
  11552. // function shall be of type void *.
  11553. CanQualType ExpectedFirstParamType =
  11554. MD && MD->isDestroyingOperatorDelete()
  11555. ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
  11556. SemaRef.Context.getRecordType(MD->getParent())))
  11557. : SemaRef.Context.VoidPtrTy;
  11558. // C++ [basic.stc.dynamic.deallocation]p2:
  11559. // Each deallocation function shall return void
  11560. if (CheckOperatorNewDeleteTypes(
  11561. SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
  11562. diag::err_operator_delete_dependent_param_type,
  11563. diag::err_operator_delete_param_type))
  11564. return true;
  11565. // C++ P0722:
  11566. // A destroying operator delete shall be a usual deallocation function.
  11567. if (MD && !MD->getParent()->isDependentContext() &&
  11568. MD->isDestroyingOperatorDelete() &&
  11569. !SemaRef.isUsualDeallocationFunction(MD)) {
  11570. SemaRef.Diag(MD->getLocation(),
  11571. diag::err_destroying_operator_delete_not_usual);
  11572. return true;
  11573. }
  11574. return false;
  11575. }
  11576. /// CheckOverloadedOperatorDeclaration - Check whether the declaration
  11577. /// of this overloaded operator is well-formed. If so, returns false;
  11578. /// otherwise, emits appropriate diagnostics and returns true.
  11579. bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
  11580. assert(FnDecl && FnDecl->isOverloadedOperator() &&
  11581. "Expected an overloaded operator declaration");
  11582. OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
  11583. // C++ [over.oper]p5:
  11584. // The allocation and deallocation functions, operator new,
  11585. // operator new[], operator delete and operator delete[], are
  11586. // described completely in 3.7.3. The attributes and restrictions
  11587. // found in the rest of this subclause do not apply to them unless
  11588. // explicitly stated in 3.7.3.
  11589. if (Op == OO_Delete || Op == OO_Array_Delete)
  11590. return CheckOperatorDeleteDeclaration(*this, FnDecl);
  11591. if (Op == OO_New || Op == OO_Array_New)
  11592. return CheckOperatorNewDeclaration(*this, FnDecl);
  11593. // C++ [over.oper]p6:
  11594. // An operator function shall either be a non-static member
  11595. // function or be a non-member function and have at least one
  11596. // parameter whose type is a class, a reference to a class, an
  11597. // enumeration, or a reference to an enumeration.
  11598. if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
  11599. if (MethodDecl->isStatic())
  11600. return Diag(FnDecl->getLocation(),
  11601. diag::err_operator_overload_static) << FnDecl->getDeclName();
  11602. } else {
  11603. bool ClassOrEnumParam = false;
  11604. for (auto Param : FnDecl->parameters()) {
  11605. QualType ParamType = Param->getType().getNonReferenceType();
  11606. if (ParamType->isDependentType() || ParamType->isRecordType() ||
  11607. ParamType->isEnumeralType()) {
  11608. ClassOrEnumParam = true;
  11609. break;
  11610. }
  11611. }
  11612. if (!ClassOrEnumParam)
  11613. return Diag(FnDecl->getLocation(),
  11614. diag::err_operator_overload_needs_class_or_enum)
  11615. << FnDecl->getDeclName();
  11616. }
  11617. // C++ [over.oper]p8:
  11618. // An operator function cannot have default arguments (8.3.6),
  11619. // except where explicitly stated below.
  11620. //
  11621. // Only the function-call operator allows default arguments
  11622. // (C++ [over.call]p1).
  11623. if (Op != OO_Call) {
  11624. for (auto Param : FnDecl->parameters()) {
  11625. if (Param->hasDefaultArg())
  11626. return Diag(Param->getLocation(),
  11627. diag::err_operator_overload_default_arg)
  11628. << FnDecl->getDeclName() << Param->getDefaultArgRange();
  11629. }
  11630. }
  11631. static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
  11632. { false, false, false }
  11633. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  11634. , { Unary, Binary, MemberOnly }
  11635. #include "clang/Basic/OperatorKinds.def"
  11636. };
  11637. bool CanBeUnaryOperator = OperatorUses[Op][0];
  11638. bool CanBeBinaryOperator = OperatorUses[Op][1];
  11639. bool MustBeMemberOperator = OperatorUses[Op][2];
  11640. // C++ [over.oper]p8:
  11641. // [...] Operator functions cannot have more or fewer parameters
  11642. // than the number required for the corresponding operator, as
  11643. // described in the rest of this subclause.
  11644. unsigned NumParams = FnDecl->getNumParams()
  11645. + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
  11646. if (Op != OO_Call &&
  11647. ((NumParams == 1 && !CanBeUnaryOperator) ||
  11648. (NumParams == 2 && !CanBeBinaryOperator) ||
  11649. (NumParams < 1) || (NumParams > 2))) {
  11650. // We have the wrong number of parameters.
  11651. unsigned ErrorKind;
  11652. if (CanBeUnaryOperator && CanBeBinaryOperator) {
  11653. ErrorKind = 2; // 2 -> unary or binary.
  11654. } else if (CanBeUnaryOperator) {
  11655. ErrorKind = 0; // 0 -> unary
  11656. } else {
  11657. assert(CanBeBinaryOperator &&
  11658. "All non-call overloaded operators are unary or binary!");
  11659. ErrorKind = 1; // 1 -> binary
  11660. }
  11661. return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
  11662. << FnDecl->getDeclName() << NumParams << ErrorKind;
  11663. }
  11664. // Overloaded operators other than operator() cannot be variadic.
  11665. if (Op != OO_Call &&
  11666. FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
  11667. return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
  11668. << FnDecl->getDeclName();
  11669. }
  11670. // Some operators must be non-static member functions.
  11671. if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
  11672. return Diag(FnDecl->getLocation(),
  11673. diag::err_operator_overload_must_be_member)
  11674. << FnDecl->getDeclName();
  11675. }
  11676. // C++ [over.inc]p1:
  11677. // The user-defined function called operator++ implements the
  11678. // prefix and postfix ++ operator. If this function is a member
  11679. // function with no parameters, or a non-member function with one
  11680. // parameter of class or enumeration type, it defines the prefix
  11681. // increment operator ++ for objects of that type. If the function
  11682. // is a member function with one parameter (which shall be of type
  11683. // int) or a non-member function with two parameters (the second
  11684. // of which shall be of type int), it defines the postfix
  11685. // increment operator ++ for objects of that type.
  11686. if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
  11687. ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
  11688. QualType ParamType = LastParam->getType();
  11689. if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
  11690. !ParamType->isDependentType())
  11691. return Diag(LastParam->getLocation(),
  11692. diag::err_operator_overload_post_incdec_must_be_int)
  11693. << LastParam->getType() << (Op == OO_MinusMinus);
  11694. }
  11695. return false;
  11696. }
  11697. static bool
  11698. checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
  11699. FunctionTemplateDecl *TpDecl) {
  11700. TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
  11701. // Must have one or two template parameters.
  11702. if (TemplateParams->size() == 1) {
  11703. NonTypeTemplateParmDecl *PmDecl =
  11704. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
  11705. // The template parameter must be a char parameter pack.
  11706. if (PmDecl && PmDecl->isTemplateParameterPack() &&
  11707. SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
  11708. return false;
  11709. } else if (TemplateParams->size() == 2) {
  11710. TemplateTypeParmDecl *PmType =
  11711. dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
  11712. NonTypeTemplateParmDecl *PmArgs =
  11713. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
  11714. // The second template parameter must be a parameter pack with the
  11715. // first template parameter as its type.
  11716. if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
  11717. PmArgs->isTemplateParameterPack()) {
  11718. const TemplateTypeParmType *TArgs =
  11719. PmArgs->getType()->getAs<TemplateTypeParmType>();
  11720. if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
  11721. TArgs->getIndex() == PmType->getIndex()) {
  11722. if (!SemaRef.inTemplateInstantiation())
  11723. SemaRef.Diag(TpDecl->getLocation(),
  11724. diag::ext_string_literal_operator_template);
  11725. return false;
  11726. }
  11727. }
  11728. }
  11729. SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
  11730. diag::err_literal_operator_template)
  11731. << TpDecl->getTemplateParameters()->getSourceRange();
  11732. return true;
  11733. }
  11734. /// CheckLiteralOperatorDeclaration - Check whether the declaration
  11735. /// of this literal operator function is well-formed. If so, returns
  11736. /// false; otherwise, emits appropriate diagnostics and returns true.
  11737. bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
  11738. if (isa<CXXMethodDecl>(FnDecl)) {
  11739. Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
  11740. << FnDecl->getDeclName();
  11741. return true;
  11742. }
  11743. if (FnDecl->isExternC()) {
  11744. Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
  11745. if (const LinkageSpecDecl *LSD =
  11746. FnDecl->getDeclContext()->getExternCContext())
  11747. Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
  11748. return true;
  11749. }
  11750. // This might be the definition of a literal operator template.
  11751. FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
  11752. // This might be a specialization of a literal operator template.
  11753. if (!TpDecl)
  11754. TpDecl = FnDecl->getPrimaryTemplate();
  11755. // template <char...> type operator "" name() and
  11756. // template <class T, T...> type operator "" name() are the only valid
  11757. // template signatures, and the only valid signatures with no parameters.
  11758. if (TpDecl) {
  11759. if (FnDecl->param_size() != 0) {
  11760. Diag(FnDecl->getLocation(),
  11761. diag::err_literal_operator_template_with_params);
  11762. return true;
  11763. }
  11764. if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
  11765. return true;
  11766. } else if (FnDecl->param_size() == 1) {
  11767. const ParmVarDecl *Param = FnDecl->getParamDecl(0);
  11768. QualType ParamType = Param->getType().getUnqualifiedType();
  11769. // Only unsigned long long int, long double, any character type, and const
  11770. // char * are allowed as the only parameters.
  11771. if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
  11772. ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
  11773. Context.hasSameType(ParamType, Context.CharTy) ||
  11774. Context.hasSameType(ParamType, Context.WideCharTy) ||
  11775. Context.hasSameType(ParamType, Context.Char8Ty) ||
  11776. Context.hasSameType(ParamType, Context.Char16Ty) ||
  11777. Context.hasSameType(ParamType, Context.Char32Ty)) {
  11778. } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
  11779. QualType InnerType = Ptr->getPointeeType();
  11780. // Pointer parameter must be a const char *.
  11781. if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
  11782. Context.CharTy) &&
  11783. InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
  11784. Diag(Param->getSourceRange().getBegin(),
  11785. diag::err_literal_operator_param)
  11786. << ParamType << "'const char *'" << Param->getSourceRange();
  11787. return true;
  11788. }
  11789. } else if (ParamType->isRealFloatingType()) {
  11790. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  11791. << ParamType << Context.LongDoubleTy << Param->getSourceRange();
  11792. return true;
  11793. } else if (ParamType->isIntegerType()) {
  11794. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  11795. << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
  11796. return true;
  11797. } else {
  11798. Diag(Param->getSourceRange().getBegin(),
  11799. diag::err_literal_operator_invalid_param)
  11800. << ParamType << Param->getSourceRange();
  11801. return true;
  11802. }
  11803. } else if (FnDecl->param_size() == 2) {
  11804. FunctionDecl::param_iterator Param = FnDecl->param_begin();
  11805. // First, verify that the first parameter is correct.
  11806. QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
  11807. // Two parameter function must have a pointer to const as a
  11808. // first parameter; let's strip those qualifiers.
  11809. const PointerType *PT = FirstParamType->getAs<PointerType>();
  11810. if (!PT) {
  11811. Diag((*Param)->getSourceRange().getBegin(),
  11812. diag::err_literal_operator_param)
  11813. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11814. return true;
  11815. }
  11816. QualType PointeeType = PT->getPointeeType();
  11817. // First parameter must be const
  11818. if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
  11819. Diag((*Param)->getSourceRange().getBegin(),
  11820. diag::err_literal_operator_param)
  11821. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11822. return true;
  11823. }
  11824. QualType InnerType = PointeeType.getUnqualifiedType();
  11825. // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
  11826. // const char32_t* are allowed as the first parameter to a two-parameter
  11827. // function
  11828. if (!(Context.hasSameType(InnerType, Context.CharTy) ||
  11829. Context.hasSameType(InnerType, Context.WideCharTy) ||
  11830. Context.hasSameType(InnerType, Context.Char8Ty) ||
  11831. Context.hasSameType(InnerType, Context.Char16Ty) ||
  11832. Context.hasSameType(InnerType, Context.Char32Ty))) {
  11833. Diag((*Param)->getSourceRange().getBegin(),
  11834. diag::err_literal_operator_param)
  11835. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11836. return true;
  11837. }
  11838. // Move on to the second and final parameter.
  11839. ++Param;
  11840. // The second parameter must be a std::size_t.
  11841. QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
  11842. if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
  11843. Diag((*Param)->getSourceRange().getBegin(),
  11844. diag::err_literal_operator_param)
  11845. << SecondParamType << Context.getSizeType()
  11846. << (*Param)->getSourceRange();
  11847. return true;
  11848. }
  11849. } else {
  11850. Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
  11851. return true;
  11852. }
  11853. // Parameters are good.
  11854. // A parameter-declaration-clause containing a default argument is not
  11855. // equivalent to any of the permitted forms.
  11856. for (auto Param : FnDecl->parameters()) {
  11857. if (Param->hasDefaultArg()) {
  11858. Diag(Param->getDefaultArgRange().getBegin(),
  11859. diag::err_literal_operator_default_argument)
  11860. << Param->getDefaultArgRange();
  11861. break;
  11862. }
  11863. }
  11864. StringRef LiteralName
  11865. = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
  11866. if (LiteralName[0] != '_' &&
  11867. !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
  11868. // C++11 [usrlit.suffix]p1:
  11869. // Literal suffix identifiers that do not start with an underscore
  11870. // are reserved for future standardization.
  11871. Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
  11872. << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
  11873. }
  11874. return false;
  11875. }
  11876. /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
  11877. /// linkage specification, including the language and (if present)
  11878. /// the '{'. ExternLoc is the location of the 'extern', Lang is the
  11879. /// language string literal. LBraceLoc, if valid, provides the location of
  11880. /// the '{' brace. Otherwise, this linkage specification does not
  11881. /// have any braces.
  11882. Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
  11883. Expr *LangStr,
  11884. SourceLocation LBraceLoc) {
  11885. StringLiteral *Lit = cast<StringLiteral>(LangStr);
  11886. if (!Lit->isAscii()) {
  11887. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
  11888. << LangStr->getSourceRange();
  11889. return nullptr;
  11890. }
  11891. StringRef Lang = Lit->getString();
  11892. LinkageSpecDecl::LanguageIDs Language;
  11893. if (Lang == "C")
  11894. Language = LinkageSpecDecl::lang_c;
  11895. else if (Lang == "C++")
  11896. Language = LinkageSpecDecl::lang_cxx;
  11897. else {
  11898. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
  11899. << LangStr->getSourceRange();
  11900. return nullptr;
  11901. }
  11902. // FIXME: Add all the various semantics of linkage specifications
  11903. LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
  11904. LangStr->getExprLoc(), Language,
  11905. LBraceLoc.isValid());
  11906. CurContext->addDecl(D);
  11907. PushDeclContext(S, D);
  11908. return D;
  11909. }
  11910. /// ActOnFinishLinkageSpecification - Complete the definition of
  11911. /// the C++ linkage specification LinkageSpec. If RBraceLoc is
  11912. /// valid, it's the position of the closing '}' brace in a linkage
  11913. /// specification that uses braces.
  11914. Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
  11915. Decl *LinkageSpec,
  11916. SourceLocation RBraceLoc) {
  11917. if (RBraceLoc.isValid()) {
  11918. LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
  11919. LSDecl->setRBraceLoc(RBraceLoc);
  11920. }
  11921. PopDeclContext();
  11922. return LinkageSpec;
  11923. }
  11924. Decl *Sema::ActOnEmptyDeclaration(Scope *S,
  11925. const ParsedAttributesView &AttrList,
  11926. SourceLocation SemiLoc) {
  11927. Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
  11928. // Attribute declarations appertain to empty declaration so we handle
  11929. // them here.
  11930. ProcessDeclAttributeList(S, ED, AttrList);
  11931. CurContext->addDecl(ED);
  11932. return ED;
  11933. }
  11934. /// Perform semantic analysis for the variable declaration that
  11935. /// occurs within a C++ catch clause, returning the newly-created
  11936. /// variable.
  11937. VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
  11938. TypeSourceInfo *TInfo,
  11939. SourceLocation StartLoc,
  11940. SourceLocation Loc,
  11941. IdentifierInfo *Name) {
  11942. bool Invalid = false;
  11943. QualType ExDeclType = TInfo->getType();
  11944. // Arrays and functions decay.
  11945. if (ExDeclType->isArrayType())
  11946. ExDeclType = Context.getArrayDecayedType(ExDeclType);
  11947. else if (ExDeclType->isFunctionType())
  11948. ExDeclType = Context.getPointerType(ExDeclType);
  11949. // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
  11950. // The exception-declaration shall not denote a pointer or reference to an
  11951. // incomplete type, other than [cv] void*.
  11952. // N2844 forbids rvalue references.
  11953. if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
  11954. Diag(Loc, diag::err_catch_rvalue_ref);
  11955. Invalid = true;
  11956. }
  11957. if (ExDeclType->isVariablyModifiedType()) {
  11958. Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
  11959. Invalid = true;
  11960. }
  11961. QualType BaseType = ExDeclType;
  11962. int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
  11963. unsigned DK = diag::err_catch_incomplete;
  11964. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  11965. BaseType = Ptr->getPointeeType();
  11966. Mode = 1;
  11967. DK = diag::err_catch_incomplete_ptr;
  11968. } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
  11969. // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
  11970. BaseType = Ref->getPointeeType();
  11971. Mode = 2;
  11972. DK = diag::err_catch_incomplete_ref;
  11973. }
  11974. if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
  11975. !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
  11976. Invalid = true;
  11977. if (!Invalid && !ExDeclType->isDependentType() &&
  11978. RequireNonAbstractType(Loc, ExDeclType,
  11979. diag::err_abstract_type_in_decl,
  11980. AbstractVariableType))
  11981. Invalid = true;
  11982. // Only the non-fragile NeXT runtime currently supports C++ catches
  11983. // of ObjC types, and no runtime supports catching ObjC types by value.
  11984. if (!Invalid && getLangOpts().ObjC) {
  11985. QualType T = ExDeclType;
  11986. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  11987. T = RT->getPointeeType();
  11988. if (T->isObjCObjectType()) {
  11989. Diag(Loc, diag::err_objc_object_catch);
  11990. Invalid = true;
  11991. } else if (T->isObjCObjectPointerType()) {
  11992. // FIXME: should this be a test for macosx-fragile specifically?
  11993. if (getLangOpts().ObjCRuntime.isFragile())
  11994. Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
  11995. }
  11996. }
  11997. VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
  11998. ExDeclType, TInfo, SC_None);
  11999. ExDecl->setExceptionVariable(true);
  12000. // In ARC, infer 'retaining' for variables of retainable type.
  12001. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
  12002. Invalid = true;
  12003. if (!Invalid && !ExDeclType->isDependentType()) {
  12004. if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
  12005. // Insulate this from anything else we might currently be parsing.
  12006. EnterExpressionEvaluationContext scope(
  12007. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  12008. // C++ [except.handle]p16:
  12009. // The object declared in an exception-declaration or, if the
  12010. // exception-declaration does not specify a name, a temporary (12.2) is
  12011. // copy-initialized (8.5) from the exception object. [...]
  12012. // The object is destroyed when the handler exits, after the destruction
  12013. // of any automatic objects initialized within the handler.
  12014. //
  12015. // We just pretend to initialize the object with itself, then make sure
  12016. // it can be destroyed later.
  12017. QualType initType = Context.getExceptionObjectType(ExDeclType);
  12018. InitializedEntity entity =
  12019. InitializedEntity::InitializeVariable(ExDecl);
  12020. InitializationKind initKind =
  12021. InitializationKind::CreateCopy(Loc, SourceLocation());
  12022. Expr *opaqueValue =
  12023. new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
  12024. InitializationSequence sequence(*this, entity, initKind, opaqueValue);
  12025. ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
  12026. if (result.isInvalid())
  12027. Invalid = true;
  12028. else {
  12029. // If the constructor used was non-trivial, set this as the
  12030. // "initializer".
  12031. CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
  12032. if (!construct->getConstructor()->isTrivial()) {
  12033. Expr *init = MaybeCreateExprWithCleanups(construct);
  12034. ExDecl->setInit(init);
  12035. }
  12036. // And make sure it's destructable.
  12037. FinalizeVarWithDestructor(ExDecl, recordType);
  12038. }
  12039. }
  12040. }
  12041. if (Invalid)
  12042. ExDecl->setInvalidDecl();
  12043. return ExDecl;
  12044. }
  12045. /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
  12046. /// handler.
  12047. Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
  12048. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12049. bool Invalid = D.isInvalidType();
  12050. // Check for unexpanded parameter packs.
  12051. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  12052. UPPC_ExceptionType)) {
  12053. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  12054. D.getIdentifierLoc());
  12055. Invalid = true;
  12056. }
  12057. IdentifierInfo *II = D.getIdentifier();
  12058. if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
  12059. LookupOrdinaryName,
  12060. ForVisibleRedeclaration)) {
  12061. // The scope should be freshly made just for us. There is just no way
  12062. // it contains any previous declaration, except for function parameters in
  12063. // a function-try-block's catch statement.
  12064. assert(!S->isDeclScope(PrevDecl));
  12065. if (isDeclInScope(PrevDecl, CurContext, S)) {
  12066. Diag(D.getIdentifierLoc(), diag::err_redefinition)
  12067. << D.getIdentifier();
  12068. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  12069. Invalid = true;
  12070. } else if (PrevDecl->isTemplateParameter())
  12071. // Maybe we will complain about the shadowed template parameter.
  12072. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  12073. }
  12074. if (D.getCXXScopeSpec().isSet() && !Invalid) {
  12075. Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
  12076. << D.getCXXScopeSpec().getRange();
  12077. Invalid = true;
  12078. }
  12079. VarDecl *ExDecl = BuildExceptionDeclaration(
  12080. S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
  12081. if (Invalid)
  12082. ExDecl->setInvalidDecl();
  12083. // Add the exception declaration into this scope.
  12084. if (II)
  12085. PushOnScopeChains(ExDecl, S);
  12086. else
  12087. CurContext->addDecl(ExDecl);
  12088. ProcessDeclAttributes(S, ExDecl, D);
  12089. return ExDecl;
  12090. }
  12091. Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  12092. Expr *AssertExpr,
  12093. Expr *AssertMessageExpr,
  12094. SourceLocation RParenLoc) {
  12095. StringLiteral *AssertMessage =
  12096. AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
  12097. if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
  12098. return nullptr;
  12099. return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
  12100. AssertMessage, RParenLoc, false);
  12101. }
  12102. Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  12103. Expr *AssertExpr,
  12104. StringLiteral *AssertMessage,
  12105. SourceLocation RParenLoc,
  12106. bool Failed) {
  12107. assert(AssertExpr != nullptr && "Expected non-null condition");
  12108. if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
  12109. !Failed) {
  12110. // In a static_assert-declaration, the constant-expression shall be a
  12111. // constant expression that can be contextually converted to bool.
  12112. ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
  12113. if (Converted.isInvalid())
  12114. Failed = true;
  12115. llvm::APSInt Cond;
  12116. if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
  12117. diag::err_static_assert_expression_is_not_constant,
  12118. /*AllowFold=*/false).isInvalid())
  12119. Failed = true;
  12120. if (!Failed && !Cond) {
  12121. SmallString<256> MsgBuffer;
  12122. llvm::raw_svector_ostream Msg(MsgBuffer);
  12123. if (AssertMessage)
  12124. AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
  12125. Expr *InnerCond = nullptr;
  12126. std::string InnerCondDescription;
  12127. std::tie(InnerCond, InnerCondDescription) =
  12128. findFailedBooleanCondition(Converted.get());
  12129. if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
  12130. && !isa<IntegerLiteral>(InnerCond)) {
  12131. Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
  12132. << InnerCondDescription << !AssertMessage
  12133. << Msg.str() << InnerCond->getSourceRange();
  12134. } else {
  12135. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  12136. << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
  12137. }
  12138. Failed = true;
  12139. }
  12140. }
  12141. ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
  12142. /*DiscardedValue*/false,
  12143. /*IsConstexpr*/true);
  12144. if (FullAssertExpr.isInvalid())
  12145. Failed = true;
  12146. else
  12147. AssertExpr = FullAssertExpr.get();
  12148. Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
  12149. AssertExpr, AssertMessage, RParenLoc,
  12150. Failed);
  12151. CurContext->addDecl(Decl);
  12152. return Decl;
  12153. }
  12154. /// Perform semantic analysis of the given friend type declaration.
  12155. ///
  12156. /// \returns A friend declaration that.
  12157. FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
  12158. SourceLocation FriendLoc,
  12159. TypeSourceInfo *TSInfo) {
  12160. assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
  12161. QualType T = TSInfo->getType();
  12162. SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
  12163. // C++03 [class.friend]p2:
  12164. // An elaborated-type-specifier shall be used in a friend declaration
  12165. // for a class.*
  12166. //
  12167. // * The class-key of the elaborated-type-specifier is required.
  12168. if (!CodeSynthesisContexts.empty()) {
  12169. // Do not complain about the form of friend template types during any kind
  12170. // of code synthesis. For template instantiation, we will have complained
  12171. // when the template was defined.
  12172. } else {
  12173. if (!T->isElaboratedTypeSpecifier()) {
  12174. // If we evaluated the type to a record type, suggest putting
  12175. // a tag in front.
  12176. if (const RecordType *RT = T->getAs<RecordType>()) {
  12177. RecordDecl *RD = RT->getDecl();
  12178. SmallString<16> InsertionText(" ");
  12179. InsertionText += RD->getKindName();
  12180. Diag(TypeRange.getBegin(),
  12181. getLangOpts().CPlusPlus11 ?
  12182. diag::warn_cxx98_compat_unelaborated_friend_type :
  12183. diag::ext_unelaborated_friend_type)
  12184. << (unsigned) RD->getTagKind()
  12185. << T
  12186. << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
  12187. InsertionText);
  12188. } else {
  12189. Diag(FriendLoc,
  12190. getLangOpts().CPlusPlus11 ?
  12191. diag::warn_cxx98_compat_nonclass_type_friend :
  12192. diag::ext_nonclass_type_friend)
  12193. << T
  12194. << TypeRange;
  12195. }
  12196. } else if (T->getAs<EnumType>()) {
  12197. Diag(FriendLoc,
  12198. getLangOpts().CPlusPlus11 ?
  12199. diag::warn_cxx98_compat_enum_friend :
  12200. diag::ext_enum_friend)
  12201. << T
  12202. << TypeRange;
  12203. }
  12204. // C++11 [class.friend]p3:
  12205. // A friend declaration that does not declare a function shall have one
  12206. // of the following forms:
  12207. // friend elaborated-type-specifier ;
  12208. // friend simple-type-specifier ;
  12209. // friend typename-specifier ;
  12210. if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
  12211. Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
  12212. }
  12213. // If the type specifier in a friend declaration designates a (possibly
  12214. // cv-qualified) class type, that class is declared as a friend; otherwise,
  12215. // the friend declaration is ignored.
  12216. return FriendDecl::Create(Context, CurContext,
  12217. TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
  12218. FriendLoc);
  12219. }
  12220. /// Handle a friend tag declaration where the scope specifier was
  12221. /// templated.
  12222. Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
  12223. unsigned TagSpec, SourceLocation TagLoc,
  12224. CXXScopeSpec &SS, IdentifierInfo *Name,
  12225. SourceLocation NameLoc,
  12226. const ParsedAttributesView &Attr,
  12227. MultiTemplateParamsArg TempParamLists) {
  12228. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12229. bool IsMemberSpecialization = false;
  12230. bool Invalid = false;
  12231. if (TemplateParameterList *TemplateParams =
  12232. MatchTemplateParametersToScopeSpecifier(
  12233. TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
  12234. IsMemberSpecialization, Invalid)) {
  12235. if (TemplateParams->size() > 0) {
  12236. // This is a declaration of a class template.
  12237. if (Invalid)
  12238. return nullptr;
  12239. return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
  12240. NameLoc, Attr, TemplateParams, AS_public,
  12241. /*ModulePrivateLoc=*/SourceLocation(),
  12242. FriendLoc, TempParamLists.size() - 1,
  12243. TempParamLists.data()).get();
  12244. } else {
  12245. // The "template<>" header is extraneous.
  12246. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12247. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12248. IsMemberSpecialization = true;
  12249. }
  12250. }
  12251. if (Invalid) return nullptr;
  12252. bool isAllExplicitSpecializations = true;
  12253. for (unsigned I = TempParamLists.size(); I-- > 0; ) {
  12254. if (TempParamLists[I]->size()) {
  12255. isAllExplicitSpecializations = false;
  12256. break;
  12257. }
  12258. }
  12259. // FIXME: don't ignore attributes.
  12260. // If it's explicit specializations all the way down, just forget
  12261. // about the template header and build an appropriate non-templated
  12262. // friend. TODO: for source fidelity, remember the headers.
  12263. if (isAllExplicitSpecializations) {
  12264. if (SS.isEmpty()) {
  12265. bool Owned = false;
  12266. bool IsDependent = false;
  12267. return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
  12268. Attr, AS_public,
  12269. /*ModulePrivateLoc=*/SourceLocation(),
  12270. MultiTemplateParamsArg(), Owned, IsDependent,
  12271. /*ScopedEnumKWLoc=*/SourceLocation(),
  12272. /*ScopedEnumUsesClassTag=*/false,
  12273. /*UnderlyingType=*/TypeResult(),
  12274. /*IsTypeSpecifier=*/false,
  12275. /*IsTemplateParamOrArg=*/false);
  12276. }
  12277. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  12278. ElaboratedTypeKeyword Keyword
  12279. = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  12280. QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
  12281. *Name, NameLoc);
  12282. if (T.isNull())
  12283. return nullptr;
  12284. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  12285. if (isa<DependentNameType>(T)) {
  12286. DependentNameTypeLoc TL =
  12287. TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  12288. TL.setElaboratedKeywordLoc(TagLoc);
  12289. TL.setQualifierLoc(QualifierLoc);
  12290. TL.setNameLoc(NameLoc);
  12291. } else {
  12292. ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
  12293. TL.setElaboratedKeywordLoc(TagLoc);
  12294. TL.setQualifierLoc(QualifierLoc);
  12295. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
  12296. }
  12297. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  12298. TSI, FriendLoc, TempParamLists);
  12299. Friend->setAccess(AS_public);
  12300. CurContext->addDecl(Friend);
  12301. return Friend;
  12302. }
  12303. assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
  12304. // Handle the case of a templated-scope friend class. e.g.
  12305. // template <class T> class A<T>::B;
  12306. // FIXME: we don't support these right now.
  12307. Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
  12308. << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
  12309. ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  12310. QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
  12311. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  12312. DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  12313. TL.setElaboratedKeywordLoc(TagLoc);
  12314. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  12315. TL.setNameLoc(NameLoc);
  12316. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  12317. TSI, FriendLoc, TempParamLists);
  12318. Friend->setAccess(AS_public);
  12319. Friend->setUnsupportedFriend(true);
  12320. CurContext->addDecl(Friend);
  12321. return Friend;
  12322. }
  12323. /// Handle a friend type declaration. This works in tandem with
  12324. /// ActOnTag.
  12325. ///
  12326. /// Notes on friend class templates:
  12327. ///
  12328. /// We generally treat friend class declarations as if they were
  12329. /// declaring a class. So, for example, the elaborated type specifier
  12330. /// in a friend declaration is required to obey the restrictions of a
  12331. /// class-head (i.e. no typedefs in the scope chain), template
  12332. /// parameters are required to match up with simple template-ids, &c.
  12333. /// However, unlike when declaring a template specialization, it's
  12334. /// okay to refer to a template specialization without an empty
  12335. /// template parameter declaration, e.g.
  12336. /// friend class A<T>::B<unsigned>;
  12337. /// We permit this as a special case; if there are any template
  12338. /// parameters present at all, require proper matching, i.e.
  12339. /// template <> template \<class T> friend class A<int>::B;
  12340. Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
  12341. MultiTemplateParamsArg TempParams) {
  12342. SourceLocation Loc = DS.getBeginLoc();
  12343. assert(DS.isFriendSpecified());
  12344. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  12345. // C++ [class.friend]p3:
  12346. // A friend declaration that does not declare a function shall have one of
  12347. // the following forms:
  12348. // friend elaborated-type-specifier ;
  12349. // friend simple-type-specifier ;
  12350. // friend typename-specifier ;
  12351. //
  12352. // Any declaration with a type qualifier does not have that form. (It's
  12353. // legal to specify a qualified type as a friend, you just can't write the
  12354. // keywords.)
  12355. if (DS.getTypeQualifiers()) {
  12356. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  12357. Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
  12358. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  12359. Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
  12360. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  12361. Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
  12362. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  12363. Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
  12364. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  12365. Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
  12366. }
  12367. // Try to convert the decl specifier to a type. This works for
  12368. // friend templates because ActOnTag never produces a ClassTemplateDecl
  12369. // for a TUK_Friend.
  12370. Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
  12371. TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
  12372. QualType T = TSI->getType();
  12373. if (TheDeclarator.isInvalidType())
  12374. return nullptr;
  12375. if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
  12376. return nullptr;
  12377. // This is definitely an error in C++98. It's probably meant to
  12378. // be forbidden in C++0x, too, but the specification is just
  12379. // poorly written.
  12380. //
  12381. // The problem is with declarations like the following:
  12382. // template <T> friend A<T>::foo;
  12383. // where deciding whether a class C is a friend or not now hinges
  12384. // on whether there exists an instantiation of A that causes
  12385. // 'foo' to equal C. There are restrictions on class-heads
  12386. // (which we declare (by fiat) elaborated friend declarations to
  12387. // be) that makes this tractable.
  12388. //
  12389. // FIXME: handle "template <> friend class A<T>;", which
  12390. // is possibly well-formed? Who even knows?
  12391. if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
  12392. Diag(Loc, diag::err_tagless_friend_type_template)
  12393. << DS.getSourceRange();
  12394. return nullptr;
  12395. }
  12396. // C++98 [class.friend]p1: A friend of a class is a function
  12397. // or class that is not a member of the class . . .
  12398. // This is fixed in DR77, which just barely didn't make the C++03
  12399. // deadline. It's also a very silly restriction that seriously
  12400. // affects inner classes and which nobody else seems to implement;
  12401. // thus we never diagnose it, not even in -pedantic.
  12402. //
  12403. // But note that we could warn about it: it's always useless to
  12404. // friend one of your own members (it's not, however, worthless to
  12405. // friend a member of an arbitrary specialization of your template).
  12406. Decl *D;
  12407. if (!TempParams.empty())
  12408. D = FriendTemplateDecl::Create(Context, CurContext, Loc,
  12409. TempParams,
  12410. TSI,
  12411. DS.getFriendSpecLoc());
  12412. else
  12413. D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
  12414. if (!D)
  12415. return nullptr;
  12416. D->setAccess(AS_public);
  12417. CurContext->addDecl(D);
  12418. return D;
  12419. }
  12420. NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
  12421. MultiTemplateParamsArg TemplateParams) {
  12422. const DeclSpec &DS = D.getDeclSpec();
  12423. assert(DS.isFriendSpecified());
  12424. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  12425. SourceLocation Loc = D.getIdentifierLoc();
  12426. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12427. // C++ [class.friend]p1
  12428. // A friend of a class is a function or class....
  12429. // Note that this sees through typedefs, which is intended.
  12430. // It *doesn't* see through dependent types, which is correct
  12431. // according to [temp.arg.type]p3:
  12432. // If a declaration acquires a function type through a
  12433. // type dependent on a template-parameter and this causes
  12434. // a declaration that does not use the syntactic form of a
  12435. // function declarator to have a function type, the program
  12436. // is ill-formed.
  12437. if (!TInfo->getType()->isFunctionType()) {
  12438. Diag(Loc, diag::err_unexpected_friend);
  12439. // It might be worthwhile to try to recover by creating an
  12440. // appropriate declaration.
  12441. return nullptr;
  12442. }
  12443. // C++ [namespace.memdef]p3
  12444. // - If a friend declaration in a non-local class first declares a
  12445. // class or function, the friend class or function is a member
  12446. // of the innermost enclosing namespace.
  12447. // - The name of the friend is not found by simple name lookup
  12448. // until a matching declaration is provided in that namespace
  12449. // scope (either before or after the class declaration granting
  12450. // friendship).
  12451. // - If a friend function is called, its name may be found by the
  12452. // name lookup that considers functions from namespaces and
  12453. // classes associated with the types of the function arguments.
  12454. // - When looking for a prior declaration of a class or a function
  12455. // declared as a friend, scopes outside the innermost enclosing
  12456. // namespace scope are not considered.
  12457. CXXScopeSpec &SS = D.getCXXScopeSpec();
  12458. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  12459. assert(NameInfo.getName());
  12460. // Check for unexpanded parameter packs.
  12461. if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
  12462. DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
  12463. DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
  12464. return nullptr;
  12465. // The context we found the declaration in, or in which we should
  12466. // create the declaration.
  12467. DeclContext *DC;
  12468. Scope *DCScope = S;
  12469. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  12470. ForExternalRedeclaration);
  12471. // There are five cases here.
  12472. // - There's no scope specifier and we're in a local class. Only look
  12473. // for functions declared in the immediately-enclosing block scope.
  12474. // We recover from invalid scope qualifiers as if they just weren't there.
  12475. FunctionDecl *FunctionContainingLocalClass = nullptr;
  12476. if ((SS.isInvalid() || !SS.isSet()) &&
  12477. (FunctionContainingLocalClass =
  12478. cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
  12479. // C++11 [class.friend]p11:
  12480. // If a friend declaration appears in a local class and the name
  12481. // specified is an unqualified name, a prior declaration is
  12482. // looked up without considering scopes that are outside the
  12483. // innermost enclosing non-class scope. For a friend function
  12484. // declaration, if there is no prior declaration, the program is
  12485. // ill-formed.
  12486. // Find the innermost enclosing non-class scope. This is the block
  12487. // scope containing the local class definition (or for a nested class,
  12488. // the outer local class).
  12489. DCScope = S->getFnParent();
  12490. // Look up the function name in the scope.
  12491. Previous.clear(LookupLocalFriendName);
  12492. LookupName(Previous, S, /*AllowBuiltinCreation*/false);
  12493. if (!Previous.empty()) {
  12494. // All possible previous declarations must have the same context:
  12495. // either they were declared at block scope or they are members of
  12496. // one of the enclosing local classes.
  12497. DC = Previous.getRepresentativeDecl()->getDeclContext();
  12498. } else {
  12499. // This is ill-formed, but provide the context that we would have
  12500. // declared the function in, if we were permitted to, for error recovery.
  12501. DC = FunctionContainingLocalClass;
  12502. }
  12503. adjustContextForLocalExternDecl(DC);
  12504. // C++ [class.friend]p6:
  12505. // A function can be defined in a friend declaration of a class if and
  12506. // only if the class is a non-local class (9.8), the function name is
  12507. // unqualified, and the function has namespace scope.
  12508. if (D.isFunctionDefinition()) {
  12509. Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
  12510. }
  12511. // - There's no scope specifier, in which case we just go to the
  12512. // appropriate scope and look for a function or function template
  12513. // there as appropriate.
  12514. } else if (SS.isInvalid() || !SS.isSet()) {
  12515. // C++11 [namespace.memdef]p3:
  12516. // If the name in a friend declaration is neither qualified nor
  12517. // a template-id and the declaration is a function or an
  12518. // elaborated-type-specifier, the lookup to determine whether
  12519. // the entity has been previously declared shall not consider
  12520. // any scopes outside the innermost enclosing namespace.
  12521. bool isTemplateId =
  12522. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
  12523. // Find the appropriate context according to the above.
  12524. DC = CurContext;
  12525. // Skip class contexts. If someone can cite chapter and verse
  12526. // for this behavior, that would be nice --- it's what GCC and
  12527. // EDG do, and it seems like a reasonable intent, but the spec
  12528. // really only says that checks for unqualified existing
  12529. // declarations should stop at the nearest enclosing namespace,
  12530. // not that they should only consider the nearest enclosing
  12531. // namespace.
  12532. while (DC->isRecord())
  12533. DC = DC->getParent();
  12534. DeclContext *LookupDC = DC;
  12535. while (LookupDC->isTransparentContext())
  12536. LookupDC = LookupDC->getParent();
  12537. while (true) {
  12538. LookupQualifiedName(Previous, LookupDC);
  12539. if (!Previous.empty()) {
  12540. DC = LookupDC;
  12541. break;
  12542. }
  12543. if (isTemplateId) {
  12544. if (isa<TranslationUnitDecl>(LookupDC)) break;
  12545. } else {
  12546. if (LookupDC->isFileContext()) break;
  12547. }
  12548. LookupDC = LookupDC->getParent();
  12549. }
  12550. DCScope = getScopeForDeclContext(S, DC);
  12551. // - There's a non-dependent scope specifier, in which case we
  12552. // compute it and do a previous lookup there for a function
  12553. // or function template.
  12554. } else if (!SS.getScopeRep()->isDependent()) {
  12555. DC = computeDeclContext(SS);
  12556. if (!DC) return nullptr;
  12557. if (RequireCompleteDeclContext(SS, DC)) return nullptr;
  12558. LookupQualifiedName(Previous, DC);
  12559. // C++ [class.friend]p1: A friend of a class is a function or
  12560. // class that is not a member of the class . . .
  12561. if (DC->Equals(CurContext))
  12562. Diag(DS.getFriendSpecLoc(),
  12563. getLangOpts().CPlusPlus11 ?
  12564. diag::warn_cxx98_compat_friend_is_member :
  12565. diag::err_friend_is_member);
  12566. if (D.isFunctionDefinition()) {
  12567. // C++ [class.friend]p6:
  12568. // A function can be defined in a friend declaration of a class if and
  12569. // only if the class is a non-local class (9.8), the function name is
  12570. // unqualified, and the function has namespace scope.
  12571. //
  12572. // FIXME: We should only do this if the scope specifier names the
  12573. // innermost enclosing namespace; otherwise the fixit changes the
  12574. // meaning of the code.
  12575. SemaDiagnosticBuilder DB
  12576. = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
  12577. DB << SS.getScopeRep();
  12578. if (DC->isFileContext())
  12579. DB << FixItHint::CreateRemoval(SS.getRange());
  12580. SS.clear();
  12581. }
  12582. // - There's a scope specifier that does not match any template
  12583. // parameter lists, in which case we use some arbitrary context,
  12584. // create a method or method template, and wait for instantiation.
  12585. // - There's a scope specifier that does match some template
  12586. // parameter lists, which we don't handle right now.
  12587. } else {
  12588. if (D.isFunctionDefinition()) {
  12589. // C++ [class.friend]p6:
  12590. // A function can be defined in a friend declaration of a class if and
  12591. // only if the class is a non-local class (9.8), the function name is
  12592. // unqualified, and the function has namespace scope.
  12593. Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
  12594. << SS.getScopeRep();
  12595. }
  12596. DC = CurContext;
  12597. assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
  12598. }
  12599. if (!DC->isRecord()) {
  12600. int DiagArg = -1;
  12601. switch (D.getName().getKind()) {
  12602. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  12603. case UnqualifiedIdKind::IK_ConstructorName:
  12604. DiagArg = 0;
  12605. break;
  12606. case UnqualifiedIdKind::IK_DestructorName:
  12607. DiagArg = 1;
  12608. break;
  12609. case UnqualifiedIdKind::IK_ConversionFunctionId:
  12610. DiagArg = 2;
  12611. break;
  12612. case UnqualifiedIdKind::IK_DeductionGuideName:
  12613. DiagArg = 3;
  12614. break;
  12615. case UnqualifiedIdKind::IK_Identifier:
  12616. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  12617. case UnqualifiedIdKind::IK_LiteralOperatorId:
  12618. case UnqualifiedIdKind::IK_OperatorFunctionId:
  12619. case UnqualifiedIdKind::IK_TemplateId:
  12620. break;
  12621. }
  12622. // This implies that it has to be an operator or function.
  12623. if (DiagArg >= 0) {
  12624. Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
  12625. return nullptr;
  12626. }
  12627. }
  12628. // FIXME: This is an egregious hack to cope with cases where the scope stack
  12629. // does not contain the declaration context, i.e., in an out-of-line
  12630. // definition of a class.
  12631. Scope FakeDCScope(S, Scope::DeclScope, Diags);
  12632. if (!DCScope) {
  12633. FakeDCScope.setEntity(DC);
  12634. DCScope = &FakeDCScope;
  12635. }
  12636. bool AddToScope = true;
  12637. NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
  12638. TemplateParams, AddToScope);
  12639. if (!ND) return nullptr;
  12640. assert(ND->getLexicalDeclContext() == CurContext);
  12641. // If we performed typo correction, we might have added a scope specifier
  12642. // and changed the decl context.
  12643. DC = ND->getDeclContext();
  12644. // Add the function declaration to the appropriate lookup tables,
  12645. // adjusting the redeclarations list as necessary. We don't
  12646. // want to do this yet if the friending class is dependent.
  12647. //
  12648. // Also update the scope-based lookup if the target context's
  12649. // lookup context is in lexical scope.
  12650. if (!CurContext->isDependentContext()) {
  12651. DC = DC->getRedeclContext();
  12652. DC->makeDeclVisibleInContext(ND);
  12653. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  12654. PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
  12655. }
  12656. FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
  12657. D.getIdentifierLoc(), ND,
  12658. DS.getFriendSpecLoc());
  12659. FrD->setAccess(AS_public);
  12660. CurContext->addDecl(FrD);
  12661. if (ND->isInvalidDecl()) {
  12662. FrD->setInvalidDecl();
  12663. } else {
  12664. if (DC->isRecord()) CheckFriendAccess(ND);
  12665. FunctionDecl *FD;
  12666. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  12667. FD = FTD->getTemplatedDecl();
  12668. else
  12669. FD = cast<FunctionDecl>(ND);
  12670. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
  12671. // default argument expression, that declaration shall be a definition
  12672. // and shall be the only declaration of the function or function
  12673. // template in the translation unit.
  12674. if (functionDeclHasDefaultArgument(FD)) {
  12675. // We can't look at FD->getPreviousDecl() because it may not have been set
  12676. // if we're in a dependent context. If the function is known to be a
  12677. // redeclaration, we will have narrowed Previous down to the right decl.
  12678. if (D.isRedeclaration()) {
  12679. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  12680. Diag(Previous.getRepresentativeDecl()->getLocation(),
  12681. diag::note_previous_declaration);
  12682. } else if (!D.isFunctionDefinition())
  12683. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
  12684. }
  12685. // Mark templated-scope function declarations as unsupported.
  12686. if (FD->getNumTemplateParameterLists() && SS.isValid()) {
  12687. Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
  12688. << SS.getScopeRep() << SS.getRange()
  12689. << cast<CXXRecordDecl>(CurContext);
  12690. FrD->setUnsupportedFriend(true);
  12691. }
  12692. }
  12693. return ND;
  12694. }
  12695. void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
  12696. AdjustDeclIfTemplate(Dcl);
  12697. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
  12698. if (!Fn) {
  12699. Diag(DelLoc, diag::err_deleted_non_function);
  12700. return;
  12701. }
  12702. // Deleted function does not have a body.
  12703. Fn->setWillHaveBody(false);
  12704. if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
  12705. // Don't consider the implicit declaration we generate for explicit
  12706. // specializations. FIXME: Do not generate these implicit declarations.
  12707. if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
  12708. Prev->getPreviousDecl()) &&
  12709. !Prev->isDefined()) {
  12710. Diag(DelLoc, diag::err_deleted_decl_not_first);
  12711. Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
  12712. Prev->isImplicit() ? diag::note_previous_implicit_declaration
  12713. : diag::note_previous_declaration);
  12714. }
  12715. // If the declaration wasn't the first, we delete the function anyway for
  12716. // recovery.
  12717. Fn = Fn->getCanonicalDecl();
  12718. }
  12719. // dllimport/dllexport cannot be deleted.
  12720. if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
  12721. Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
  12722. Fn->setInvalidDecl();
  12723. }
  12724. if (Fn->isDeleted())
  12725. return;
  12726. // See if we're deleting a function which is already known to override a
  12727. // non-deleted virtual function.
  12728. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
  12729. bool IssuedDiagnostic = false;
  12730. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  12731. if (!(*MD->begin_overridden_methods())->isDeleted()) {
  12732. if (!IssuedDiagnostic) {
  12733. Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
  12734. IssuedDiagnostic = true;
  12735. }
  12736. Diag(O->getLocation(), diag::note_overridden_virtual_function);
  12737. }
  12738. }
  12739. // If this function was implicitly deleted because it was defaulted,
  12740. // explain why it was deleted.
  12741. if (IssuedDiagnostic && MD->isDefaulted())
  12742. ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
  12743. /*Diagnose*/true);
  12744. }
  12745. // C++11 [basic.start.main]p3:
  12746. // A program that defines main as deleted [...] is ill-formed.
  12747. if (Fn->isMain())
  12748. Diag(DelLoc, diag::err_deleted_main);
  12749. // C++11 [dcl.fct.def.delete]p4:
  12750. // A deleted function is implicitly inline.
  12751. Fn->setImplicitlyInline();
  12752. Fn->setDeletedAsWritten();
  12753. }
  12754. void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
  12755. CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
  12756. if (MD) {
  12757. if (MD->getParent()->isDependentType()) {
  12758. MD->setDefaulted();
  12759. MD->setExplicitlyDefaulted();
  12760. return;
  12761. }
  12762. CXXSpecialMember Member = getSpecialMember(MD);
  12763. if (Member == CXXInvalid) {
  12764. if (!MD->isInvalidDecl())
  12765. Diag(DefaultLoc, diag::err_default_special_members);
  12766. return;
  12767. }
  12768. MD->setDefaulted();
  12769. MD->setExplicitlyDefaulted();
  12770. // Unset that we will have a body for this function. We might not,
  12771. // if it turns out to be trivial, and we don't need this marking now
  12772. // that we've marked it as defaulted.
  12773. MD->setWillHaveBody(false);
  12774. // If this definition appears within the record, do the checking when
  12775. // the record is complete.
  12776. const FunctionDecl *Primary = MD;
  12777. if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
  12778. // Ask the template instantiation pattern that actually had the
  12779. // '= default' on it.
  12780. Primary = Pattern;
  12781. // If the method was defaulted on its first declaration, we will have
  12782. // already performed the checking in CheckCompletedCXXClass. Such a
  12783. // declaration doesn't trigger an implicit definition.
  12784. if (Primary->getCanonicalDecl()->isDefaulted())
  12785. return;
  12786. CheckExplicitlyDefaultedSpecialMember(MD);
  12787. if (!MD->isInvalidDecl())
  12788. DefineImplicitSpecialMember(*this, MD, DefaultLoc);
  12789. } else {
  12790. Diag(DefaultLoc, diag::err_default_special_members);
  12791. }
  12792. }
  12793. static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
  12794. for (Stmt *SubStmt : S->children()) {
  12795. if (!SubStmt)
  12796. continue;
  12797. if (isa<ReturnStmt>(SubStmt))
  12798. Self.Diag(SubStmt->getBeginLoc(),
  12799. diag::err_return_in_constructor_handler);
  12800. if (!isa<Expr>(SubStmt))
  12801. SearchForReturnInStmt(Self, SubStmt);
  12802. }
  12803. }
  12804. void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
  12805. for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
  12806. CXXCatchStmt *Handler = TryBlock->getHandler(I);
  12807. SearchForReturnInStmt(*this, Handler);
  12808. }
  12809. }
  12810. bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  12811. const CXXMethodDecl *Old) {
  12812. const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
  12813. const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
  12814. if (OldFT->hasExtParameterInfos()) {
  12815. for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
  12816. // A parameter of the overriding method should be annotated with noescape
  12817. // if the corresponding parameter of the overridden method is annotated.
  12818. if (OldFT->getExtParameterInfo(I).isNoEscape() &&
  12819. !NewFT->getExtParameterInfo(I).isNoEscape()) {
  12820. Diag(New->getParamDecl(I)->getLocation(),
  12821. diag::warn_overriding_method_missing_noescape);
  12822. Diag(Old->getParamDecl(I)->getLocation(),
  12823. diag::note_overridden_marked_noescape);
  12824. }
  12825. }
  12826. // Virtual overrides must have the same code_seg.
  12827. const auto *OldCSA = Old->getAttr<CodeSegAttr>();
  12828. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  12829. if ((NewCSA || OldCSA) &&
  12830. (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
  12831. Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
  12832. Diag(Old->getLocation(), diag::note_previous_declaration);
  12833. return true;
  12834. }
  12835. CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
  12836. // If the calling conventions match, everything is fine
  12837. if (NewCC == OldCC)
  12838. return false;
  12839. // If the calling conventions mismatch because the new function is static,
  12840. // suppress the calling convention mismatch error; the error about static
  12841. // function override (err_static_overrides_virtual from
  12842. // Sema::CheckFunctionDeclaration) is more clear.
  12843. if (New->getStorageClass() == SC_Static)
  12844. return false;
  12845. Diag(New->getLocation(),
  12846. diag::err_conflicting_overriding_cc_attributes)
  12847. << New->getDeclName() << New->getType() << Old->getType();
  12848. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  12849. return true;
  12850. }
  12851. bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
  12852. const CXXMethodDecl *Old) {
  12853. QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
  12854. QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
  12855. if (Context.hasSameType(NewTy, OldTy) ||
  12856. NewTy->isDependentType() || OldTy->isDependentType())
  12857. return false;
  12858. // Check if the return types are covariant
  12859. QualType NewClassTy, OldClassTy;
  12860. /// Both types must be pointers or references to classes.
  12861. if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
  12862. if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
  12863. NewClassTy = NewPT->getPointeeType();
  12864. OldClassTy = OldPT->getPointeeType();
  12865. }
  12866. } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
  12867. if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
  12868. if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
  12869. NewClassTy = NewRT->getPointeeType();
  12870. OldClassTy = OldRT->getPointeeType();
  12871. }
  12872. }
  12873. }
  12874. // The return types aren't either both pointers or references to a class type.
  12875. if (NewClassTy.isNull()) {
  12876. Diag(New->getLocation(),
  12877. diag::err_different_return_type_for_overriding_virtual_function)
  12878. << New->getDeclName() << NewTy << OldTy
  12879. << New->getReturnTypeSourceRange();
  12880. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12881. << Old->getReturnTypeSourceRange();
  12882. return true;
  12883. }
  12884. if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
  12885. // C++14 [class.virtual]p8:
  12886. // If the class type in the covariant return type of D::f differs from
  12887. // that of B::f, the class type in the return type of D::f shall be
  12888. // complete at the point of declaration of D::f or shall be the class
  12889. // type D.
  12890. if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
  12891. if (!RT->isBeingDefined() &&
  12892. RequireCompleteType(New->getLocation(), NewClassTy,
  12893. diag::err_covariant_return_incomplete,
  12894. New->getDeclName()))
  12895. return true;
  12896. }
  12897. // Check if the new class derives from the old class.
  12898. if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
  12899. Diag(New->getLocation(), diag::err_covariant_return_not_derived)
  12900. << New->getDeclName() << NewTy << OldTy
  12901. << New->getReturnTypeSourceRange();
  12902. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12903. << Old->getReturnTypeSourceRange();
  12904. return true;
  12905. }
  12906. // Check if we the conversion from derived to base is valid.
  12907. if (CheckDerivedToBaseConversion(
  12908. NewClassTy, OldClassTy,
  12909. diag::err_covariant_return_inaccessible_base,
  12910. diag::err_covariant_return_ambiguous_derived_to_base_conv,
  12911. New->getLocation(), New->getReturnTypeSourceRange(),
  12912. New->getDeclName(), nullptr)) {
  12913. // FIXME: this note won't trigger for delayed access control
  12914. // diagnostics, and it's impossible to get an undelayed error
  12915. // here from access control during the original parse because
  12916. // the ParsingDeclSpec/ParsingDeclarator are still in scope.
  12917. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12918. << Old->getReturnTypeSourceRange();
  12919. return true;
  12920. }
  12921. }
  12922. // The qualifiers of the return types must be the same.
  12923. if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
  12924. Diag(New->getLocation(),
  12925. diag::err_covariant_return_type_different_qualifications)
  12926. << New->getDeclName() << NewTy << OldTy
  12927. << New->getReturnTypeSourceRange();
  12928. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12929. << Old->getReturnTypeSourceRange();
  12930. return true;
  12931. }
  12932. // The new class type must have the same or less qualifiers as the old type.
  12933. if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
  12934. Diag(New->getLocation(),
  12935. diag::err_covariant_return_type_class_type_more_qualified)
  12936. << New->getDeclName() << NewTy << OldTy
  12937. << New->getReturnTypeSourceRange();
  12938. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12939. << Old->getReturnTypeSourceRange();
  12940. return true;
  12941. }
  12942. return false;
  12943. }
  12944. /// Mark the given method pure.
  12945. ///
  12946. /// \param Method the method to be marked pure.
  12947. ///
  12948. /// \param InitRange the source range that covers the "0" initializer.
  12949. bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
  12950. SourceLocation EndLoc = InitRange.getEnd();
  12951. if (EndLoc.isValid())
  12952. Method->setRangeEnd(EndLoc);
  12953. if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
  12954. Method->setPure();
  12955. return false;
  12956. }
  12957. if (!Method->isInvalidDecl())
  12958. Diag(Method->getLocation(), diag::err_non_virtual_pure)
  12959. << Method->getDeclName() << InitRange;
  12960. return true;
  12961. }
  12962. void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
  12963. if (D->getFriendObjectKind())
  12964. Diag(D->getLocation(), diag::err_pure_friend);
  12965. else if (auto *M = dyn_cast<CXXMethodDecl>(D))
  12966. CheckPureMethod(M, ZeroLoc);
  12967. else
  12968. Diag(D->getLocation(), diag::err_illegal_initializer);
  12969. }
  12970. /// Determine whether the given declaration is a global variable or
  12971. /// static data member.
  12972. static bool isNonlocalVariable(const Decl *D) {
  12973. if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
  12974. return Var->hasGlobalStorage();
  12975. return false;
  12976. }
  12977. /// Invoked when we are about to parse an initializer for the declaration
  12978. /// 'Dcl'.
  12979. ///
  12980. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
  12981. /// static data member of class X, names should be looked up in the scope of
  12982. /// class X. If the declaration had a scope specifier, a scope will have
  12983. /// been created and passed in for this purpose. Otherwise, S will be null.
  12984. void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
  12985. // If there is no declaration, there was an error parsing it.
  12986. if (!D || D->isInvalidDecl())
  12987. return;
  12988. // We will always have a nested name specifier here, but this declaration
  12989. // might not be out of line if the specifier names the current namespace:
  12990. // extern int n;
  12991. // int ::n = 0;
  12992. if (S && D->isOutOfLine())
  12993. EnterDeclaratorContext(S, D->getDeclContext());
  12994. // If we are parsing the initializer for a static data member, push a
  12995. // new expression evaluation context that is associated with this static
  12996. // data member.
  12997. if (isNonlocalVariable(D))
  12998. PushExpressionEvaluationContext(
  12999. ExpressionEvaluationContext::PotentiallyEvaluated, D);
  13000. }
  13001. /// Invoked after we are finished parsing an initializer for the declaration D.
  13002. void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
  13003. // If there is no declaration, there was an error parsing it.
  13004. if (!D || D->isInvalidDecl())
  13005. return;
  13006. if (isNonlocalVariable(D))
  13007. PopExpressionEvaluationContext();
  13008. if (S && D->isOutOfLine())
  13009. ExitDeclaratorContext(S);
  13010. }
  13011. /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
  13012. /// C++ if/switch/while/for statement.
  13013. /// e.g: "if (int x = f()) {...}"
  13014. DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
  13015. // C++ 6.4p2:
  13016. // The declarator shall not specify a function or an array.
  13017. // The type-specifier-seq shall not contain typedef and shall not declare a
  13018. // new class or enumeration.
  13019. assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  13020. "Parser allowed 'typedef' as storage class of condition decl.");
  13021. Decl *Dcl = ActOnDeclarator(S, D);
  13022. if (!Dcl)
  13023. return true;
  13024. if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
  13025. Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
  13026. << D.getSourceRange();
  13027. return true;
  13028. }
  13029. return Dcl;
  13030. }
  13031. void Sema::LoadExternalVTableUses() {
  13032. if (!ExternalSource)
  13033. return;
  13034. SmallVector<ExternalVTableUse, 4> VTables;
  13035. ExternalSource->ReadUsedVTables(VTables);
  13036. SmallVector<VTableUse, 4> NewUses;
  13037. for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
  13038. llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
  13039. = VTablesUsed.find(VTables[I].Record);
  13040. // Even if a definition wasn't required before, it may be required now.
  13041. if (Pos != VTablesUsed.end()) {
  13042. if (!Pos->second && VTables[I].DefinitionRequired)
  13043. Pos->second = true;
  13044. continue;
  13045. }
  13046. VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
  13047. NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
  13048. }
  13049. VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
  13050. }
  13051. void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
  13052. bool DefinitionRequired) {
  13053. // Ignore any vtable uses in unevaluated operands or for classes that do
  13054. // not have a vtable.
  13055. if (!Class->isDynamicClass() || Class->isDependentContext() ||
  13056. CurContext->isDependentContext() || isUnevaluatedContext())
  13057. return;
  13058. // Do not mark as used if compiling for the device outside of the target
  13059. // region.
  13060. if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  13061. !isInOpenMPDeclareTargetContext() &&
  13062. !isInOpenMPTargetExecutionDirective()) {
  13063. if (!DefinitionRequired)
  13064. MarkVirtualMembersReferenced(Loc, Class);
  13065. return;
  13066. }
  13067. // Try to insert this class into the map.
  13068. LoadExternalVTableUses();
  13069. Class = Class->getCanonicalDecl();
  13070. std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
  13071. Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
  13072. if (!Pos.second) {
  13073. // If we already had an entry, check to see if we are promoting this vtable
  13074. // to require a definition. If so, we need to reappend to the VTableUses
  13075. // list, since we may have already processed the first entry.
  13076. if (DefinitionRequired && !Pos.first->second) {
  13077. Pos.first->second = true;
  13078. } else {
  13079. // Otherwise, we can early exit.
  13080. return;
  13081. }
  13082. } else {
  13083. // The Microsoft ABI requires that we perform the destructor body
  13084. // checks (i.e. operator delete() lookup) when the vtable is marked used, as
  13085. // the deleting destructor is emitted with the vtable, not with the
  13086. // destructor definition as in the Itanium ABI.
  13087. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  13088. CXXDestructorDecl *DD = Class->getDestructor();
  13089. if (DD && DD->isVirtual() && !DD->isDeleted()) {
  13090. if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
  13091. // If this is an out-of-line declaration, marking it referenced will
  13092. // not do anything. Manually call CheckDestructor to look up operator
  13093. // delete().
  13094. ContextRAII SavedContext(*this, DD);
  13095. CheckDestructor(DD);
  13096. } else {
  13097. MarkFunctionReferenced(Loc, Class->getDestructor());
  13098. }
  13099. }
  13100. }
  13101. }
  13102. // Local classes need to have their virtual members marked
  13103. // immediately. For all other classes, we mark their virtual members
  13104. // at the end of the translation unit.
  13105. if (Class->isLocalClass())
  13106. MarkVirtualMembersReferenced(Loc, Class);
  13107. else
  13108. VTableUses.push_back(std::make_pair(Class, Loc));
  13109. }
  13110. bool Sema::DefineUsedVTables() {
  13111. LoadExternalVTableUses();
  13112. if (VTableUses.empty())
  13113. return false;
  13114. // Note: The VTableUses vector could grow as a result of marking
  13115. // the members of a class as "used", so we check the size each
  13116. // time through the loop and prefer indices (which are stable) to
  13117. // iterators (which are not).
  13118. bool DefinedAnything = false;
  13119. for (unsigned I = 0; I != VTableUses.size(); ++I) {
  13120. CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
  13121. if (!Class)
  13122. continue;
  13123. TemplateSpecializationKind ClassTSK =
  13124. Class->getTemplateSpecializationKind();
  13125. SourceLocation Loc = VTableUses[I].second;
  13126. bool DefineVTable = true;
  13127. // If this class has a key function, but that key function is
  13128. // defined in another translation unit, we don't need to emit the
  13129. // vtable even though we're using it.
  13130. const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
  13131. if (KeyFunction && !KeyFunction->hasBody()) {
  13132. // The key function is in another translation unit.
  13133. DefineVTable = false;
  13134. TemplateSpecializationKind TSK =
  13135. KeyFunction->getTemplateSpecializationKind();
  13136. assert(TSK != TSK_ExplicitInstantiationDefinition &&
  13137. TSK != TSK_ImplicitInstantiation &&
  13138. "Instantiations don't have key functions");
  13139. (void)TSK;
  13140. } else if (!KeyFunction) {
  13141. // If we have a class with no key function that is the subject
  13142. // of an explicit instantiation declaration, suppress the
  13143. // vtable; it will live with the explicit instantiation
  13144. // definition.
  13145. bool IsExplicitInstantiationDeclaration =
  13146. ClassTSK == TSK_ExplicitInstantiationDeclaration;
  13147. for (auto R : Class->redecls()) {
  13148. TemplateSpecializationKind TSK
  13149. = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
  13150. if (TSK == TSK_ExplicitInstantiationDeclaration)
  13151. IsExplicitInstantiationDeclaration = true;
  13152. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  13153. IsExplicitInstantiationDeclaration = false;
  13154. break;
  13155. }
  13156. }
  13157. if (IsExplicitInstantiationDeclaration)
  13158. DefineVTable = false;
  13159. }
  13160. // The exception specifications for all virtual members may be needed even
  13161. // if we are not providing an authoritative form of the vtable in this TU.
  13162. // We may choose to emit it available_externally anyway.
  13163. if (!DefineVTable) {
  13164. MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
  13165. continue;
  13166. }
  13167. // Mark all of the virtual members of this class as referenced, so
  13168. // that we can build a vtable. Then, tell the AST consumer that a
  13169. // vtable for this class is required.
  13170. DefinedAnything = true;
  13171. MarkVirtualMembersReferenced(Loc, Class);
  13172. CXXRecordDecl *Canonical = Class->getCanonicalDecl();
  13173. if (VTablesUsed[Canonical])
  13174. Consumer.HandleVTable(Class);
  13175. // Warn if we're emitting a weak vtable. The vtable will be weak if there is
  13176. // no key function or the key function is inlined. Don't warn in C++ ABIs
  13177. // that lack key functions, since the user won't be able to make one.
  13178. if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
  13179. Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
  13180. const FunctionDecl *KeyFunctionDef = nullptr;
  13181. if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
  13182. KeyFunctionDef->isInlined())) {
  13183. Diag(Class->getLocation(),
  13184. ClassTSK == TSK_ExplicitInstantiationDefinition
  13185. ? diag::warn_weak_template_vtable
  13186. : diag::warn_weak_vtable)
  13187. << Class;
  13188. }
  13189. }
  13190. }
  13191. VTableUses.clear();
  13192. return DefinedAnything;
  13193. }
  13194. void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
  13195. const CXXRecordDecl *RD) {
  13196. for (const auto *I : RD->methods())
  13197. if (I->isVirtual() && !I->isPure())
  13198. ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
  13199. }
  13200. void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
  13201. const CXXRecordDecl *RD,
  13202. bool ConstexprOnly) {
  13203. // Mark all functions which will appear in RD's vtable as used.
  13204. CXXFinalOverriderMap FinalOverriders;
  13205. RD->getFinalOverriders(FinalOverriders);
  13206. for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
  13207. E = FinalOverriders.end();
  13208. I != E; ++I) {
  13209. for (OverridingMethods::const_iterator OI = I->second.begin(),
  13210. OE = I->second.end();
  13211. OI != OE; ++OI) {
  13212. assert(OI->second.size() > 0 && "no final overrider");
  13213. CXXMethodDecl *Overrider = OI->second.front().Method;
  13214. // C++ [basic.def.odr]p2:
  13215. // [...] A virtual member function is used if it is not pure. [...]
  13216. if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
  13217. MarkFunctionReferenced(Loc, Overrider);
  13218. }
  13219. }
  13220. // Only classes that have virtual bases need a VTT.
  13221. if (RD->getNumVBases() == 0)
  13222. return;
  13223. for (const auto &I : RD->bases()) {
  13224. const CXXRecordDecl *Base =
  13225. cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  13226. if (Base->getNumVBases() == 0)
  13227. continue;
  13228. MarkVirtualMembersReferenced(Loc, Base);
  13229. }
  13230. }
  13231. /// SetIvarInitializers - This routine builds initialization ASTs for the
  13232. /// Objective-C implementation whose ivars need be initialized.
  13233. void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
  13234. if (!getLangOpts().CPlusPlus)
  13235. return;
  13236. if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
  13237. SmallVector<ObjCIvarDecl*, 8> ivars;
  13238. CollectIvarsToConstructOrDestruct(OID, ivars);
  13239. if (ivars.empty())
  13240. return;
  13241. SmallVector<CXXCtorInitializer*, 32> AllToInit;
  13242. for (unsigned i = 0; i < ivars.size(); i++) {
  13243. FieldDecl *Field = ivars[i];
  13244. if (Field->isInvalidDecl())
  13245. continue;
  13246. CXXCtorInitializer *Member;
  13247. InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
  13248. InitializationKind InitKind =
  13249. InitializationKind::CreateDefault(ObjCImplementation->getLocation());
  13250. InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
  13251. ExprResult MemberInit =
  13252. InitSeq.Perform(*this, InitEntity, InitKind, None);
  13253. MemberInit = MaybeCreateExprWithCleanups(MemberInit);
  13254. // Note, MemberInit could actually come back empty if no initialization
  13255. // is required (e.g., because it would call a trivial default constructor)
  13256. if (!MemberInit.get() || MemberInit.isInvalid())
  13257. continue;
  13258. Member =
  13259. new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
  13260. SourceLocation(),
  13261. MemberInit.getAs<Expr>(),
  13262. SourceLocation());
  13263. AllToInit.push_back(Member);
  13264. // Be sure that the destructor is accessible and is marked as referenced.
  13265. if (const RecordType *RecordTy =
  13266. Context.getBaseElementType(Field->getType())
  13267. ->getAs<RecordType>()) {
  13268. CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  13269. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  13270. MarkFunctionReferenced(Field->getLocation(), Destructor);
  13271. CheckDestructorAccess(Field->getLocation(), Destructor,
  13272. PDiag(diag::err_access_dtor_ivar)
  13273. << Context.getBaseElementType(Field->getType()));
  13274. }
  13275. }
  13276. }
  13277. ObjCImplementation->setIvarInitializers(Context,
  13278. AllToInit.data(), AllToInit.size());
  13279. }
  13280. }
  13281. static
  13282. void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
  13283. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
  13284. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
  13285. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
  13286. Sema &S) {
  13287. if (Ctor->isInvalidDecl())
  13288. return;
  13289. CXXConstructorDecl *Target = Ctor->getTargetConstructor();
  13290. // Target may not be determinable yet, for instance if this is a dependent
  13291. // call in an uninstantiated template.
  13292. if (Target) {
  13293. const FunctionDecl *FNTarget = nullptr;
  13294. (void)Target->hasBody(FNTarget);
  13295. Target = const_cast<CXXConstructorDecl*>(
  13296. cast_or_null<CXXConstructorDecl>(FNTarget));
  13297. }
  13298. CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
  13299. // Avoid dereferencing a null pointer here.
  13300. *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
  13301. if (!Current.insert(Canonical).second)
  13302. return;
  13303. // We know that beyond here, we aren't chaining into a cycle.
  13304. if (!Target || !Target->isDelegatingConstructor() ||
  13305. Target->isInvalidDecl() || Valid.count(TCanonical)) {
  13306. Valid.insert(Current.begin(), Current.end());
  13307. Current.clear();
  13308. // We've hit a cycle.
  13309. } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
  13310. Current.count(TCanonical)) {
  13311. // If we haven't diagnosed this cycle yet, do so now.
  13312. if (!Invalid.count(TCanonical)) {
  13313. S.Diag((*Ctor->init_begin())->getSourceLocation(),
  13314. diag::warn_delegating_ctor_cycle)
  13315. << Ctor;
  13316. // Don't add a note for a function delegating directly to itself.
  13317. if (TCanonical != Canonical)
  13318. S.Diag(Target->getLocation(), diag::note_it_delegates_to);
  13319. CXXConstructorDecl *C = Target;
  13320. while (C->getCanonicalDecl() != Canonical) {
  13321. const FunctionDecl *FNTarget = nullptr;
  13322. (void)C->getTargetConstructor()->hasBody(FNTarget);
  13323. assert(FNTarget && "Ctor cycle through bodiless function");
  13324. C = const_cast<CXXConstructorDecl*>(
  13325. cast<CXXConstructorDecl>(FNTarget));
  13326. S.Diag(C->getLocation(), diag::note_which_delegates_to);
  13327. }
  13328. }
  13329. Invalid.insert(Current.begin(), Current.end());
  13330. Current.clear();
  13331. } else {
  13332. DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
  13333. }
  13334. }
  13335. void Sema::CheckDelegatingCtorCycles() {
  13336. llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
  13337. for (DelegatingCtorDeclsType::iterator
  13338. I = DelegatingCtorDecls.begin(ExternalSource),
  13339. E = DelegatingCtorDecls.end();
  13340. I != E; ++I)
  13341. DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
  13342. for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
  13343. (*CI)->setInvalidDecl();
  13344. }
  13345. namespace {
  13346. /// AST visitor that finds references to the 'this' expression.
  13347. class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
  13348. Sema &S;
  13349. public:
  13350. explicit FindCXXThisExpr(Sema &S) : S(S) { }
  13351. bool VisitCXXThisExpr(CXXThisExpr *E) {
  13352. S.Diag(E->getLocation(), diag::err_this_static_member_func)
  13353. << E->isImplicit();
  13354. return false;
  13355. }
  13356. };
  13357. }
  13358. bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
  13359. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  13360. if (!TSInfo)
  13361. return false;
  13362. TypeLoc TL = TSInfo->getTypeLoc();
  13363. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  13364. if (!ProtoTL)
  13365. return false;
  13366. // C++11 [expr.prim.general]p3:
  13367. // [The expression this] shall not appear before the optional
  13368. // cv-qualifier-seq and it shall not appear within the declaration of a
  13369. // static member function (although its type and value category are defined
  13370. // within a static member function as they are within a non-static member
  13371. // function). [ Note: this is because declaration matching does not occur
  13372. // until the complete declarator is known. - end note ]
  13373. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  13374. FindCXXThisExpr Finder(*this);
  13375. // If the return type came after the cv-qualifier-seq, check it now.
  13376. if (Proto->hasTrailingReturn() &&
  13377. !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
  13378. return true;
  13379. // Check the exception specification.
  13380. if (checkThisInStaticMemberFunctionExceptionSpec(Method))
  13381. return true;
  13382. return checkThisInStaticMemberFunctionAttributes(Method);
  13383. }
  13384. bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
  13385. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  13386. if (!TSInfo)
  13387. return false;
  13388. TypeLoc TL = TSInfo->getTypeLoc();
  13389. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  13390. if (!ProtoTL)
  13391. return false;
  13392. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  13393. FindCXXThisExpr Finder(*this);
  13394. switch (Proto->getExceptionSpecType()) {
  13395. case EST_Unparsed:
  13396. case EST_Uninstantiated:
  13397. case EST_Unevaluated:
  13398. case EST_BasicNoexcept:
  13399. case EST_NoThrow:
  13400. case EST_DynamicNone:
  13401. case EST_MSAny:
  13402. case EST_None:
  13403. break;
  13404. case EST_DependentNoexcept:
  13405. case EST_NoexceptFalse:
  13406. case EST_NoexceptTrue:
  13407. if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
  13408. return true;
  13409. LLVM_FALLTHROUGH;
  13410. case EST_Dynamic:
  13411. for (const auto &E : Proto->exceptions()) {
  13412. if (!Finder.TraverseType(E))
  13413. return true;
  13414. }
  13415. break;
  13416. }
  13417. return false;
  13418. }
  13419. bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
  13420. FindCXXThisExpr Finder(*this);
  13421. // Check attributes.
  13422. for (const auto *A : Method->attrs()) {
  13423. // FIXME: This should be emitted by tblgen.
  13424. Expr *Arg = nullptr;
  13425. ArrayRef<Expr *> Args;
  13426. if (const auto *G = dyn_cast<GuardedByAttr>(A))
  13427. Arg = G->getArg();
  13428. else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
  13429. Arg = G->getArg();
  13430. else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
  13431. Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
  13432. else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
  13433. Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
  13434. else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
  13435. Arg = ETLF->getSuccessValue();
  13436. Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
  13437. } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
  13438. Arg = STLF->getSuccessValue();
  13439. Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
  13440. } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
  13441. Arg = LR->getArg();
  13442. else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
  13443. Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
  13444. else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
  13445. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  13446. else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
  13447. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  13448. else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
  13449. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  13450. else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
  13451. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  13452. if (Arg && !Finder.TraverseStmt(Arg))
  13453. return true;
  13454. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  13455. if (!Finder.TraverseStmt(Args[I]))
  13456. return true;
  13457. }
  13458. }
  13459. return false;
  13460. }
  13461. void Sema::checkExceptionSpecification(
  13462. bool IsTopLevel, ExceptionSpecificationType EST,
  13463. ArrayRef<ParsedType> DynamicExceptions,
  13464. ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
  13465. SmallVectorImpl<QualType> &Exceptions,
  13466. FunctionProtoType::ExceptionSpecInfo &ESI) {
  13467. Exceptions.clear();
  13468. ESI.Type = EST;
  13469. if (EST == EST_Dynamic) {
  13470. Exceptions.reserve(DynamicExceptions.size());
  13471. for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
  13472. // FIXME: Preserve type source info.
  13473. QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
  13474. if (IsTopLevel) {
  13475. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  13476. collectUnexpandedParameterPacks(ET, Unexpanded);
  13477. if (!Unexpanded.empty()) {
  13478. DiagnoseUnexpandedParameterPacks(
  13479. DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
  13480. Unexpanded);
  13481. continue;
  13482. }
  13483. }
  13484. // Check that the type is valid for an exception spec, and
  13485. // drop it if not.
  13486. if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
  13487. Exceptions.push_back(ET);
  13488. }
  13489. ESI.Exceptions = Exceptions;
  13490. return;
  13491. }
  13492. if (isComputedNoexcept(EST)) {
  13493. assert((NoexceptExpr->isTypeDependent() ||
  13494. NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
  13495. Context.BoolTy) &&
  13496. "Parser should have made sure that the expression is boolean");
  13497. if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
  13498. ESI.Type = EST_BasicNoexcept;
  13499. return;
  13500. }
  13501. ESI.NoexceptExpr = NoexceptExpr;
  13502. return;
  13503. }
  13504. }
  13505. void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
  13506. ExceptionSpecificationType EST,
  13507. SourceRange SpecificationRange,
  13508. ArrayRef<ParsedType> DynamicExceptions,
  13509. ArrayRef<SourceRange> DynamicExceptionRanges,
  13510. Expr *NoexceptExpr) {
  13511. if (!MethodD)
  13512. return;
  13513. // Dig out the method we're referring to.
  13514. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
  13515. MethodD = FunTmpl->getTemplatedDecl();
  13516. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
  13517. if (!Method)
  13518. return;
  13519. // Check the exception specification.
  13520. llvm::SmallVector<QualType, 4> Exceptions;
  13521. FunctionProtoType::ExceptionSpecInfo ESI;
  13522. checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
  13523. DynamicExceptionRanges, NoexceptExpr, Exceptions,
  13524. ESI);
  13525. // Update the exception specification on the function type.
  13526. Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
  13527. if (Method->isStatic())
  13528. checkThisInStaticMemberFunctionExceptionSpec(Method);
  13529. if (Method->isVirtual()) {
  13530. // Check overrides, which we previously had to delay.
  13531. for (const CXXMethodDecl *O : Method->overridden_methods())
  13532. CheckOverridingFunctionExceptionSpec(Method, O);
  13533. }
  13534. }
  13535. /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
  13536. ///
  13537. MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
  13538. SourceLocation DeclStart, Declarator &D,
  13539. Expr *BitWidth,
  13540. InClassInitStyle InitStyle,
  13541. AccessSpecifier AS,
  13542. const ParsedAttr &MSPropertyAttr) {
  13543. IdentifierInfo *II = D.getIdentifier();
  13544. if (!II) {
  13545. Diag(DeclStart, diag::err_anonymous_property);
  13546. return nullptr;
  13547. }
  13548. SourceLocation Loc = D.getIdentifierLoc();
  13549. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13550. QualType T = TInfo->getType();
  13551. if (getLangOpts().CPlusPlus) {
  13552. CheckExtraCXXDefaultArguments(D);
  13553. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  13554. UPPC_DataMemberType)) {
  13555. D.setInvalidType();
  13556. T = Context.IntTy;
  13557. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  13558. }
  13559. }
  13560. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  13561. if (D.getDeclSpec().isInlineSpecified())
  13562. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13563. << getLangOpts().CPlusPlus17;
  13564. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13565. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13566. diag::err_invalid_thread)
  13567. << DeclSpec::getSpecifierName(TSCS);
  13568. // Check to see if this name was declared as a member previously
  13569. NamedDecl *PrevDecl = nullptr;
  13570. LookupResult Previous(*this, II, Loc, LookupMemberName,
  13571. ForVisibleRedeclaration);
  13572. LookupName(Previous, S);
  13573. switch (Previous.getResultKind()) {
  13574. case LookupResult::Found:
  13575. case LookupResult::FoundUnresolvedValue:
  13576. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13577. break;
  13578. case LookupResult::FoundOverloaded:
  13579. PrevDecl = Previous.getRepresentativeDecl();
  13580. break;
  13581. case LookupResult::NotFound:
  13582. case LookupResult::NotFoundInCurrentInstantiation:
  13583. case LookupResult::Ambiguous:
  13584. break;
  13585. }
  13586. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13587. // Maybe we will complain about the shadowed template parameter.
  13588. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13589. // Just pretend that we didn't see the previous declaration.
  13590. PrevDecl = nullptr;
  13591. }
  13592. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13593. PrevDecl = nullptr;
  13594. SourceLocation TSSL = D.getBeginLoc();
  13595. MSPropertyDecl *NewPD =
  13596. MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
  13597. MSPropertyAttr.getPropertyDataGetter(),
  13598. MSPropertyAttr.getPropertyDataSetter());
  13599. ProcessDeclAttributes(TUScope, NewPD, D);
  13600. NewPD->setAccess(AS);
  13601. if (NewPD->isInvalidDecl())
  13602. Record->setInvalidDecl();
  13603. if (D.getDeclSpec().isModulePrivateSpecified())
  13604. NewPD->setModulePrivate();
  13605. if (NewPD->isInvalidDecl() && PrevDecl) {
  13606. // Don't introduce NewFD into scope; there's already something
  13607. // with the same name in the same scope.
  13608. } else if (II) {
  13609. PushOnScopeChains(NewPD, S);
  13610. } else
  13611. Record->addDecl(NewPD);
  13612. return NewPD;
  13613. }