SemaDeclCXX.cpp 590 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602
  1. //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for C++ declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/ComparisonCategories.h"
  20. #include "clang/AST/EvaluatedExprVisitor.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/RecordLayout.h"
  23. #include "clang/AST/RecursiveASTVisitor.h"
  24. #include "clang/AST/StmtVisitor.h"
  25. #include "clang/AST/TypeLoc.h"
  26. #include "clang/AST/TypeOrdering.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/LiteralSupport.h"
  30. #include "clang/Lex/Preprocessor.h"
  31. #include "clang/Sema/CXXFieldCollector.h"
  32. #include "clang/Sema/DeclSpec.h"
  33. #include "clang/Sema/Initialization.h"
  34. #include "clang/Sema/Lookup.h"
  35. #include "clang/Sema/ParsedTemplate.h"
  36. #include "clang/Sema/Scope.h"
  37. #include "clang/Sema/ScopeInfo.h"
  38. #include "clang/Sema/SemaInternal.h"
  39. #include "clang/Sema/Template.h"
  40. #include "llvm/ADT/STLExtras.h"
  41. #include "llvm/ADT/SmallString.h"
  42. #include "llvm/ADT/StringExtras.h"
  43. #include <map>
  44. #include <set>
  45. using namespace clang;
  46. //===----------------------------------------------------------------------===//
  47. // CheckDefaultArgumentVisitor
  48. //===----------------------------------------------------------------------===//
  49. namespace {
  50. /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
  51. /// the default argument of a parameter to determine whether it
  52. /// contains any ill-formed subexpressions. For example, this will
  53. /// diagnose the use of local variables or parameters within the
  54. /// default argument expression.
  55. class CheckDefaultArgumentVisitor
  56. : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
  57. Expr *DefaultArg;
  58. Sema *S;
  59. public:
  60. CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
  61. : DefaultArg(defarg), S(s) {}
  62. bool VisitExpr(Expr *Node);
  63. bool VisitDeclRefExpr(DeclRefExpr *DRE);
  64. bool VisitCXXThisExpr(CXXThisExpr *ThisE);
  65. bool VisitLambdaExpr(LambdaExpr *Lambda);
  66. bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
  67. };
  68. /// VisitExpr - Visit all of the children of this expression.
  69. bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
  70. bool IsInvalid = false;
  71. for (Stmt *SubStmt : Node->children())
  72. IsInvalid |= Visit(SubStmt);
  73. return IsInvalid;
  74. }
  75. /// VisitDeclRefExpr - Visit a reference to a declaration, to
  76. /// determine whether this declaration can be used in the default
  77. /// argument expression.
  78. bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
  79. NamedDecl *Decl = DRE->getDecl();
  80. if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
  81. // C++ [dcl.fct.default]p9
  82. // Default arguments are evaluated each time the function is
  83. // called. The order of evaluation of function arguments is
  84. // unspecified. Consequently, parameters of a function shall not
  85. // be used in default argument expressions, even if they are not
  86. // evaluated. Parameters of a function declared before a default
  87. // argument expression are in scope and can hide namespace and
  88. // class member names.
  89. return S->Diag(DRE->getBeginLoc(),
  90. diag::err_param_default_argument_references_param)
  91. << Param->getDeclName() << DefaultArg->getSourceRange();
  92. } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
  93. // C++ [dcl.fct.default]p7
  94. // Local variables shall not be used in default argument
  95. // expressions.
  96. if (VDecl->isLocalVarDecl())
  97. return S->Diag(DRE->getBeginLoc(),
  98. diag::err_param_default_argument_references_local)
  99. << VDecl->getDeclName() << DefaultArg->getSourceRange();
  100. }
  101. return false;
  102. }
  103. /// VisitCXXThisExpr - Visit a C++ "this" expression.
  104. bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
  105. // C++ [dcl.fct.default]p8:
  106. // The keyword this shall not be used in a default argument of a
  107. // member function.
  108. return S->Diag(ThisE->getBeginLoc(),
  109. diag::err_param_default_argument_references_this)
  110. << ThisE->getSourceRange();
  111. }
  112. bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
  113. bool Invalid = false;
  114. for (PseudoObjectExpr::semantics_iterator
  115. i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
  116. Expr *E = *i;
  117. // Look through bindings.
  118. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  119. E = OVE->getSourceExpr();
  120. assert(E && "pseudo-object binding without source expression?");
  121. }
  122. Invalid |= Visit(E);
  123. }
  124. return Invalid;
  125. }
  126. bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
  127. // C++11 [expr.lambda.prim]p13:
  128. // A lambda-expression appearing in a default argument shall not
  129. // implicitly or explicitly capture any entity.
  130. if (Lambda->capture_begin() == Lambda->capture_end())
  131. return false;
  132. return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
  133. }
  134. }
  135. void
  136. Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
  137. const CXXMethodDecl *Method) {
  138. // If we have an MSAny spec already, don't bother.
  139. if (!Method || ComputedEST == EST_MSAny)
  140. return;
  141. const FunctionProtoType *Proto
  142. = Method->getType()->getAs<FunctionProtoType>();
  143. Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
  144. if (!Proto)
  145. return;
  146. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  147. // If we have a throw-all spec at this point, ignore the function.
  148. if (ComputedEST == EST_None)
  149. return;
  150. if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
  151. EST = EST_BasicNoexcept;
  152. switch (EST) {
  153. case EST_Unparsed:
  154. case EST_Uninstantiated:
  155. case EST_Unevaluated:
  156. llvm_unreachable("should not see unresolved exception specs here");
  157. // If this function can throw any exceptions, make a note of that.
  158. case EST_MSAny:
  159. case EST_None:
  160. // FIXME: Whichever we see last of MSAny and None determines our result.
  161. // We should make a consistent, order-independent choice here.
  162. ClearExceptions();
  163. ComputedEST = EST;
  164. return;
  165. case EST_NoexceptFalse:
  166. ClearExceptions();
  167. ComputedEST = EST_None;
  168. return;
  169. // FIXME: If the call to this decl is using any of its default arguments, we
  170. // need to search them for potentially-throwing calls.
  171. // If this function has a basic noexcept, it doesn't affect the outcome.
  172. case EST_BasicNoexcept:
  173. case EST_NoexceptTrue:
  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->isConstexpr() != Old->isConstexpr()) {
  581. Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
  582. << New << New->isConstexpr();
  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. // FIXME: It's not clear what should happen if multiple declarations of a
  600. // deduction guide have different explicitness. For now at least we simply
  601. // reject any case where the explicitness changes.
  602. auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
  603. if (NewGuide && NewGuide->isExplicitSpecified() !=
  604. cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
  605. Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
  606. << NewGuide->isExplicitSpecified();
  607. Diag(Old->getLocation(), diag::note_previous_declaration);
  608. }
  609. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
  610. // argument expression, that declaration shall be a definition and shall be
  611. // the only declaration of the function or function template in the
  612. // translation unit.
  613. if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
  614. functionDeclHasDefaultArgument(Old)) {
  615. Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  616. Diag(Old->getLocation(), diag::note_previous_declaration);
  617. Invalid = true;
  618. }
  619. return Invalid;
  620. }
  621. NamedDecl *
  622. Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
  623. MultiTemplateParamsArg TemplateParamLists) {
  624. assert(D.isDecompositionDeclarator());
  625. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  626. // The syntax only allows a decomposition declarator as a simple-declaration,
  627. // a for-range-declaration, or a condition in Clang, but we parse it in more
  628. // cases than that.
  629. if (!D.mayHaveDecompositionDeclarator()) {
  630. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  631. << Decomp.getSourceRange();
  632. return nullptr;
  633. }
  634. if (!TemplateParamLists.empty()) {
  635. // FIXME: There's no rule against this, but there are also no rules that
  636. // would actually make it usable, so we reject it for now.
  637. Diag(TemplateParamLists.front()->getTemplateLoc(),
  638. diag::err_decomp_decl_template);
  639. return nullptr;
  640. }
  641. Diag(Decomp.getLSquareLoc(),
  642. !getLangOpts().CPlusPlus17
  643. ? diag::ext_decomp_decl
  644. : D.getContext() == DeclaratorContext::ConditionContext
  645. ? diag::ext_decomp_decl_cond
  646. : diag::warn_cxx14_compat_decomp_decl)
  647. << Decomp.getSourceRange();
  648. // The semantic context is always just the current context.
  649. DeclContext *const DC = CurContext;
  650. // C++1z [dcl.dcl]/8:
  651. // The decl-specifier-seq shall contain only the type-specifier auto
  652. // and cv-qualifiers.
  653. auto &DS = D.getDeclSpec();
  654. {
  655. SmallVector<StringRef, 8> BadSpecifiers;
  656. SmallVector<SourceLocation, 8> BadSpecifierLocs;
  657. if (auto SCS = DS.getStorageClassSpec()) {
  658. BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
  659. BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
  660. }
  661. if (auto TSCS = DS.getThreadStorageClassSpec()) {
  662. BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
  663. BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
  664. }
  665. if (DS.isConstexprSpecified()) {
  666. BadSpecifiers.push_back("constexpr");
  667. BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
  668. }
  669. if (DS.isInlineSpecified()) {
  670. BadSpecifiers.push_back("inline");
  671. BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
  672. }
  673. if (!BadSpecifiers.empty()) {
  674. auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
  675. Err << (int)BadSpecifiers.size()
  676. << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
  677. // Don't add FixItHints to remove the specifiers; we do still respect
  678. // them when building the underlying variable.
  679. for (auto Loc : BadSpecifierLocs)
  680. Err << SourceRange(Loc, Loc);
  681. }
  682. // We can't recover from it being declared as a typedef.
  683. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  684. return nullptr;
  685. }
  686. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  687. QualType R = TInfo->getType();
  688. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  689. UPPC_DeclarationType))
  690. D.setInvalidType();
  691. // The syntax only allows a single ref-qualifier prior to the decomposition
  692. // declarator. No other declarator chunks are permitted. Also check the type
  693. // specifier here.
  694. if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
  695. D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
  696. (D.getNumTypeObjects() == 1 &&
  697. D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
  698. Diag(Decomp.getLSquareLoc(),
  699. (D.hasGroupingParens() ||
  700. (D.getNumTypeObjects() &&
  701. D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
  702. ? diag::err_decomp_decl_parens
  703. : diag::err_decomp_decl_type)
  704. << R;
  705. // In most cases, there's no actual problem with an explicitly-specified
  706. // type, but a function type won't work here, and ActOnVariableDeclarator
  707. // shouldn't be called for such a type.
  708. if (R->isFunctionType())
  709. D.setInvalidType();
  710. }
  711. // Build the BindingDecls.
  712. SmallVector<BindingDecl*, 8> Bindings;
  713. // Build the BindingDecls.
  714. for (auto &B : D.getDecompositionDeclarator().bindings()) {
  715. // Check for name conflicts.
  716. DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
  717. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  718. ForVisibleRedeclaration);
  719. LookupName(Previous, S,
  720. /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
  721. // It's not permitted to shadow a template parameter name.
  722. if (Previous.isSingleResult() &&
  723. Previous.getFoundDecl()->isTemplateParameter()) {
  724. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  725. Previous.getFoundDecl());
  726. Previous.clear();
  727. }
  728. bool ConsiderLinkage = DC->isFunctionOrMethod() &&
  729. DS.getStorageClassSpec() == DeclSpec::SCS_extern;
  730. FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
  731. /*AllowInlineNamespace*/false);
  732. if (!Previous.empty()) {
  733. auto *Old = Previous.getRepresentativeDecl();
  734. Diag(B.NameLoc, diag::err_redefinition) << B.Name;
  735. Diag(Old->getLocation(), diag::note_previous_definition);
  736. }
  737. auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
  738. PushOnScopeChains(BD, S, true);
  739. Bindings.push_back(BD);
  740. ParsingInitForAutoVars.insert(BD);
  741. }
  742. // There are no prior lookup results for the variable itself, because it
  743. // is unnamed.
  744. DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
  745. Decomp.getLSquareLoc());
  746. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  747. ForVisibleRedeclaration);
  748. // Build the variable that holds the non-decomposed object.
  749. bool AddToScope = true;
  750. NamedDecl *New =
  751. ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
  752. MultiTemplateParamsArg(), AddToScope, Bindings);
  753. if (AddToScope) {
  754. S->AddDecl(New);
  755. CurContext->addHiddenDecl(New);
  756. }
  757. if (isInOpenMPDeclareTargetContext())
  758. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  759. return New;
  760. }
  761. static bool checkSimpleDecomposition(
  762. Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
  763. QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
  764. llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
  765. if ((int64_t)Bindings.size() != NumElems) {
  766. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  767. << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
  768. << (NumElems < Bindings.size());
  769. return true;
  770. }
  771. unsigned I = 0;
  772. for (auto *B : Bindings) {
  773. SourceLocation Loc = B->getLocation();
  774. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  775. if (E.isInvalid())
  776. return true;
  777. E = GetInit(Loc, E.get(), I++);
  778. if (E.isInvalid())
  779. return true;
  780. B->setBinding(ElemType, E.get());
  781. }
  782. return false;
  783. }
  784. static bool checkArrayLikeDecomposition(Sema &S,
  785. ArrayRef<BindingDecl *> Bindings,
  786. ValueDecl *Src, QualType DecompType,
  787. const llvm::APSInt &NumElems,
  788. QualType ElemType) {
  789. return checkSimpleDecomposition(
  790. S, Bindings, Src, DecompType, NumElems, ElemType,
  791. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  792. ExprResult E = S.ActOnIntegerConstant(Loc, I);
  793. if (E.isInvalid())
  794. return ExprError();
  795. return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
  796. });
  797. }
  798. static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  799. ValueDecl *Src, QualType DecompType,
  800. const ConstantArrayType *CAT) {
  801. return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
  802. llvm::APSInt(CAT->getSize()),
  803. CAT->getElementType());
  804. }
  805. static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  806. ValueDecl *Src, QualType DecompType,
  807. const VectorType *VT) {
  808. return checkArrayLikeDecomposition(
  809. S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
  810. S.Context.getQualifiedType(VT->getElementType(),
  811. DecompType.getQualifiers()));
  812. }
  813. static bool checkComplexDecomposition(Sema &S,
  814. ArrayRef<BindingDecl *> Bindings,
  815. ValueDecl *Src, QualType DecompType,
  816. const ComplexType *CT) {
  817. return checkSimpleDecomposition(
  818. S, Bindings, Src, DecompType, llvm::APSInt::get(2),
  819. S.Context.getQualifiedType(CT->getElementType(),
  820. DecompType.getQualifiers()),
  821. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  822. return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
  823. });
  824. }
  825. static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
  826. TemplateArgumentListInfo &Args) {
  827. SmallString<128> SS;
  828. llvm::raw_svector_ostream OS(SS);
  829. bool First = true;
  830. for (auto &Arg : Args.arguments()) {
  831. if (!First)
  832. OS << ", ";
  833. Arg.getArgument().print(PrintingPolicy, OS);
  834. First = false;
  835. }
  836. return OS.str();
  837. }
  838. static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
  839. SourceLocation Loc, StringRef Trait,
  840. TemplateArgumentListInfo &Args,
  841. unsigned DiagID) {
  842. auto DiagnoseMissing = [&] {
  843. if (DiagID)
  844. S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
  845. Args);
  846. return true;
  847. };
  848. // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
  849. NamespaceDecl *Std = S.getStdNamespace();
  850. if (!Std)
  851. return DiagnoseMissing();
  852. // Look up the trait itself, within namespace std. We can diagnose various
  853. // problems with this lookup even if we've been asked to not diagnose a
  854. // missing specialization, because this can only fail if the user has been
  855. // declaring their own names in namespace std or we don't support the
  856. // standard library implementation in use.
  857. LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
  858. Loc, Sema::LookupOrdinaryName);
  859. if (!S.LookupQualifiedName(Result, Std))
  860. return DiagnoseMissing();
  861. if (Result.isAmbiguous())
  862. return true;
  863. ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
  864. if (!TraitTD) {
  865. Result.suppressDiagnostics();
  866. NamedDecl *Found = *Result.begin();
  867. S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
  868. S.Diag(Found->getLocation(), diag::note_declared_at);
  869. return true;
  870. }
  871. // Build the template-id.
  872. QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
  873. if (TraitTy.isNull())
  874. return true;
  875. if (!S.isCompleteType(Loc, TraitTy)) {
  876. if (DiagID)
  877. S.RequireCompleteType(
  878. Loc, TraitTy, DiagID,
  879. printTemplateArgs(S.Context.getPrintingPolicy(), Args));
  880. return true;
  881. }
  882. CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
  883. assert(RD && "specialization of class template is not a class?");
  884. // Look up the member of the trait type.
  885. S.LookupQualifiedName(TraitMemberLookup, RD);
  886. return TraitMemberLookup.isAmbiguous();
  887. }
  888. static TemplateArgumentLoc
  889. getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
  890. uint64_t I) {
  891. TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
  892. return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
  893. }
  894. static TemplateArgumentLoc
  895. getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
  896. return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
  897. }
  898. namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
  899. static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
  900. llvm::APSInt &Size) {
  901. EnterExpressionEvaluationContext ContextRAII(
  902. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  903. DeclarationName Value = S.PP.getIdentifierInfo("value");
  904. LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
  905. // Form template argument list for tuple_size<T>.
  906. TemplateArgumentListInfo Args(Loc, Loc);
  907. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  908. // If there's no tuple_size specialization, it's not tuple-like.
  909. if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
  910. return IsTupleLike::NotTupleLike;
  911. // If we get this far, we've committed to the tuple interpretation, but
  912. // we can still fail if there actually isn't a usable ::value.
  913. struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
  914. LookupResult &R;
  915. TemplateArgumentListInfo &Args;
  916. ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
  917. : R(R), Args(Args) {}
  918. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
  919. S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
  920. << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
  921. }
  922. } Diagnoser(R, Args);
  923. if (R.empty()) {
  924. Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
  925. return IsTupleLike::Error;
  926. }
  927. ExprResult E =
  928. S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
  929. if (E.isInvalid())
  930. return IsTupleLike::Error;
  931. E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
  932. if (E.isInvalid())
  933. return IsTupleLike::Error;
  934. return IsTupleLike::TupleLike;
  935. }
  936. /// \return std::tuple_element<I, T>::type.
  937. static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
  938. unsigned I, QualType T) {
  939. // Form template argument list for tuple_element<I, T>.
  940. TemplateArgumentListInfo Args(Loc, Loc);
  941. Args.addArgument(
  942. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  943. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  944. DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
  945. LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
  946. if (lookupStdTypeTraitMember(
  947. S, R, Loc, "tuple_element", Args,
  948. diag::err_decomp_decl_std_tuple_element_not_specialized))
  949. return QualType();
  950. auto *TD = R.getAsSingle<TypeDecl>();
  951. if (!TD) {
  952. R.suppressDiagnostics();
  953. S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
  954. << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
  955. if (!R.empty())
  956. S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
  957. return QualType();
  958. }
  959. return S.Context.getTypeDeclType(TD);
  960. }
  961. namespace {
  962. struct BindingDiagnosticTrap {
  963. Sema &S;
  964. DiagnosticErrorTrap Trap;
  965. BindingDecl *BD;
  966. BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
  967. : S(S), Trap(S.Diags), BD(BD) {}
  968. ~BindingDiagnosticTrap() {
  969. if (Trap.hasErrorOccurred())
  970. S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
  971. }
  972. };
  973. }
  974. static bool checkTupleLikeDecomposition(Sema &S,
  975. ArrayRef<BindingDecl *> Bindings,
  976. VarDecl *Src, QualType DecompType,
  977. const llvm::APSInt &TupleSize) {
  978. if ((int64_t)Bindings.size() != TupleSize) {
  979. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  980. << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
  981. << (TupleSize < Bindings.size());
  982. return true;
  983. }
  984. if (Bindings.empty())
  985. return false;
  986. DeclarationName GetDN = S.PP.getIdentifierInfo("get");
  987. // [dcl.decomp]p3:
  988. // The unqualified-id get is looked up in the scope of E by class member
  989. // access lookup ...
  990. LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
  991. bool UseMemberGet = false;
  992. if (S.isCompleteType(Src->getLocation(), DecompType)) {
  993. if (auto *RD = DecompType->getAsCXXRecordDecl())
  994. S.LookupQualifiedName(MemberGet, RD);
  995. if (MemberGet.isAmbiguous())
  996. return true;
  997. // ... and if that finds at least one declaration that is a function
  998. // template whose first template parameter is a non-type parameter ...
  999. for (NamedDecl *D : MemberGet) {
  1000. if (FunctionTemplateDecl *FTD =
  1001. dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
  1002. TemplateParameterList *TPL = FTD->getTemplateParameters();
  1003. if (TPL->size() != 0 &&
  1004. isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
  1005. // ... the initializer is e.get<i>().
  1006. UseMemberGet = true;
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. S.FilterAcceptableTemplateNames(MemberGet);
  1012. }
  1013. unsigned I = 0;
  1014. for (auto *B : Bindings) {
  1015. BindingDiagnosticTrap Trap(S, B);
  1016. SourceLocation Loc = B->getLocation();
  1017. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1018. if (E.isInvalid())
  1019. return true;
  1020. // e is an lvalue if the type of the entity is an lvalue reference and
  1021. // an xvalue otherwise
  1022. if (!Src->getType()->isLValueReferenceType())
  1023. E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
  1024. E.get(), nullptr, VK_XValue);
  1025. TemplateArgumentListInfo Args(Loc, Loc);
  1026. Args.addArgument(
  1027. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  1028. if (UseMemberGet) {
  1029. // if [lookup of member get] finds at least one declaration, the
  1030. // initializer is e.get<i-1>().
  1031. E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
  1032. CXXScopeSpec(), SourceLocation(), nullptr,
  1033. MemberGet, &Args, nullptr);
  1034. if (E.isInvalid())
  1035. return true;
  1036. E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
  1037. } else {
  1038. // Otherwise, the initializer is get<i-1>(e), where get is looked up
  1039. // in the associated namespaces.
  1040. Expr *Get = UnresolvedLookupExpr::Create(
  1041. S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
  1042. DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
  1043. UnresolvedSetIterator(), UnresolvedSetIterator());
  1044. Expr *Arg = E.get();
  1045. E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
  1046. }
  1047. if (E.isInvalid())
  1048. return true;
  1049. Expr *Init = E.get();
  1050. // Given the type T designated by std::tuple_element<i - 1, E>::type,
  1051. QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
  1052. if (T.isNull())
  1053. return true;
  1054. // each vi is a variable of type "reference to T" initialized with the
  1055. // initializer, where the reference is an lvalue reference if the
  1056. // initializer is an lvalue and an rvalue reference otherwise
  1057. QualType RefType =
  1058. S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
  1059. if (RefType.isNull())
  1060. return true;
  1061. auto *RefVD = VarDecl::Create(
  1062. S.Context, Src->getDeclContext(), Loc, Loc,
  1063. B->getDeclName().getAsIdentifierInfo(), RefType,
  1064. S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
  1065. RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
  1066. RefVD->setTSCSpec(Src->getTSCSpec());
  1067. RefVD->setImplicit();
  1068. if (Src->isInlineSpecified())
  1069. RefVD->setInlineSpecified();
  1070. RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
  1071. InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
  1072. InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
  1073. InitializationSequence Seq(S, Entity, Kind, Init);
  1074. E = Seq.Perform(S, Entity, Kind, Init);
  1075. if (E.isInvalid())
  1076. return true;
  1077. E = S.ActOnFinishFullExpr(E.get(), Loc);
  1078. if (E.isInvalid())
  1079. return true;
  1080. RefVD->setInit(E.get());
  1081. RefVD->checkInitIsICE();
  1082. E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
  1083. DeclarationNameInfo(B->getDeclName(), Loc),
  1084. RefVD);
  1085. if (E.isInvalid())
  1086. return true;
  1087. B->setBinding(T, E.get());
  1088. I++;
  1089. }
  1090. return false;
  1091. }
  1092. /// Find the base class to decompose in a built-in decomposition of a class type.
  1093. /// This base class search is, unfortunately, not quite like any other that we
  1094. /// perform anywhere else in C++.
  1095. static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
  1096. const CXXRecordDecl *RD,
  1097. CXXCastPath &BasePath) {
  1098. auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
  1099. CXXBasePath &Path) {
  1100. return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
  1101. };
  1102. const CXXRecordDecl *ClassWithFields = nullptr;
  1103. AccessSpecifier AS = AS_public;
  1104. if (RD->hasDirectFields())
  1105. // [dcl.decomp]p4:
  1106. // Otherwise, all of E's non-static data members shall be public direct
  1107. // members of E ...
  1108. ClassWithFields = RD;
  1109. else {
  1110. // ... or of ...
  1111. CXXBasePaths Paths;
  1112. Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
  1113. if (!RD->lookupInBases(BaseHasFields, Paths)) {
  1114. // If no classes have fields, just decompose RD itself. (This will work
  1115. // if and only if zero bindings were provided.)
  1116. return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
  1117. }
  1118. CXXBasePath *BestPath = nullptr;
  1119. for (auto &P : Paths) {
  1120. if (!BestPath)
  1121. BestPath = &P;
  1122. else if (!S.Context.hasSameType(P.back().Base->getType(),
  1123. BestPath->back().Base->getType())) {
  1124. // ... the same ...
  1125. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1126. << false << RD << BestPath->back().Base->getType()
  1127. << P.back().Base->getType();
  1128. return DeclAccessPair();
  1129. } else if (P.Access < BestPath->Access) {
  1130. BestPath = &P;
  1131. }
  1132. }
  1133. // ... unambiguous ...
  1134. QualType BaseType = BestPath->back().Base->getType();
  1135. if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
  1136. S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
  1137. << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
  1138. return DeclAccessPair();
  1139. }
  1140. // ... [accessible, implied by other rules] base class of E.
  1141. S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
  1142. *BestPath, diag::err_decomp_decl_inaccessible_base);
  1143. AS = BestPath->Access;
  1144. ClassWithFields = BaseType->getAsCXXRecordDecl();
  1145. S.BuildBasePathArray(Paths, BasePath);
  1146. }
  1147. // The above search did not check whether the selected class itself has base
  1148. // classes with fields, so check that now.
  1149. CXXBasePaths Paths;
  1150. if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
  1151. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1152. << (ClassWithFields == RD) << RD << ClassWithFields
  1153. << Paths.front().back().Base->getType();
  1154. return DeclAccessPair();
  1155. }
  1156. return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
  1157. }
  1158. static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  1159. ValueDecl *Src, QualType DecompType,
  1160. const CXXRecordDecl *OrigRD) {
  1161. CXXCastPath BasePath;
  1162. DeclAccessPair BasePair =
  1163. findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
  1164. const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
  1165. if (!RD)
  1166. return true;
  1167. QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
  1168. DecompType.getQualifiers());
  1169. auto DiagnoseBadNumberOfBindings = [&]() -> bool {
  1170. unsigned NumFields =
  1171. std::count_if(RD->field_begin(), RD->field_end(),
  1172. [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
  1173. assert(Bindings.size() != NumFields);
  1174. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  1175. << DecompType << (unsigned)Bindings.size() << NumFields
  1176. << (NumFields < Bindings.size());
  1177. return true;
  1178. };
  1179. // all of E's non-static data members shall be [...] well-formed
  1180. // when named as e.name in the context of the structured binding,
  1181. // E shall not have an anonymous union member, ...
  1182. unsigned I = 0;
  1183. for (auto *FD : RD->fields()) {
  1184. if (FD->isUnnamedBitfield())
  1185. continue;
  1186. if (FD->isAnonymousStructOrUnion()) {
  1187. S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
  1188. << DecompType << FD->getType()->isUnionType();
  1189. S.Diag(FD->getLocation(), diag::note_declared_at);
  1190. return true;
  1191. }
  1192. // We have a real field to bind.
  1193. if (I >= Bindings.size())
  1194. return DiagnoseBadNumberOfBindings();
  1195. auto *B = Bindings[I++];
  1196. SourceLocation Loc = B->getLocation();
  1197. // The field must be accessible in the context of the structured binding.
  1198. // We already checked that the base class is accessible.
  1199. // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
  1200. // const_cast here.
  1201. S.CheckStructuredBindingMemberAccess(
  1202. Loc, const_cast<CXXRecordDecl *>(OrigRD),
  1203. DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
  1204. BasePair.getAccess(), FD->getAccess())));
  1205. // Initialize the binding to Src.FD.
  1206. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1207. if (E.isInvalid())
  1208. return true;
  1209. E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
  1210. VK_LValue, &BasePath);
  1211. if (E.isInvalid())
  1212. return true;
  1213. E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
  1214. CXXScopeSpec(), FD,
  1215. DeclAccessPair::make(FD, FD->getAccess()),
  1216. DeclarationNameInfo(FD->getDeclName(), Loc));
  1217. if (E.isInvalid())
  1218. return true;
  1219. // If the type of the member is T, the referenced type is cv T, where cv is
  1220. // the cv-qualification of the decomposition expression.
  1221. //
  1222. // FIXME: We resolve a defect here: if the field is mutable, we do not add
  1223. // 'const' to the type of the field.
  1224. Qualifiers Q = DecompType.getQualifiers();
  1225. if (FD->isMutable())
  1226. Q.removeConst();
  1227. B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
  1228. }
  1229. if (I != Bindings.size())
  1230. return DiagnoseBadNumberOfBindings();
  1231. return false;
  1232. }
  1233. void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
  1234. QualType DecompType = DD->getType();
  1235. // If the type of the decomposition is dependent, then so is the type of
  1236. // each binding.
  1237. if (DecompType->isDependentType()) {
  1238. for (auto *B : DD->bindings())
  1239. B->setType(Context.DependentTy);
  1240. return;
  1241. }
  1242. DecompType = DecompType.getNonReferenceType();
  1243. ArrayRef<BindingDecl*> Bindings = DD->bindings();
  1244. // C++1z [dcl.decomp]/2:
  1245. // If E is an array type [...]
  1246. // As an extension, we also support decomposition of built-in complex and
  1247. // vector types.
  1248. if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
  1249. if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
  1250. DD->setInvalidDecl();
  1251. return;
  1252. }
  1253. if (auto *VT = DecompType->getAs<VectorType>()) {
  1254. if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
  1255. DD->setInvalidDecl();
  1256. return;
  1257. }
  1258. if (auto *CT = DecompType->getAs<ComplexType>()) {
  1259. if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
  1260. DD->setInvalidDecl();
  1261. return;
  1262. }
  1263. // C++1z [dcl.decomp]/3:
  1264. // if the expression std::tuple_size<E>::value is a well-formed integral
  1265. // constant expression, [...]
  1266. llvm::APSInt TupleSize(32);
  1267. switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
  1268. case IsTupleLike::Error:
  1269. DD->setInvalidDecl();
  1270. return;
  1271. case IsTupleLike::TupleLike:
  1272. if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
  1273. DD->setInvalidDecl();
  1274. return;
  1275. case IsTupleLike::NotTupleLike:
  1276. break;
  1277. }
  1278. // C++1z [dcl.dcl]/8:
  1279. // [E shall be of array or non-union class type]
  1280. CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
  1281. if (!RD || RD->isUnion()) {
  1282. Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
  1283. << DD << !RD << DecompType;
  1284. DD->setInvalidDecl();
  1285. return;
  1286. }
  1287. // C++1z [dcl.decomp]/4:
  1288. // all of E's non-static data members shall be [...] direct members of
  1289. // E or of the same unambiguous public base class of E, ...
  1290. if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
  1291. DD->setInvalidDecl();
  1292. }
  1293. /// Merge the exception specifications of two variable declarations.
  1294. ///
  1295. /// This is called when there's a redeclaration of a VarDecl. The function
  1296. /// checks if the redeclaration might have an exception specification and
  1297. /// validates compatibility and merges the specs if necessary.
  1298. void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
  1299. // Shortcut if exceptions are disabled.
  1300. if (!getLangOpts().CXXExceptions)
  1301. return;
  1302. assert(Context.hasSameType(New->getType(), Old->getType()) &&
  1303. "Should only be called if types are otherwise the same.");
  1304. QualType NewType = New->getType();
  1305. QualType OldType = Old->getType();
  1306. // We're only interested in pointers and references to functions, as well
  1307. // as pointers to member functions.
  1308. if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
  1309. NewType = R->getPointeeType();
  1310. OldType = OldType->getAs<ReferenceType>()->getPointeeType();
  1311. } else if (const PointerType *P = NewType->getAs<PointerType>()) {
  1312. NewType = P->getPointeeType();
  1313. OldType = OldType->getAs<PointerType>()->getPointeeType();
  1314. } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
  1315. NewType = M->getPointeeType();
  1316. OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
  1317. }
  1318. if (!NewType->isFunctionProtoType())
  1319. return;
  1320. // There's lots of special cases for functions. For function pointers, system
  1321. // libraries are hopefully not as broken so that we don't need these
  1322. // workarounds.
  1323. if (CheckEquivalentExceptionSpec(
  1324. OldType->getAs<FunctionProtoType>(), Old->getLocation(),
  1325. NewType->getAs<FunctionProtoType>(), New->getLocation())) {
  1326. New->setInvalidDecl();
  1327. }
  1328. }
  1329. /// CheckCXXDefaultArguments - Verify that the default arguments for a
  1330. /// function declaration are well-formed according to C++
  1331. /// [dcl.fct.default].
  1332. void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
  1333. unsigned NumParams = FD->getNumParams();
  1334. unsigned p;
  1335. // Find first parameter with a default argument
  1336. for (p = 0; p < NumParams; ++p) {
  1337. ParmVarDecl *Param = FD->getParamDecl(p);
  1338. if (Param->hasDefaultArg())
  1339. break;
  1340. }
  1341. // C++11 [dcl.fct.default]p4:
  1342. // In a given function declaration, each parameter subsequent to a parameter
  1343. // with a default argument shall have a default argument supplied in this or
  1344. // a previous declaration or shall be a function parameter pack. A default
  1345. // argument shall not be redefined by a later declaration (not even to the
  1346. // same value).
  1347. unsigned LastMissingDefaultArg = 0;
  1348. for (; p < NumParams; ++p) {
  1349. ParmVarDecl *Param = FD->getParamDecl(p);
  1350. if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
  1351. if (Param->isInvalidDecl())
  1352. /* We already complained about this parameter. */;
  1353. else if (Param->getIdentifier())
  1354. Diag(Param->getLocation(),
  1355. diag::err_param_default_argument_missing_name)
  1356. << Param->getIdentifier();
  1357. else
  1358. Diag(Param->getLocation(),
  1359. diag::err_param_default_argument_missing);
  1360. LastMissingDefaultArg = p;
  1361. }
  1362. }
  1363. if (LastMissingDefaultArg > 0) {
  1364. // Some default arguments were missing. Clear out all of the
  1365. // default arguments up to (and including) the last missing
  1366. // default argument, so that we leave the function parameters
  1367. // in a semantically valid state.
  1368. for (p = 0; p <= LastMissingDefaultArg; ++p) {
  1369. ParmVarDecl *Param = FD->getParamDecl(p);
  1370. if (Param->hasDefaultArg()) {
  1371. Param->setDefaultArg(nullptr);
  1372. }
  1373. }
  1374. }
  1375. }
  1376. // CheckConstexprParameterTypes - Check whether a function's parameter types
  1377. // are all literal types. If so, return true. If not, produce a suitable
  1378. // diagnostic and return false.
  1379. static bool CheckConstexprParameterTypes(Sema &SemaRef,
  1380. const FunctionDecl *FD) {
  1381. unsigned ArgIndex = 0;
  1382. const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
  1383. for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
  1384. e = FT->param_type_end();
  1385. i != e; ++i, ++ArgIndex) {
  1386. const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
  1387. SourceLocation ParamLoc = PD->getLocation();
  1388. if (!(*i)->isDependentType() &&
  1389. SemaRef.RequireLiteralType(ParamLoc, *i,
  1390. diag::err_constexpr_non_literal_param,
  1391. ArgIndex+1, PD->getSourceRange(),
  1392. isa<CXXConstructorDecl>(FD)))
  1393. return false;
  1394. }
  1395. return true;
  1396. }
  1397. /// Get diagnostic %select index for tag kind for
  1398. /// record diagnostic message.
  1399. /// WARNING: Indexes apply to particular diagnostics only!
  1400. ///
  1401. /// \returns diagnostic %select index.
  1402. static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
  1403. switch (Tag) {
  1404. case TTK_Struct: return 0;
  1405. case TTK_Interface: return 1;
  1406. case TTK_Class: return 2;
  1407. default: llvm_unreachable("Invalid tag kind for record diagnostic!");
  1408. }
  1409. }
  1410. // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
  1411. // the requirements of a constexpr function definition or a constexpr
  1412. // constructor definition. If so, return true. If not, produce appropriate
  1413. // diagnostics and return false.
  1414. //
  1415. // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
  1416. bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
  1417. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  1418. if (MD && MD->isInstance()) {
  1419. // C++11 [dcl.constexpr]p4:
  1420. // The definition of a constexpr constructor shall satisfy the following
  1421. // constraints:
  1422. // - the class shall not have any virtual base classes;
  1423. const CXXRecordDecl *RD = MD->getParent();
  1424. if (RD->getNumVBases()) {
  1425. Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
  1426. << isa<CXXConstructorDecl>(NewFD)
  1427. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  1428. for (const auto &I : RD->vbases())
  1429. Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
  1430. << I.getSourceRange();
  1431. return false;
  1432. }
  1433. }
  1434. if (!isa<CXXConstructorDecl>(NewFD)) {
  1435. // C++11 [dcl.constexpr]p3:
  1436. // The definition of a constexpr function shall satisfy the following
  1437. // constraints:
  1438. // - it shall not be virtual;
  1439. const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
  1440. if (Method && Method->isVirtual()) {
  1441. Method = Method->getCanonicalDecl();
  1442. Diag(Method->getLocation(), diag::err_constexpr_virtual);
  1443. // If it's not obvious why this function is virtual, find an overridden
  1444. // function which uses the 'virtual' keyword.
  1445. const CXXMethodDecl *WrittenVirtual = Method;
  1446. while (!WrittenVirtual->isVirtualAsWritten())
  1447. WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
  1448. if (WrittenVirtual != Method)
  1449. Diag(WrittenVirtual->getLocation(),
  1450. diag::note_overridden_virtual_function);
  1451. return false;
  1452. }
  1453. // - its return type shall be a literal type;
  1454. QualType RT = NewFD->getReturnType();
  1455. if (!RT->isDependentType() &&
  1456. RequireLiteralType(NewFD->getLocation(), RT,
  1457. diag::err_constexpr_non_literal_return))
  1458. return false;
  1459. }
  1460. // - each of its parameter types shall be a literal type;
  1461. if (!CheckConstexprParameterTypes(*this, NewFD))
  1462. return false;
  1463. return true;
  1464. }
  1465. /// Check the given declaration statement is legal within a constexpr function
  1466. /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
  1467. ///
  1468. /// \return true if the body is OK (maybe only as an extension), false if we
  1469. /// have diagnosed a problem.
  1470. static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
  1471. DeclStmt *DS, SourceLocation &Cxx1yLoc) {
  1472. // C++11 [dcl.constexpr]p3 and p4:
  1473. // The definition of a constexpr function(p3) or constructor(p4) [...] shall
  1474. // contain only
  1475. for (const auto *DclIt : DS->decls()) {
  1476. switch (DclIt->getKind()) {
  1477. case Decl::StaticAssert:
  1478. case Decl::Using:
  1479. case Decl::UsingShadow:
  1480. case Decl::UsingDirective:
  1481. case Decl::UnresolvedUsingTypename:
  1482. case Decl::UnresolvedUsingValue:
  1483. // - static_assert-declarations
  1484. // - using-declarations,
  1485. // - using-directives,
  1486. continue;
  1487. case Decl::Typedef:
  1488. case Decl::TypeAlias: {
  1489. // - typedef declarations and alias-declarations that do not define
  1490. // classes or enumerations,
  1491. const auto *TN = cast<TypedefNameDecl>(DclIt);
  1492. if (TN->getUnderlyingType()->isVariablyModifiedType()) {
  1493. // Don't allow variably-modified types in constexpr functions.
  1494. TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
  1495. SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
  1496. << TL.getSourceRange() << TL.getType()
  1497. << isa<CXXConstructorDecl>(Dcl);
  1498. return false;
  1499. }
  1500. continue;
  1501. }
  1502. case Decl::Enum:
  1503. case Decl::CXXRecord:
  1504. // C++1y allows types to be defined, not just declared.
  1505. if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
  1506. SemaRef.Diag(DS->getBeginLoc(),
  1507. SemaRef.getLangOpts().CPlusPlus14
  1508. ? diag::warn_cxx11_compat_constexpr_type_definition
  1509. : diag::ext_constexpr_type_definition)
  1510. << isa<CXXConstructorDecl>(Dcl);
  1511. continue;
  1512. case Decl::EnumConstant:
  1513. case Decl::IndirectField:
  1514. case Decl::ParmVar:
  1515. // These can only appear with other declarations which are banned in
  1516. // C++11 and permitted in C++1y, so ignore them.
  1517. continue;
  1518. case Decl::Var:
  1519. case Decl::Decomposition: {
  1520. // C++1y [dcl.constexpr]p3 allows anything except:
  1521. // a definition of a variable of non-literal type or of static or
  1522. // thread storage duration or for which no initialization is performed.
  1523. const auto *VD = cast<VarDecl>(DclIt);
  1524. if (VD->isThisDeclarationADefinition()) {
  1525. if (VD->isStaticLocal()) {
  1526. SemaRef.Diag(VD->getLocation(),
  1527. diag::err_constexpr_local_var_static)
  1528. << isa<CXXConstructorDecl>(Dcl)
  1529. << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
  1530. return false;
  1531. }
  1532. if (!VD->getType()->isDependentType() &&
  1533. SemaRef.RequireLiteralType(
  1534. VD->getLocation(), VD->getType(),
  1535. diag::err_constexpr_local_var_non_literal_type,
  1536. isa<CXXConstructorDecl>(Dcl)))
  1537. return false;
  1538. if (!VD->getType()->isDependentType() &&
  1539. !VD->hasInit() && !VD->isCXXForRangeDecl()) {
  1540. SemaRef.Diag(VD->getLocation(),
  1541. diag::err_constexpr_local_var_no_init)
  1542. << isa<CXXConstructorDecl>(Dcl);
  1543. return false;
  1544. }
  1545. }
  1546. SemaRef.Diag(VD->getLocation(),
  1547. SemaRef.getLangOpts().CPlusPlus14
  1548. ? diag::warn_cxx11_compat_constexpr_local_var
  1549. : diag::ext_constexpr_local_var)
  1550. << isa<CXXConstructorDecl>(Dcl);
  1551. continue;
  1552. }
  1553. case Decl::NamespaceAlias:
  1554. case Decl::Function:
  1555. // These are disallowed in C++11 and permitted in C++1y. Allow them
  1556. // everywhere as an extension.
  1557. if (!Cxx1yLoc.isValid())
  1558. Cxx1yLoc = DS->getBeginLoc();
  1559. continue;
  1560. default:
  1561. SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1562. << isa<CXXConstructorDecl>(Dcl);
  1563. return false;
  1564. }
  1565. }
  1566. return true;
  1567. }
  1568. /// Check that the given field is initialized within a constexpr constructor.
  1569. ///
  1570. /// \param Dcl The constexpr constructor being checked.
  1571. /// \param Field The field being checked. This may be a member of an anonymous
  1572. /// struct or union nested within the class being checked.
  1573. /// \param Inits All declarations, including anonymous struct/union members and
  1574. /// indirect members, for which any initialization was provided.
  1575. /// \param Diagnosed Set to true if an error is produced.
  1576. static void CheckConstexprCtorInitializer(Sema &SemaRef,
  1577. const FunctionDecl *Dcl,
  1578. FieldDecl *Field,
  1579. llvm::SmallSet<Decl*, 16> &Inits,
  1580. bool &Diagnosed) {
  1581. if (Field->isInvalidDecl())
  1582. return;
  1583. if (Field->isUnnamedBitfield())
  1584. return;
  1585. // Anonymous unions with no variant members and empty anonymous structs do not
  1586. // need to be explicitly initialized. FIXME: Anonymous structs that contain no
  1587. // indirect fields don't need initializing.
  1588. if (Field->isAnonymousStructOrUnion() &&
  1589. (Field->getType()->isUnionType()
  1590. ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
  1591. : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
  1592. return;
  1593. if (!Inits.count(Field)) {
  1594. if (!Diagnosed) {
  1595. SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
  1596. Diagnosed = true;
  1597. }
  1598. SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
  1599. } else if (Field->isAnonymousStructOrUnion()) {
  1600. const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
  1601. for (auto *I : RD->fields())
  1602. // If an anonymous union contains an anonymous struct of which any member
  1603. // is initialized, all members must be initialized.
  1604. if (!RD->isUnion() || Inits.count(I))
  1605. CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
  1606. }
  1607. }
  1608. /// Check the provided statement is allowed in a constexpr function
  1609. /// definition.
  1610. static bool
  1611. CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
  1612. SmallVectorImpl<SourceLocation> &ReturnStmts,
  1613. SourceLocation &Cxx1yLoc) {
  1614. // - its function-body shall be [...] a compound-statement that contains only
  1615. switch (S->getStmtClass()) {
  1616. case Stmt::NullStmtClass:
  1617. // - null statements,
  1618. return true;
  1619. case Stmt::DeclStmtClass:
  1620. // - static_assert-declarations
  1621. // - using-declarations,
  1622. // - using-directives,
  1623. // - typedef declarations and alias-declarations that do not define
  1624. // classes or enumerations,
  1625. if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
  1626. return false;
  1627. return true;
  1628. case Stmt::ReturnStmtClass:
  1629. // - and exactly one return statement;
  1630. if (isa<CXXConstructorDecl>(Dcl)) {
  1631. // C++1y allows return statements in constexpr constructors.
  1632. if (!Cxx1yLoc.isValid())
  1633. Cxx1yLoc = S->getBeginLoc();
  1634. return true;
  1635. }
  1636. ReturnStmts.push_back(S->getBeginLoc());
  1637. return true;
  1638. case Stmt::CompoundStmtClass: {
  1639. // C++1y allows compound-statements.
  1640. if (!Cxx1yLoc.isValid())
  1641. Cxx1yLoc = S->getBeginLoc();
  1642. CompoundStmt *CompStmt = cast<CompoundStmt>(S);
  1643. for (auto *BodyIt : CompStmt->body()) {
  1644. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
  1645. Cxx1yLoc))
  1646. return false;
  1647. }
  1648. return true;
  1649. }
  1650. case Stmt::AttributedStmtClass:
  1651. if (!Cxx1yLoc.isValid())
  1652. Cxx1yLoc = S->getBeginLoc();
  1653. return true;
  1654. case Stmt::IfStmtClass: {
  1655. // C++1y allows if-statements.
  1656. if (!Cxx1yLoc.isValid())
  1657. Cxx1yLoc = S->getBeginLoc();
  1658. IfStmt *If = cast<IfStmt>(S);
  1659. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
  1660. Cxx1yLoc))
  1661. return false;
  1662. if (If->getElse() &&
  1663. !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
  1664. Cxx1yLoc))
  1665. return false;
  1666. return true;
  1667. }
  1668. case Stmt::WhileStmtClass:
  1669. case Stmt::DoStmtClass:
  1670. case Stmt::ForStmtClass:
  1671. case Stmt::CXXForRangeStmtClass:
  1672. case Stmt::ContinueStmtClass:
  1673. // C++1y allows all of these. We don't allow them as extensions in C++11,
  1674. // because they don't make sense without variable mutation.
  1675. if (!SemaRef.getLangOpts().CPlusPlus14)
  1676. break;
  1677. if (!Cxx1yLoc.isValid())
  1678. Cxx1yLoc = S->getBeginLoc();
  1679. for (Stmt *SubStmt : S->children())
  1680. if (SubStmt &&
  1681. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1682. Cxx1yLoc))
  1683. return false;
  1684. return true;
  1685. case Stmt::SwitchStmtClass:
  1686. case Stmt::CaseStmtClass:
  1687. case Stmt::DefaultStmtClass:
  1688. case Stmt::BreakStmtClass:
  1689. // C++1y allows switch-statements, and since they don't need variable
  1690. // mutation, we can reasonably allow them in C++11 as an extension.
  1691. if (!Cxx1yLoc.isValid())
  1692. Cxx1yLoc = S->getBeginLoc();
  1693. for (Stmt *SubStmt : S->children())
  1694. if (SubStmt &&
  1695. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1696. Cxx1yLoc))
  1697. return false;
  1698. return true;
  1699. default:
  1700. if (!isa<Expr>(S))
  1701. break;
  1702. // C++1y allows expression-statements.
  1703. if (!Cxx1yLoc.isValid())
  1704. Cxx1yLoc = S->getBeginLoc();
  1705. return true;
  1706. }
  1707. SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1708. << isa<CXXConstructorDecl>(Dcl);
  1709. return false;
  1710. }
  1711. /// Check the body for the given constexpr function declaration only contains
  1712. /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
  1713. ///
  1714. /// \return true if the body is OK, false if we have diagnosed a problem.
  1715. bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
  1716. if (isa<CXXTryStmt>(Body)) {
  1717. // C++11 [dcl.constexpr]p3:
  1718. // The definition of a constexpr function shall satisfy the following
  1719. // constraints: [...]
  1720. // - its function-body shall be = delete, = default, or a
  1721. // compound-statement
  1722. //
  1723. // C++11 [dcl.constexpr]p4:
  1724. // In the definition of a constexpr constructor, [...]
  1725. // - its function-body shall not be a function-try-block;
  1726. Diag(Body->getBeginLoc(), diag::err_constexpr_function_try_block)
  1727. << isa<CXXConstructorDecl>(Dcl);
  1728. return false;
  1729. }
  1730. SmallVector<SourceLocation, 4> ReturnStmts;
  1731. // - its function-body shall be [...] a compound-statement that contains only
  1732. // [... list of cases ...]
  1733. CompoundStmt *CompBody = cast<CompoundStmt>(Body);
  1734. SourceLocation Cxx1yLoc;
  1735. for (auto *BodyIt : CompBody->body()) {
  1736. if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
  1737. return false;
  1738. }
  1739. if (Cxx1yLoc.isValid())
  1740. Diag(Cxx1yLoc,
  1741. getLangOpts().CPlusPlus14
  1742. ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
  1743. : diag::ext_constexpr_body_invalid_stmt)
  1744. << isa<CXXConstructorDecl>(Dcl);
  1745. if (const CXXConstructorDecl *Constructor
  1746. = dyn_cast<CXXConstructorDecl>(Dcl)) {
  1747. const CXXRecordDecl *RD = Constructor->getParent();
  1748. // DR1359:
  1749. // - every non-variant non-static data member and base class sub-object
  1750. // shall be initialized;
  1751. // DR1460:
  1752. // - if the class is a union having variant members, exactly one of them
  1753. // shall be initialized;
  1754. if (RD->isUnion()) {
  1755. if (Constructor->getNumCtorInitializers() == 0 &&
  1756. RD->hasVariantMembers()) {
  1757. Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
  1758. return false;
  1759. }
  1760. } else if (!Constructor->isDependentContext() &&
  1761. !Constructor->isDelegatingConstructor()) {
  1762. assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
  1763. // Skip detailed checking if we have enough initializers, and we would
  1764. // allow at most one initializer per member.
  1765. bool AnyAnonStructUnionMembers = false;
  1766. unsigned Fields = 0;
  1767. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  1768. E = RD->field_end(); I != E; ++I, ++Fields) {
  1769. if (I->isAnonymousStructOrUnion()) {
  1770. AnyAnonStructUnionMembers = true;
  1771. break;
  1772. }
  1773. }
  1774. // DR1460:
  1775. // - if the class is a union-like class, but is not a union, for each of
  1776. // its anonymous union members having variant members, exactly one of
  1777. // them shall be initialized;
  1778. if (AnyAnonStructUnionMembers ||
  1779. Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
  1780. // Check initialization of non-static data members. Base classes are
  1781. // always initialized so do not need to be checked. Dependent bases
  1782. // might not have initializers in the member initializer list.
  1783. llvm::SmallSet<Decl*, 16> Inits;
  1784. for (const auto *I: Constructor->inits()) {
  1785. if (FieldDecl *FD = I->getMember())
  1786. Inits.insert(FD);
  1787. else if (IndirectFieldDecl *ID = I->getIndirectMember())
  1788. Inits.insert(ID->chain_begin(), ID->chain_end());
  1789. }
  1790. bool Diagnosed = false;
  1791. for (auto *I : RD->fields())
  1792. CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
  1793. if (Diagnosed)
  1794. return false;
  1795. }
  1796. }
  1797. } else {
  1798. if (ReturnStmts.empty()) {
  1799. // C++1y doesn't require constexpr functions to contain a 'return'
  1800. // statement. We still do, unless the return type might be void, because
  1801. // otherwise if there's no return statement, the function cannot
  1802. // be used in a core constant expression.
  1803. bool OK = getLangOpts().CPlusPlus14 &&
  1804. (Dcl->getReturnType()->isVoidType() ||
  1805. Dcl->getReturnType()->isDependentType());
  1806. Diag(Dcl->getLocation(),
  1807. OK ? diag::warn_cxx11_compat_constexpr_body_no_return
  1808. : diag::err_constexpr_body_no_return);
  1809. if (!OK)
  1810. return false;
  1811. } else if (ReturnStmts.size() > 1) {
  1812. Diag(ReturnStmts.back(),
  1813. getLangOpts().CPlusPlus14
  1814. ? diag::warn_cxx11_compat_constexpr_body_multiple_return
  1815. : diag::ext_constexpr_body_multiple_return);
  1816. for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
  1817. Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
  1818. }
  1819. }
  1820. // C++11 [dcl.constexpr]p5:
  1821. // if no function argument values exist such that the function invocation
  1822. // substitution would produce a constant expression, the program is
  1823. // ill-formed; no diagnostic required.
  1824. // C++11 [dcl.constexpr]p3:
  1825. // - every constructor call and implicit conversion used in initializing the
  1826. // return value shall be one of those allowed in a constant expression.
  1827. // C++11 [dcl.constexpr]p4:
  1828. // - every constructor involved in initializing non-static data members and
  1829. // base class sub-objects shall be a constexpr constructor.
  1830. SmallVector<PartialDiagnosticAt, 8> Diags;
  1831. if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
  1832. Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
  1833. << isa<CXXConstructorDecl>(Dcl);
  1834. for (size_t I = 0, N = Diags.size(); I != N; ++I)
  1835. Diag(Diags[I].first, Diags[I].second);
  1836. // Don't return false here: we allow this for compatibility in
  1837. // system headers.
  1838. }
  1839. return true;
  1840. }
  1841. /// Get the class that is directly named by the current context. This is the
  1842. /// class for which an unqualified-id in this scope could name a constructor
  1843. /// or destructor.
  1844. ///
  1845. /// If the scope specifier denotes a class, this will be that class.
  1846. /// If the scope specifier is empty, this will be the class whose
  1847. /// member-specification we are currently within. Otherwise, there
  1848. /// is no such class.
  1849. CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
  1850. assert(getLangOpts().CPlusPlus && "No class names in C!");
  1851. if (SS && SS->isInvalid())
  1852. return nullptr;
  1853. if (SS && SS->isNotEmpty()) {
  1854. DeclContext *DC = computeDeclContext(*SS, true);
  1855. return dyn_cast_or_null<CXXRecordDecl>(DC);
  1856. }
  1857. return dyn_cast_or_null<CXXRecordDecl>(CurContext);
  1858. }
  1859. /// isCurrentClassName - Determine whether the identifier II is the
  1860. /// name of the class type currently being defined. In the case of
  1861. /// nested classes, this will only return true if II is the name of
  1862. /// the innermost class.
  1863. bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
  1864. const CXXScopeSpec *SS) {
  1865. CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
  1866. return CurDecl && &II == CurDecl->getIdentifier();
  1867. }
  1868. /// Determine whether the identifier II is a typo for the name of
  1869. /// the class type currently being defined. If so, update it to the identifier
  1870. /// that should have been used.
  1871. bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
  1872. assert(getLangOpts().CPlusPlus && "No class names in C!");
  1873. if (!getLangOpts().SpellChecking)
  1874. return false;
  1875. CXXRecordDecl *CurDecl;
  1876. if (SS && SS->isSet() && !SS->isInvalid()) {
  1877. DeclContext *DC = computeDeclContext(*SS, true);
  1878. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  1879. } else
  1880. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  1881. if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
  1882. 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
  1883. < II->getLength()) {
  1884. II = CurDecl->getIdentifier();
  1885. return true;
  1886. }
  1887. return false;
  1888. }
  1889. /// Determine whether the given class is a base class of the given
  1890. /// class, including looking at dependent bases.
  1891. static bool findCircularInheritance(const CXXRecordDecl *Class,
  1892. const CXXRecordDecl *Current) {
  1893. SmallVector<const CXXRecordDecl*, 8> Queue;
  1894. Class = Class->getCanonicalDecl();
  1895. while (true) {
  1896. for (const auto &I : Current->bases()) {
  1897. CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  1898. if (!Base)
  1899. continue;
  1900. Base = Base->getDefinition();
  1901. if (!Base)
  1902. continue;
  1903. if (Base->getCanonicalDecl() == Class)
  1904. return true;
  1905. Queue.push_back(Base);
  1906. }
  1907. if (Queue.empty())
  1908. return false;
  1909. Current = Queue.pop_back_val();
  1910. }
  1911. return false;
  1912. }
  1913. /// Check the validity of a C++ base class specifier.
  1914. ///
  1915. /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
  1916. /// and returns NULL otherwise.
  1917. CXXBaseSpecifier *
  1918. Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
  1919. SourceRange SpecifierRange,
  1920. bool Virtual, AccessSpecifier Access,
  1921. TypeSourceInfo *TInfo,
  1922. SourceLocation EllipsisLoc) {
  1923. QualType BaseType = TInfo->getType();
  1924. // C++ [class.union]p1:
  1925. // A union shall not have base classes.
  1926. if (Class->isUnion()) {
  1927. Diag(Class->getLocation(), diag::err_base_clause_on_union)
  1928. << SpecifierRange;
  1929. return nullptr;
  1930. }
  1931. if (EllipsisLoc.isValid() &&
  1932. !TInfo->getType()->containsUnexpandedParameterPack()) {
  1933. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  1934. << TInfo->getTypeLoc().getSourceRange();
  1935. EllipsisLoc = SourceLocation();
  1936. }
  1937. SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
  1938. if (BaseType->isDependentType()) {
  1939. // Make sure that we don't have circular inheritance among our dependent
  1940. // bases. For non-dependent bases, the check for completeness below handles
  1941. // this.
  1942. if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
  1943. if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
  1944. ((BaseDecl = BaseDecl->getDefinition()) &&
  1945. findCircularInheritance(Class, BaseDecl))) {
  1946. Diag(BaseLoc, diag::err_circular_inheritance)
  1947. << BaseType << Context.getTypeDeclType(Class);
  1948. if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
  1949. Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  1950. << BaseType;
  1951. return nullptr;
  1952. }
  1953. }
  1954. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  1955. Class->getTagKind() == TTK_Class,
  1956. Access, TInfo, EllipsisLoc);
  1957. }
  1958. // Base specifiers must be record types.
  1959. if (!BaseType->isRecordType()) {
  1960. Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
  1961. return nullptr;
  1962. }
  1963. // C++ [class.union]p1:
  1964. // A union shall not be used as a base class.
  1965. if (BaseType->isUnionType()) {
  1966. Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
  1967. return nullptr;
  1968. }
  1969. // For the MS ABI, propagate DLL attributes to base class templates.
  1970. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1971. if (Attr *ClassAttr = getDLLAttr(Class)) {
  1972. if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  1973. BaseType->getAsCXXRecordDecl())) {
  1974. propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
  1975. BaseLoc);
  1976. }
  1977. }
  1978. }
  1979. // C++ [class.derived]p2:
  1980. // The class-name in a base-specifier shall not be an incompletely
  1981. // defined class.
  1982. if (RequireCompleteType(BaseLoc, BaseType,
  1983. diag::err_incomplete_base_class, SpecifierRange)) {
  1984. Class->setInvalidDecl();
  1985. return nullptr;
  1986. }
  1987. // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
  1988. RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
  1989. assert(BaseDecl && "Record type has no declaration");
  1990. BaseDecl = BaseDecl->getDefinition();
  1991. assert(BaseDecl && "Base type is not incomplete, but has no definition");
  1992. CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
  1993. assert(CXXBaseDecl && "Base type is not a C++ type");
  1994. // Microsoft docs say:
  1995. // "If a base-class has a code_seg attribute, derived classes must have the
  1996. // same attribute."
  1997. const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
  1998. const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
  1999. if ((DerivedCSA || BaseCSA) &&
  2000. (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
  2001. Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
  2002. Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
  2003. << CXXBaseDecl;
  2004. return nullptr;
  2005. }
  2006. // A class which contains a flexible array member is not suitable for use as a
  2007. // base class:
  2008. // - If the layout determines that a base comes before another base,
  2009. // the flexible array member would index into the subsequent base.
  2010. // - If the layout determines that base comes before the derived class,
  2011. // the flexible array member would index into the derived class.
  2012. if (CXXBaseDecl->hasFlexibleArrayMember()) {
  2013. Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
  2014. << CXXBaseDecl->getDeclName();
  2015. return nullptr;
  2016. }
  2017. // C++ [class]p3:
  2018. // If a class is marked final and it appears as a base-type-specifier in
  2019. // base-clause, the program is ill-formed.
  2020. if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
  2021. Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
  2022. << CXXBaseDecl->getDeclName()
  2023. << FA->isSpelledAsSealed();
  2024. Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
  2025. << CXXBaseDecl->getDeclName() << FA->getRange();
  2026. return nullptr;
  2027. }
  2028. if (BaseDecl->isInvalidDecl())
  2029. Class->setInvalidDecl();
  2030. // Create the base specifier.
  2031. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2032. Class->getTagKind() == TTK_Class,
  2033. Access, TInfo, EllipsisLoc);
  2034. }
  2035. /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
  2036. /// one entry in the base class list of a class specifier, for
  2037. /// example:
  2038. /// class foo : public bar, virtual private baz {
  2039. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  2040. BaseResult
  2041. Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
  2042. ParsedAttributes &Attributes,
  2043. bool Virtual, AccessSpecifier Access,
  2044. ParsedType basetype, SourceLocation BaseLoc,
  2045. SourceLocation EllipsisLoc) {
  2046. if (!classdecl)
  2047. return true;
  2048. AdjustDeclIfTemplate(classdecl);
  2049. CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
  2050. if (!Class)
  2051. return true;
  2052. // We haven't yet attached the base specifiers.
  2053. Class->setIsParsingBaseSpecifiers();
  2054. // We do not support any C++11 attributes on base-specifiers yet.
  2055. // Diagnose any attributes we see.
  2056. for (const ParsedAttr &AL : Attributes) {
  2057. if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
  2058. continue;
  2059. Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
  2060. ? diag::warn_unknown_attribute_ignored
  2061. : diag::err_base_specifier_attribute)
  2062. << AL.getName();
  2063. }
  2064. TypeSourceInfo *TInfo = nullptr;
  2065. GetTypeFromParser(basetype, &TInfo);
  2066. if (EllipsisLoc.isInvalid() &&
  2067. DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
  2068. UPPC_BaseType))
  2069. return true;
  2070. if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
  2071. Virtual, Access, TInfo,
  2072. EllipsisLoc))
  2073. return BaseSpec;
  2074. else
  2075. Class->setInvalidDecl();
  2076. return true;
  2077. }
  2078. /// Use small set to collect indirect bases. As this is only used
  2079. /// locally, there's no need to abstract the small size parameter.
  2080. typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
  2081. /// Recursively add the bases of Type. Don't add Type itself.
  2082. static void
  2083. NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
  2084. const QualType &Type)
  2085. {
  2086. // Even though the incoming type is a base, it might not be
  2087. // a class -- it could be a template parm, for instance.
  2088. if (auto Rec = Type->getAs<RecordType>()) {
  2089. auto Decl = Rec->getAsCXXRecordDecl();
  2090. // Iterate over its bases.
  2091. for (const auto &BaseSpec : Decl->bases()) {
  2092. QualType Base = Context.getCanonicalType(BaseSpec.getType())
  2093. .getUnqualifiedType();
  2094. if (Set.insert(Base).second)
  2095. // If we've not already seen it, recurse.
  2096. NoteIndirectBases(Context, Set, Base);
  2097. }
  2098. }
  2099. }
  2100. /// Performs the actual work of attaching the given base class
  2101. /// specifiers to a C++ class.
  2102. bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
  2103. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2104. if (Bases.empty())
  2105. return false;
  2106. // Used to keep track of which base types we have already seen, so
  2107. // that we can properly diagnose redundant direct base types. Note
  2108. // that the key is always the unqualified canonical type of the base
  2109. // class.
  2110. std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
  2111. // Used to track indirect bases so we can see if a direct base is
  2112. // ambiguous.
  2113. IndirectBaseSet IndirectBaseTypes;
  2114. // Copy non-redundant base specifiers into permanent storage.
  2115. unsigned NumGoodBases = 0;
  2116. bool Invalid = false;
  2117. for (unsigned idx = 0; idx < Bases.size(); ++idx) {
  2118. QualType NewBaseType
  2119. = Context.getCanonicalType(Bases[idx]->getType());
  2120. NewBaseType = NewBaseType.getLocalUnqualifiedType();
  2121. CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
  2122. if (KnownBase) {
  2123. // C++ [class.mi]p3:
  2124. // A class shall not be specified as a direct base class of a
  2125. // derived class more than once.
  2126. Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
  2127. << KnownBase->getType() << Bases[idx]->getSourceRange();
  2128. // Delete the duplicate base class specifier; we're going to
  2129. // overwrite its pointer later.
  2130. Context.Deallocate(Bases[idx]);
  2131. Invalid = true;
  2132. } else {
  2133. // Okay, add this new base class.
  2134. KnownBase = Bases[idx];
  2135. Bases[NumGoodBases++] = Bases[idx];
  2136. // Note this base's direct & indirect bases, if there could be ambiguity.
  2137. if (Bases.size() > 1)
  2138. NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
  2139. if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
  2140. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  2141. if (Class->isInterface() &&
  2142. (!RD->isInterfaceLike() ||
  2143. KnownBase->getAccessSpecifier() != AS_public)) {
  2144. // The Microsoft extension __interface does not permit bases that
  2145. // are not themselves public interfaces.
  2146. Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
  2147. << getRecordDiagFromTagKind(RD->getTagKind()) << RD
  2148. << RD->getSourceRange();
  2149. Invalid = true;
  2150. }
  2151. if (RD->hasAttr<WeakAttr>())
  2152. Class->addAttr(WeakAttr::CreateImplicit(Context));
  2153. }
  2154. }
  2155. }
  2156. // Attach the remaining base class specifiers to the derived class.
  2157. Class->setBases(Bases.data(), NumGoodBases);
  2158. // Check that the only base classes that are duplicate are virtual.
  2159. for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
  2160. // Check whether this direct base is inaccessible due to ambiguity.
  2161. QualType BaseType = Bases[idx]->getType();
  2162. // Skip all dependent types in templates being used as base specifiers.
  2163. // Checks below assume that the base specifier is a CXXRecord.
  2164. if (BaseType->isDependentType())
  2165. continue;
  2166. CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
  2167. .getUnqualifiedType();
  2168. if (IndirectBaseTypes.count(CanonicalBase)) {
  2169. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2170. /*DetectVirtual=*/true);
  2171. bool found
  2172. = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
  2173. assert(found);
  2174. (void)found;
  2175. if (Paths.isAmbiguous(CanonicalBase))
  2176. Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
  2177. << BaseType << getAmbiguousPathsDisplayString(Paths)
  2178. << Bases[idx]->getSourceRange();
  2179. else
  2180. assert(Bases[idx]->isVirtual());
  2181. }
  2182. // Delete the base class specifier, since its data has been copied
  2183. // into the CXXRecordDecl.
  2184. Context.Deallocate(Bases[idx]);
  2185. }
  2186. return Invalid;
  2187. }
  2188. /// ActOnBaseSpecifiers - Attach the given base specifiers to the
  2189. /// class, after checking whether there are any duplicate base
  2190. /// classes.
  2191. void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
  2192. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2193. if (!ClassDecl || Bases.empty())
  2194. return;
  2195. AdjustDeclIfTemplate(ClassDecl);
  2196. AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
  2197. }
  2198. /// Determine whether the type \p Derived is a C++ class that is
  2199. /// derived from the type \p Base.
  2200. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
  2201. if (!getLangOpts().CPlusPlus)
  2202. return false;
  2203. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2204. if (!DerivedRD)
  2205. return false;
  2206. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2207. if (!BaseRD)
  2208. return false;
  2209. // If either the base or the derived type is invalid, don't try to
  2210. // check whether one is derived from the other.
  2211. if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
  2212. return false;
  2213. // FIXME: In a modules build, do we need the entire path to be visible for us
  2214. // to be able to use the inheritance relationship?
  2215. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2216. return false;
  2217. return DerivedRD->isDerivedFrom(BaseRD);
  2218. }
  2219. /// Determine whether the type \p Derived is a C++ class that is
  2220. /// derived from the type \p Base.
  2221. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
  2222. CXXBasePaths &Paths) {
  2223. if (!getLangOpts().CPlusPlus)
  2224. return false;
  2225. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2226. if (!DerivedRD)
  2227. return false;
  2228. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2229. if (!BaseRD)
  2230. return false;
  2231. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2232. return false;
  2233. return DerivedRD->isDerivedFrom(BaseRD, Paths);
  2234. }
  2235. static void BuildBasePathArray(const CXXBasePath &Path,
  2236. CXXCastPath &BasePathArray) {
  2237. // We first go backward and check if we have a virtual base.
  2238. // FIXME: It would be better if CXXBasePath had the base specifier for
  2239. // the nearest virtual base.
  2240. unsigned Start = 0;
  2241. for (unsigned I = Path.size(); I != 0; --I) {
  2242. if (Path[I - 1].Base->isVirtual()) {
  2243. Start = I - 1;
  2244. break;
  2245. }
  2246. }
  2247. // Now add all bases.
  2248. for (unsigned I = Start, E = Path.size(); I != E; ++I)
  2249. BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
  2250. }
  2251. void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
  2252. CXXCastPath &BasePathArray) {
  2253. assert(BasePathArray.empty() && "Base path array must be empty!");
  2254. assert(Paths.isRecordingPaths() && "Must record paths!");
  2255. return ::BuildBasePathArray(Paths.front(), BasePathArray);
  2256. }
  2257. /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
  2258. /// conversion (where Derived and Base are class types) is
  2259. /// well-formed, meaning that the conversion is unambiguous (and
  2260. /// that all of the base classes are accessible). Returns true
  2261. /// and emits a diagnostic if the code is ill-formed, returns false
  2262. /// otherwise. Loc is the location where this routine should point to
  2263. /// if there is an error, and Range is the source range to highlight
  2264. /// if there is an error.
  2265. ///
  2266. /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
  2267. /// diagnostic for the respective type of error will be suppressed, but the
  2268. /// check for ill-formed code will still be performed.
  2269. bool
  2270. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2271. unsigned InaccessibleBaseID,
  2272. unsigned AmbigiousBaseConvID,
  2273. SourceLocation Loc, SourceRange Range,
  2274. DeclarationName Name,
  2275. CXXCastPath *BasePath,
  2276. bool IgnoreAccess) {
  2277. // First, determine whether the path from Derived to Base is
  2278. // ambiguous. This is slightly more expensive than checking whether
  2279. // the Derived to Base conversion exists, because here we need to
  2280. // explore multiple paths to determine if there is an ambiguity.
  2281. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2282. /*DetectVirtual=*/false);
  2283. bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2284. if (!DerivationOkay)
  2285. return true;
  2286. const CXXBasePath *Path = nullptr;
  2287. if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
  2288. Path = &Paths.front();
  2289. // For MSVC compatibility, check if Derived directly inherits from Base. Clang
  2290. // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
  2291. // user to access such bases.
  2292. if (!Path && getLangOpts().MSVCCompat) {
  2293. for (const CXXBasePath &PossiblePath : Paths) {
  2294. if (PossiblePath.size() == 1) {
  2295. Path = &PossiblePath;
  2296. if (AmbigiousBaseConvID)
  2297. Diag(Loc, diag::ext_ms_ambiguous_direct_base)
  2298. << Base << Derived << Range;
  2299. break;
  2300. }
  2301. }
  2302. }
  2303. if (Path) {
  2304. if (!IgnoreAccess) {
  2305. // Check that the base class can be accessed.
  2306. switch (
  2307. CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
  2308. case AR_inaccessible:
  2309. return true;
  2310. case AR_accessible:
  2311. case AR_dependent:
  2312. case AR_delayed:
  2313. break;
  2314. }
  2315. }
  2316. // Build a base path if necessary.
  2317. if (BasePath)
  2318. ::BuildBasePathArray(*Path, *BasePath);
  2319. return false;
  2320. }
  2321. if (AmbigiousBaseConvID) {
  2322. // We know that the derived-to-base conversion is ambiguous, and
  2323. // we're going to produce a diagnostic. Perform the derived-to-base
  2324. // search just one more time to compute all of the possible paths so
  2325. // that we can print them out. This is more expensive than any of
  2326. // the previous derived-to-base checks we've done, but at this point
  2327. // performance isn't as much of an issue.
  2328. Paths.clear();
  2329. Paths.setRecordingPaths(true);
  2330. bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2331. assert(StillOkay && "Can only be used with a derived-to-base conversion");
  2332. (void)StillOkay;
  2333. // Build up a textual representation of the ambiguous paths, e.g.,
  2334. // D -> B -> A, that will be used to illustrate the ambiguous
  2335. // conversions in the diagnostic. We only print one of the paths
  2336. // to each base class subobject.
  2337. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2338. Diag(Loc, AmbigiousBaseConvID)
  2339. << Derived << Base << PathDisplayStr << Range << Name;
  2340. }
  2341. return true;
  2342. }
  2343. bool
  2344. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2345. SourceLocation Loc, SourceRange Range,
  2346. CXXCastPath *BasePath,
  2347. bool IgnoreAccess) {
  2348. return CheckDerivedToBaseConversion(
  2349. Derived, Base, diag::err_upcast_to_inaccessible_base,
  2350. diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
  2351. BasePath, IgnoreAccess);
  2352. }
  2353. /// Builds a string representing ambiguous paths from a
  2354. /// specific derived class to different subobjects of the same base
  2355. /// class.
  2356. ///
  2357. /// This function builds a string that can be used in error messages
  2358. /// to show the different paths that one can take through the
  2359. /// inheritance hierarchy to go from the derived class to different
  2360. /// subobjects of a base class. The result looks something like this:
  2361. /// @code
  2362. /// struct D -> struct B -> struct A
  2363. /// struct D -> struct C -> struct A
  2364. /// @endcode
  2365. std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
  2366. std::string PathDisplayStr;
  2367. std::set<unsigned> DisplayedPaths;
  2368. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  2369. Path != Paths.end(); ++Path) {
  2370. if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
  2371. // We haven't displayed a path to this particular base
  2372. // class subobject yet.
  2373. PathDisplayStr += "\n ";
  2374. PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
  2375. for (CXXBasePath::const_iterator Element = Path->begin();
  2376. Element != Path->end(); ++Element)
  2377. PathDisplayStr += " -> " + Element->Base->getType().getAsString();
  2378. }
  2379. }
  2380. return PathDisplayStr;
  2381. }
  2382. //===----------------------------------------------------------------------===//
  2383. // C++ class member Handling
  2384. //===----------------------------------------------------------------------===//
  2385. /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
  2386. bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
  2387. SourceLocation ColonLoc,
  2388. const ParsedAttributesView &Attrs) {
  2389. assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
  2390. AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
  2391. ASLoc, ColonLoc);
  2392. CurContext->addHiddenDecl(ASDecl);
  2393. return ProcessAccessDeclAttributeList(ASDecl, Attrs);
  2394. }
  2395. /// CheckOverrideControl - Check C++11 override control semantics.
  2396. void Sema::CheckOverrideControl(NamedDecl *D) {
  2397. if (D->isInvalidDecl())
  2398. return;
  2399. // We only care about "override" and "final" declarations.
  2400. if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
  2401. return;
  2402. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2403. // We can't check dependent instance methods.
  2404. if (MD && MD->isInstance() &&
  2405. (MD->getParent()->hasAnyDependentBases() ||
  2406. MD->getType()->isDependentType()))
  2407. return;
  2408. if (MD && !MD->isVirtual()) {
  2409. // If we have a non-virtual method, check if if hides a virtual method.
  2410. // (In that case, it's most likely the method has the wrong type.)
  2411. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  2412. FindHiddenVirtualMethods(MD, OverloadedMethods);
  2413. if (!OverloadedMethods.empty()) {
  2414. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2415. Diag(OA->getLocation(),
  2416. diag::override_keyword_hides_virtual_member_function)
  2417. << "override" << (OverloadedMethods.size() > 1);
  2418. } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2419. Diag(FA->getLocation(),
  2420. diag::override_keyword_hides_virtual_member_function)
  2421. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2422. << (OverloadedMethods.size() > 1);
  2423. }
  2424. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  2425. MD->setInvalidDecl();
  2426. return;
  2427. }
  2428. // Fall through into the general case diagnostic.
  2429. // FIXME: We might want to attempt typo correction here.
  2430. }
  2431. if (!MD || !MD->isVirtual()) {
  2432. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2433. Diag(OA->getLocation(),
  2434. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2435. << "override" << FixItHint::CreateRemoval(OA->getLocation());
  2436. D->dropAttr<OverrideAttr>();
  2437. }
  2438. if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2439. Diag(FA->getLocation(),
  2440. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2441. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2442. << FixItHint::CreateRemoval(FA->getLocation());
  2443. D->dropAttr<FinalAttr>();
  2444. }
  2445. return;
  2446. }
  2447. // C++11 [class.virtual]p5:
  2448. // If a function is marked with the virt-specifier override and
  2449. // does not override a member function of a base class, the program is
  2450. // ill-formed.
  2451. bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
  2452. if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
  2453. Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
  2454. << MD->getDeclName();
  2455. }
  2456. void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
  2457. if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
  2458. return;
  2459. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2460. if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
  2461. return;
  2462. SourceLocation Loc = MD->getLocation();
  2463. SourceLocation SpellingLoc = Loc;
  2464. if (getSourceManager().isMacroArgExpansion(Loc))
  2465. SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
  2466. SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
  2467. if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
  2468. return;
  2469. if (MD->size_overridden_methods() > 0) {
  2470. unsigned DiagID = isa<CXXDestructorDecl>(MD)
  2471. ? diag::warn_destructor_marked_not_override_overriding
  2472. : diag::warn_function_marked_not_override_overriding;
  2473. Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  2474. const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
  2475. Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
  2476. }
  2477. }
  2478. /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
  2479. /// function overrides a virtual member function marked 'final', according to
  2480. /// C++11 [class.virtual]p4.
  2481. bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
  2482. const CXXMethodDecl *Old) {
  2483. FinalAttr *FA = Old->getAttr<FinalAttr>();
  2484. if (!FA)
  2485. return false;
  2486. Diag(New->getLocation(), diag::err_final_function_overridden)
  2487. << New->getDeclName()
  2488. << FA->isSpelledAsSealed();
  2489. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  2490. return true;
  2491. }
  2492. static bool InitializationHasSideEffects(const FieldDecl &FD) {
  2493. const Type *T = FD.getType()->getBaseElementTypeUnsafe();
  2494. // FIXME: Destruction of ObjC lifetime types has side-effects.
  2495. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  2496. return !RD->isCompleteDefinition() ||
  2497. !RD->hasTrivialDefaultConstructor() ||
  2498. !RD->hasTrivialDestructor();
  2499. return false;
  2500. }
  2501. static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
  2502. ParsedAttributesView::const_iterator Itr =
  2503. llvm::find_if(list, [](const ParsedAttr &AL) {
  2504. return AL.isDeclspecPropertyAttribute();
  2505. });
  2506. if (Itr != list.end())
  2507. return &*Itr;
  2508. return nullptr;
  2509. }
  2510. // Check if there is a field shadowing.
  2511. void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
  2512. DeclarationName FieldName,
  2513. const CXXRecordDecl *RD,
  2514. bool DeclIsField) {
  2515. if (Diags.isIgnored(diag::warn_shadow_field, Loc))
  2516. return;
  2517. // To record a shadowed field in a base
  2518. std::map<CXXRecordDecl*, NamedDecl*> Bases;
  2519. auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
  2520. CXXBasePath &Path) {
  2521. const auto Base = Specifier->getType()->getAsCXXRecordDecl();
  2522. // Record an ambiguous path directly
  2523. if (Bases.find(Base) != Bases.end())
  2524. return true;
  2525. for (const auto Field : Base->lookup(FieldName)) {
  2526. if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
  2527. Field->getAccess() != AS_private) {
  2528. assert(Field->getAccess() != AS_none);
  2529. assert(Bases.find(Base) == Bases.end());
  2530. Bases[Base] = Field;
  2531. return true;
  2532. }
  2533. }
  2534. return false;
  2535. };
  2536. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2537. /*DetectVirtual=*/true);
  2538. if (!RD->lookupInBases(FieldShadowed, Paths))
  2539. return;
  2540. for (const auto &P : Paths) {
  2541. auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
  2542. auto It = Bases.find(Base);
  2543. // Skip duplicated bases
  2544. if (It == Bases.end())
  2545. continue;
  2546. auto BaseField = It->second;
  2547. assert(BaseField->getAccess() != AS_private);
  2548. if (AS_none !=
  2549. CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
  2550. Diag(Loc, diag::warn_shadow_field)
  2551. << FieldName << RD << Base << DeclIsField;
  2552. Diag(BaseField->getLocation(), diag::note_shadow_field);
  2553. Bases.erase(It);
  2554. }
  2555. }
  2556. }
  2557. /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
  2558. /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
  2559. /// bitfield width if there is one, 'InitExpr' specifies the initializer if
  2560. /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
  2561. /// present (but parsing it has been deferred).
  2562. NamedDecl *
  2563. Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
  2564. MultiTemplateParamsArg TemplateParameterLists,
  2565. Expr *BW, const VirtSpecifiers &VS,
  2566. InClassInitStyle InitStyle) {
  2567. const DeclSpec &DS = D.getDeclSpec();
  2568. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  2569. DeclarationName Name = NameInfo.getName();
  2570. SourceLocation Loc = NameInfo.getLoc();
  2571. // For anonymous bitfields, the location should point to the type.
  2572. if (Loc.isInvalid())
  2573. Loc = D.getBeginLoc();
  2574. Expr *BitWidth = static_cast<Expr*>(BW);
  2575. assert(isa<CXXRecordDecl>(CurContext));
  2576. assert(!DS.isFriendSpecified());
  2577. bool isFunc = D.isDeclarationOfFunction();
  2578. const ParsedAttr *MSPropertyAttr =
  2579. getMSPropertyAttr(D.getDeclSpec().getAttributes());
  2580. if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
  2581. // The Microsoft extension __interface only permits public member functions
  2582. // and prohibits constructors, destructors, operators, non-public member
  2583. // functions, static methods and data members.
  2584. unsigned InvalidDecl;
  2585. bool ShowDeclName = true;
  2586. if (!isFunc &&
  2587. (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
  2588. InvalidDecl = 0;
  2589. else if (!isFunc)
  2590. InvalidDecl = 1;
  2591. else if (AS != AS_public)
  2592. InvalidDecl = 2;
  2593. else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
  2594. InvalidDecl = 3;
  2595. else switch (Name.getNameKind()) {
  2596. case DeclarationName::CXXConstructorName:
  2597. InvalidDecl = 4;
  2598. ShowDeclName = false;
  2599. break;
  2600. case DeclarationName::CXXDestructorName:
  2601. InvalidDecl = 5;
  2602. ShowDeclName = false;
  2603. break;
  2604. case DeclarationName::CXXOperatorName:
  2605. case DeclarationName::CXXConversionFunctionName:
  2606. InvalidDecl = 6;
  2607. break;
  2608. default:
  2609. InvalidDecl = 0;
  2610. break;
  2611. }
  2612. if (InvalidDecl) {
  2613. if (ShowDeclName)
  2614. Diag(Loc, diag::err_invalid_member_in_interface)
  2615. << (InvalidDecl-1) << Name;
  2616. else
  2617. Diag(Loc, diag::err_invalid_member_in_interface)
  2618. << (InvalidDecl-1) << "";
  2619. return nullptr;
  2620. }
  2621. }
  2622. // C++ 9.2p6: A member shall not be declared to have automatic storage
  2623. // duration (auto, register) or with the extern storage-class-specifier.
  2624. // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
  2625. // data members and cannot be applied to names declared const or static,
  2626. // and cannot be applied to reference members.
  2627. switch (DS.getStorageClassSpec()) {
  2628. case DeclSpec::SCS_unspecified:
  2629. case DeclSpec::SCS_typedef:
  2630. case DeclSpec::SCS_static:
  2631. break;
  2632. case DeclSpec::SCS_mutable:
  2633. if (isFunc) {
  2634. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
  2635. // FIXME: It would be nicer if the keyword was ignored only for this
  2636. // declarator. Otherwise we could get follow-up errors.
  2637. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2638. }
  2639. break;
  2640. default:
  2641. Diag(DS.getStorageClassSpecLoc(),
  2642. diag::err_storageclass_invalid_for_member);
  2643. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2644. break;
  2645. }
  2646. bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
  2647. DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
  2648. !isFunc);
  2649. if (DS.isConstexprSpecified() && isInstField) {
  2650. SemaDiagnosticBuilder B =
  2651. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
  2652. SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
  2653. if (InitStyle == ICIS_NoInit) {
  2654. B << 0 << 0;
  2655. if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
  2656. B << FixItHint::CreateRemoval(ConstexprLoc);
  2657. else {
  2658. B << FixItHint::CreateReplacement(ConstexprLoc, "const");
  2659. D.getMutableDeclSpec().ClearConstexprSpec();
  2660. const char *PrevSpec;
  2661. unsigned DiagID;
  2662. bool Failed = D.getMutableDeclSpec().SetTypeQual(
  2663. DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
  2664. (void)Failed;
  2665. assert(!Failed && "Making a constexpr member const shouldn't fail");
  2666. }
  2667. } else {
  2668. B << 1;
  2669. const char *PrevSpec;
  2670. unsigned DiagID;
  2671. if (D.getMutableDeclSpec().SetStorageClassSpec(
  2672. *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
  2673. Context.getPrintingPolicy())) {
  2674. assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
  2675. "This is the only DeclSpec that should fail to be applied");
  2676. B << 1;
  2677. } else {
  2678. B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
  2679. isInstField = false;
  2680. }
  2681. }
  2682. }
  2683. NamedDecl *Member;
  2684. if (isInstField) {
  2685. CXXScopeSpec &SS = D.getCXXScopeSpec();
  2686. // Data members must have identifiers for names.
  2687. if (!Name.isIdentifier()) {
  2688. Diag(Loc, diag::err_bad_variable_name)
  2689. << Name;
  2690. return nullptr;
  2691. }
  2692. IdentifierInfo *II = Name.getAsIdentifierInfo();
  2693. // Member field could not be with "template" keyword.
  2694. // So TemplateParameterLists should be empty in this case.
  2695. if (TemplateParameterLists.size()) {
  2696. TemplateParameterList* TemplateParams = TemplateParameterLists[0];
  2697. if (TemplateParams->size()) {
  2698. // There is no such thing as a member field template.
  2699. Diag(D.getIdentifierLoc(), diag::err_template_member)
  2700. << II
  2701. << SourceRange(TemplateParams->getTemplateLoc(),
  2702. TemplateParams->getRAngleLoc());
  2703. } else {
  2704. // There is an extraneous 'template<>' for this member.
  2705. Diag(TemplateParams->getTemplateLoc(),
  2706. diag::err_template_member_noparams)
  2707. << II
  2708. << SourceRange(TemplateParams->getTemplateLoc(),
  2709. TemplateParams->getRAngleLoc());
  2710. }
  2711. return nullptr;
  2712. }
  2713. if (SS.isSet() && !SS.isInvalid()) {
  2714. // The user provided a superfluous scope specifier inside a class
  2715. // definition:
  2716. //
  2717. // class X {
  2718. // int X::member;
  2719. // };
  2720. if (DeclContext *DC = computeDeclContext(SS, false))
  2721. diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
  2722. D.getName().getKind() ==
  2723. UnqualifiedIdKind::IK_TemplateId);
  2724. else
  2725. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  2726. << Name << SS.getRange();
  2727. SS.clear();
  2728. }
  2729. if (MSPropertyAttr) {
  2730. Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2731. BitWidth, InitStyle, AS, *MSPropertyAttr);
  2732. if (!Member)
  2733. return nullptr;
  2734. isInstField = false;
  2735. } else {
  2736. Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2737. BitWidth, InitStyle, AS);
  2738. if (!Member)
  2739. return nullptr;
  2740. }
  2741. CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
  2742. } else {
  2743. Member = HandleDeclarator(S, D, TemplateParameterLists);
  2744. if (!Member)
  2745. return nullptr;
  2746. // Non-instance-fields can't have a bitfield.
  2747. if (BitWidth) {
  2748. if (Member->isInvalidDecl()) {
  2749. // don't emit another diagnostic.
  2750. } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
  2751. // C++ 9.6p3: A bit-field shall not be a static member.
  2752. // "static member 'A' cannot be a bit-field"
  2753. Diag(Loc, diag::err_static_not_bitfield)
  2754. << Name << BitWidth->getSourceRange();
  2755. } else if (isa<TypedefDecl>(Member)) {
  2756. // "typedef member 'x' cannot be a bit-field"
  2757. Diag(Loc, diag::err_typedef_not_bitfield)
  2758. << Name << BitWidth->getSourceRange();
  2759. } else {
  2760. // A function typedef ("typedef int f(); f a;").
  2761. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  2762. Diag(Loc, diag::err_not_integral_type_bitfield)
  2763. << Name << cast<ValueDecl>(Member)->getType()
  2764. << BitWidth->getSourceRange();
  2765. }
  2766. BitWidth = nullptr;
  2767. Member->setInvalidDecl();
  2768. }
  2769. NamedDecl *NonTemplateMember = Member;
  2770. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
  2771. NonTemplateMember = FunTmpl->getTemplatedDecl();
  2772. else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
  2773. NonTemplateMember = VarTmpl->getTemplatedDecl();
  2774. Member->setAccess(AS);
  2775. // If we have declared a member function template or static data member
  2776. // template, set the access of the templated declaration as well.
  2777. if (NonTemplateMember != Member)
  2778. NonTemplateMember->setAccess(AS);
  2779. // C++ [temp.deduct.guide]p3:
  2780. // A deduction guide [...] for a member class template [shall be
  2781. // declared] with the same access [as the template].
  2782. if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
  2783. auto *TD = DG->getDeducedTemplate();
  2784. if (AS != TD->getAccess()) {
  2785. Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
  2786. Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
  2787. << TD->getAccess();
  2788. const AccessSpecDecl *LastAccessSpec = nullptr;
  2789. for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
  2790. if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
  2791. LastAccessSpec = AccessSpec;
  2792. }
  2793. assert(LastAccessSpec && "differing access with no access specifier");
  2794. Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
  2795. << AS;
  2796. }
  2797. }
  2798. }
  2799. if (VS.isOverrideSpecified())
  2800. Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
  2801. if (VS.isFinalSpecified())
  2802. Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
  2803. VS.isFinalSpelledSealed()));
  2804. if (VS.getLastLocation().isValid()) {
  2805. // Update the end location of a method that has a virt-specifiers.
  2806. if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
  2807. MD->setRangeEnd(VS.getLastLocation());
  2808. }
  2809. CheckOverrideControl(Member);
  2810. assert((Name || isInstField) && "No identifier for non-field ?");
  2811. if (isInstField) {
  2812. FieldDecl *FD = cast<FieldDecl>(Member);
  2813. FieldCollector->Add(FD);
  2814. if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
  2815. // Remember all explicit private FieldDecls that have a name, no side
  2816. // effects and are not part of a dependent type declaration.
  2817. if (!FD->isImplicit() && FD->getDeclName() &&
  2818. FD->getAccess() == AS_private &&
  2819. !FD->hasAttr<UnusedAttr>() &&
  2820. !FD->getParent()->isDependentContext() &&
  2821. !InitializationHasSideEffects(*FD))
  2822. UnusedPrivateFields.insert(FD);
  2823. }
  2824. }
  2825. return Member;
  2826. }
  2827. namespace {
  2828. class UninitializedFieldVisitor
  2829. : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
  2830. Sema &S;
  2831. // List of Decls to generate a warning on. Also remove Decls that become
  2832. // initialized.
  2833. llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
  2834. // List of base classes of the record. Classes are removed after their
  2835. // initializers.
  2836. llvm::SmallPtrSetImpl<QualType> &BaseClasses;
  2837. // Vector of decls to be removed from the Decl set prior to visiting the
  2838. // nodes. These Decls may have been initialized in the prior initializer.
  2839. llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
  2840. // If non-null, add a note to the warning pointing back to the constructor.
  2841. const CXXConstructorDecl *Constructor;
  2842. // Variables to hold state when processing an initializer list. When
  2843. // InitList is true, special case initialization of FieldDecls matching
  2844. // InitListFieldDecl.
  2845. bool InitList;
  2846. FieldDecl *InitListFieldDecl;
  2847. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  2848. public:
  2849. typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
  2850. UninitializedFieldVisitor(Sema &S,
  2851. llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
  2852. llvm::SmallPtrSetImpl<QualType> &BaseClasses)
  2853. : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
  2854. Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
  2855. // Returns true if the use of ME is not an uninitialized use.
  2856. bool IsInitListMemberExprInitialized(MemberExpr *ME,
  2857. bool CheckReferenceOnly) {
  2858. llvm::SmallVector<FieldDecl*, 4> Fields;
  2859. bool ReferenceField = false;
  2860. while (ME) {
  2861. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  2862. if (!FD)
  2863. return false;
  2864. Fields.push_back(FD);
  2865. if (FD->getType()->isReferenceType())
  2866. ReferenceField = true;
  2867. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
  2868. }
  2869. // Binding a reference to an unintialized field is not an
  2870. // uninitialized use.
  2871. if (CheckReferenceOnly && !ReferenceField)
  2872. return true;
  2873. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  2874. // Discard the first field since it is the field decl that is being
  2875. // initialized.
  2876. for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
  2877. UsedFieldIndex.push_back((*I)->getFieldIndex());
  2878. }
  2879. for (auto UsedIter = UsedFieldIndex.begin(),
  2880. UsedEnd = UsedFieldIndex.end(),
  2881. OrigIter = InitFieldIndex.begin(),
  2882. OrigEnd = InitFieldIndex.end();
  2883. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  2884. if (*UsedIter < *OrigIter)
  2885. return true;
  2886. if (*UsedIter > *OrigIter)
  2887. break;
  2888. }
  2889. return false;
  2890. }
  2891. void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
  2892. bool AddressOf) {
  2893. if (isa<EnumConstantDecl>(ME->getMemberDecl()))
  2894. return;
  2895. // FieldME is the inner-most MemberExpr that is not an anonymous struct
  2896. // or union.
  2897. MemberExpr *FieldME = ME;
  2898. bool AllPODFields = FieldME->getType().isPODType(S.Context);
  2899. Expr *Base = ME;
  2900. while (MemberExpr *SubME =
  2901. dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
  2902. if (isa<VarDecl>(SubME->getMemberDecl()))
  2903. return;
  2904. if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
  2905. if (!FD->isAnonymousStructOrUnion())
  2906. FieldME = SubME;
  2907. if (!FieldME->getType().isPODType(S.Context))
  2908. AllPODFields = false;
  2909. Base = SubME->getBase();
  2910. }
  2911. if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
  2912. return;
  2913. if (AddressOf && AllPODFields)
  2914. return;
  2915. ValueDecl* FoundVD = FieldME->getMemberDecl();
  2916. if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
  2917. while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
  2918. BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
  2919. }
  2920. if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
  2921. QualType T = BaseCast->getType();
  2922. if (T->isPointerType() &&
  2923. BaseClasses.count(T->getPointeeType())) {
  2924. S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
  2925. << T->getPointeeType() << FoundVD;
  2926. }
  2927. }
  2928. }
  2929. if (!Decls.count(FoundVD))
  2930. return;
  2931. const bool IsReference = FoundVD->getType()->isReferenceType();
  2932. if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
  2933. // Special checking for initializer lists.
  2934. if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
  2935. return;
  2936. }
  2937. } else {
  2938. // Prevent double warnings on use of unbounded references.
  2939. if (CheckReferenceOnly && !IsReference)
  2940. return;
  2941. }
  2942. unsigned diag = IsReference
  2943. ? diag::warn_reference_field_is_uninit
  2944. : diag::warn_field_is_uninit;
  2945. S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
  2946. if (Constructor)
  2947. S.Diag(Constructor->getLocation(),
  2948. diag::note_uninit_in_this_constructor)
  2949. << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
  2950. }
  2951. void HandleValue(Expr *E, bool AddressOf) {
  2952. E = E->IgnoreParens();
  2953. if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  2954. HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
  2955. AddressOf /*AddressOf*/);
  2956. return;
  2957. }
  2958. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  2959. Visit(CO->getCond());
  2960. HandleValue(CO->getTrueExpr(), AddressOf);
  2961. HandleValue(CO->getFalseExpr(), AddressOf);
  2962. return;
  2963. }
  2964. if (BinaryConditionalOperator *BCO =
  2965. dyn_cast<BinaryConditionalOperator>(E)) {
  2966. Visit(BCO->getCond());
  2967. HandleValue(BCO->getFalseExpr(), AddressOf);
  2968. return;
  2969. }
  2970. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  2971. HandleValue(OVE->getSourceExpr(), AddressOf);
  2972. return;
  2973. }
  2974. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  2975. switch (BO->getOpcode()) {
  2976. default:
  2977. break;
  2978. case(BO_PtrMemD):
  2979. case(BO_PtrMemI):
  2980. HandleValue(BO->getLHS(), AddressOf);
  2981. Visit(BO->getRHS());
  2982. return;
  2983. case(BO_Comma):
  2984. Visit(BO->getLHS());
  2985. HandleValue(BO->getRHS(), AddressOf);
  2986. return;
  2987. }
  2988. }
  2989. Visit(E);
  2990. }
  2991. void CheckInitListExpr(InitListExpr *ILE) {
  2992. InitFieldIndex.push_back(0);
  2993. for (auto Child : ILE->children()) {
  2994. if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
  2995. CheckInitListExpr(SubList);
  2996. } else {
  2997. Visit(Child);
  2998. }
  2999. ++InitFieldIndex.back();
  3000. }
  3001. InitFieldIndex.pop_back();
  3002. }
  3003. void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
  3004. FieldDecl *Field, const Type *BaseClass) {
  3005. // Remove Decls that may have been initialized in the previous
  3006. // initializer.
  3007. for (ValueDecl* VD : DeclsToRemove)
  3008. Decls.erase(VD);
  3009. DeclsToRemove.clear();
  3010. Constructor = FieldConstructor;
  3011. InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  3012. if (ILE && Field) {
  3013. InitList = true;
  3014. InitListFieldDecl = Field;
  3015. InitFieldIndex.clear();
  3016. CheckInitListExpr(ILE);
  3017. } else {
  3018. InitList = false;
  3019. Visit(E);
  3020. }
  3021. if (Field)
  3022. Decls.erase(Field);
  3023. if (BaseClass)
  3024. BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
  3025. }
  3026. void VisitMemberExpr(MemberExpr *ME) {
  3027. // All uses of unbounded reference fields will warn.
  3028. HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
  3029. }
  3030. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  3031. if (E->getCastKind() == CK_LValueToRValue) {
  3032. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3033. return;
  3034. }
  3035. Inherited::VisitImplicitCastExpr(E);
  3036. }
  3037. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  3038. if (E->getConstructor()->isCopyConstructor()) {
  3039. Expr *ArgExpr = E->getArg(0);
  3040. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  3041. if (ILE->getNumInits() == 1)
  3042. ArgExpr = ILE->getInit(0);
  3043. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  3044. if (ICE->getCastKind() == CK_NoOp)
  3045. ArgExpr = ICE->getSubExpr();
  3046. HandleValue(ArgExpr, false /*AddressOf*/);
  3047. return;
  3048. }
  3049. Inherited::VisitCXXConstructExpr(E);
  3050. }
  3051. void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  3052. Expr *Callee = E->getCallee();
  3053. if (isa<MemberExpr>(Callee)) {
  3054. HandleValue(Callee, false /*AddressOf*/);
  3055. for (auto Arg : E->arguments())
  3056. Visit(Arg);
  3057. return;
  3058. }
  3059. Inherited::VisitCXXMemberCallExpr(E);
  3060. }
  3061. void VisitCallExpr(CallExpr *E) {
  3062. // Treat std::move as a use.
  3063. if (E->isCallToStdMove()) {
  3064. HandleValue(E->getArg(0), /*AddressOf=*/false);
  3065. return;
  3066. }
  3067. Inherited::VisitCallExpr(E);
  3068. }
  3069. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  3070. Expr *Callee = E->getCallee();
  3071. if (isa<UnresolvedLookupExpr>(Callee))
  3072. return Inherited::VisitCXXOperatorCallExpr(E);
  3073. Visit(Callee);
  3074. for (auto Arg : E->arguments())
  3075. HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
  3076. }
  3077. void VisitBinaryOperator(BinaryOperator *E) {
  3078. // If a field assignment is detected, remove the field from the
  3079. // uninitiailized field set.
  3080. if (E->getOpcode() == BO_Assign)
  3081. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
  3082. if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  3083. if (!FD->getType()->isReferenceType())
  3084. DeclsToRemove.push_back(FD);
  3085. if (E->isCompoundAssignmentOp()) {
  3086. HandleValue(E->getLHS(), false /*AddressOf*/);
  3087. Visit(E->getRHS());
  3088. return;
  3089. }
  3090. Inherited::VisitBinaryOperator(E);
  3091. }
  3092. void VisitUnaryOperator(UnaryOperator *E) {
  3093. if (E->isIncrementDecrementOp()) {
  3094. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3095. return;
  3096. }
  3097. if (E->getOpcode() == UO_AddrOf) {
  3098. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
  3099. HandleValue(ME->getBase(), true /*AddressOf*/);
  3100. return;
  3101. }
  3102. }
  3103. Inherited::VisitUnaryOperator(E);
  3104. }
  3105. };
  3106. // Diagnose value-uses of fields to initialize themselves, e.g.
  3107. // foo(foo)
  3108. // where foo is not also a parameter to the constructor.
  3109. // Also diagnose across field uninitialized use such as
  3110. // x(y), y(x)
  3111. // TODO: implement -Wuninitialized and fold this into that framework.
  3112. static void DiagnoseUninitializedFields(
  3113. Sema &SemaRef, const CXXConstructorDecl *Constructor) {
  3114. if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
  3115. Constructor->getLocation())) {
  3116. return;
  3117. }
  3118. if (Constructor->isInvalidDecl())
  3119. return;
  3120. const CXXRecordDecl *RD = Constructor->getParent();
  3121. if (RD->getDescribedClassTemplate())
  3122. return;
  3123. // Holds fields that are uninitialized.
  3124. llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
  3125. // At the beginning, all fields are uninitialized.
  3126. for (auto *I : RD->decls()) {
  3127. if (auto *FD = dyn_cast<FieldDecl>(I)) {
  3128. UninitializedFields.insert(FD);
  3129. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
  3130. UninitializedFields.insert(IFD->getAnonField());
  3131. }
  3132. }
  3133. llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
  3134. for (auto I : RD->bases())
  3135. UninitializedBaseClasses.insert(I.getType().getCanonicalType());
  3136. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3137. return;
  3138. UninitializedFieldVisitor UninitializedChecker(SemaRef,
  3139. UninitializedFields,
  3140. UninitializedBaseClasses);
  3141. for (const auto *FieldInit : Constructor->inits()) {
  3142. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3143. break;
  3144. Expr *InitExpr = FieldInit->getInit();
  3145. if (!InitExpr)
  3146. continue;
  3147. if (CXXDefaultInitExpr *Default =
  3148. dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
  3149. InitExpr = Default->getExpr();
  3150. if (!InitExpr)
  3151. continue;
  3152. // In class initializers will point to the constructor.
  3153. UninitializedChecker.CheckInitializer(InitExpr, Constructor,
  3154. FieldInit->getAnyMember(),
  3155. FieldInit->getBaseClass());
  3156. } else {
  3157. UninitializedChecker.CheckInitializer(InitExpr, nullptr,
  3158. FieldInit->getAnyMember(),
  3159. FieldInit->getBaseClass());
  3160. }
  3161. }
  3162. }
  3163. } // namespace
  3164. /// Enter a new C++ default initializer scope. After calling this, the
  3165. /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
  3166. /// parsing or instantiating the initializer failed.
  3167. void Sema::ActOnStartCXXInClassMemberInitializer() {
  3168. // Create a synthetic function scope to represent the call to the constructor
  3169. // that notionally surrounds a use of this initializer.
  3170. PushFunctionScope();
  3171. }
  3172. /// This is invoked after parsing an in-class initializer for a
  3173. /// non-static C++ class member, and after instantiating an in-class initializer
  3174. /// in a class template. Such actions are deferred until the class is complete.
  3175. void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
  3176. SourceLocation InitLoc,
  3177. Expr *InitExpr) {
  3178. // Pop the notional constructor scope we created earlier.
  3179. PopFunctionScopeInfo(nullptr, D);
  3180. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  3181. assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
  3182. "must set init style when field is created");
  3183. if (!InitExpr) {
  3184. D->setInvalidDecl();
  3185. if (FD)
  3186. FD->removeInClassInitializer();
  3187. return;
  3188. }
  3189. if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
  3190. FD->setInvalidDecl();
  3191. FD->removeInClassInitializer();
  3192. return;
  3193. }
  3194. ExprResult Init = InitExpr;
  3195. if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
  3196. InitializedEntity Entity =
  3197. InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
  3198. InitializationKind Kind =
  3199. FD->getInClassInitStyle() == ICIS_ListInit
  3200. ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
  3201. InitExpr->getBeginLoc(),
  3202. InitExpr->getEndLoc())
  3203. : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
  3204. InitializationSequence Seq(*this, Entity, Kind, InitExpr);
  3205. Init = Seq.Perform(*this, Entity, Kind, InitExpr);
  3206. if (Init.isInvalid()) {
  3207. FD->setInvalidDecl();
  3208. return;
  3209. }
  3210. }
  3211. // C++11 [class.base.init]p7:
  3212. // The initialization of each base and member constitutes a
  3213. // full-expression.
  3214. Init = ActOnFinishFullExpr(Init.get(), InitLoc);
  3215. if (Init.isInvalid()) {
  3216. FD->setInvalidDecl();
  3217. return;
  3218. }
  3219. InitExpr = Init.get();
  3220. FD->setInClassInitializer(InitExpr);
  3221. }
  3222. /// Find the direct and/or virtual base specifiers that
  3223. /// correspond to the given base type, for use in base initialization
  3224. /// within a constructor.
  3225. static bool FindBaseInitializer(Sema &SemaRef,
  3226. CXXRecordDecl *ClassDecl,
  3227. QualType BaseType,
  3228. const CXXBaseSpecifier *&DirectBaseSpec,
  3229. const CXXBaseSpecifier *&VirtualBaseSpec) {
  3230. // First, check for a direct base class.
  3231. DirectBaseSpec = nullptr;
  3232. for (const auto &Base : ClassDecl->bases()) {
  3233. if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
  3234. // We found a direct base of this type. That's what we're
  3235. // initializing.
  3236. DirectBaseSpec = &Base;
  3237. break;
  3238. }
  3239. }
  3240. // Check for a virtual base class.
  3241. // FIXME: We might be able to short-circuit this if we know in advance that
  3242. // there are no virtual bases.
  3243. VirtualBaseSpec = nullptr;
  3244. if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
  3245. // We haven't found a base yet; search the class hierarchy for a
  3246. // virtual base class.
  3247. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  3248. /*DetectVirtual=*/false);
  3249. if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
  3250. SemaRef.Context.getTypeDeclType(ClassDecl),
  3251. BaseType, Paths)) {
  3252. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  3253. Path != Paths.end(); ++Path) {
  3254. if (Path->back().Base->isVirtual()) {
  3255. VirtualBaseSpec = Path->back().Base;
  3256. break;
  3257. }
  3258. }
  3259. }
  3260. }
  3261. return DirectBaseSpec || VirtualBaseSpec;
  3262. }
  3263. /// Handle a C++ member initializer using braced-init-list syntax.
  3264. MemInitResult
  3265. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3266. Scope *S,
  3267. CXXScopeSpec &SS,
  3268. IdentifierInfo *MemberOrBase,
  3269. ParsedType TemplateTypeTy,
  3270. const DeclSpec &DS,
  3271. SourceLocation IdLoc,
  3272. Expr *InitList,
  3273. SourceLocation EllipsisLoc) {
  3274. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3275. DS, IdLoc, InitList,
  3276. EllipsisLoc);
  3277. }
  3278. /// Handle a C++ member initializer using parentheses syntax.
  3279. MemInitResult
  3280. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3281. Scope *S,
  3282. CXXScopeSpec &SS,
  3283. IdentifierInfo *MemberOrBase,
  3284. ParsedType TemplateTypeTy,
  3285. const DeclSpec &DS,
  3286. SourceLocation IdLoc,
  3287. SourceLocation LParenLoc,
  3288. ArrayRef<Expr *> Args,
  3289. SourceLocation RParenLoc,
  3290. SourceLocation EllipsisLoc) {
  3291. Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
  3292. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3293. DS, IdLoc, List, EllipsisLoc);
  3294. }
  3295. namespace {
  3296. // Callback to only accept typo corrections that can be a valid C++ member
  3297. // intializer: either a non-static field member or a base class.
  3298. class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
  3299. public:
  3300. explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
  3301. : ClassDecl(ClassDecl) {}
  3302. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3303. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  3304. if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
  3305. return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
  3306. return isa<TypeDecl>(ND);
  3307. }
  3308. return false;
  3309. }
  3310. private:
  3311. CXXRecordDecl *ClassDecl;
  3312. };
  3313. }
  3314. ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
  3315. CXXScopeSpec &SS,
  3316. ParsedType TemplateTypeTy,
  3317. IdentifierInfo *MemberOrBase) {
  3318. if (SS.getScopeRep() || TemplateTypeTy)
  3319. return nullptr;
  3320. DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
  3321. if (Result.empty())
  3322. return nullptr;
  3323. ValueDecl *Member;
  3324. if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
  3325. (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
  3326. return Member;
  3327. return nullptr;
  3328. }
  3329. /// Handle a C++ member initializer.
  3330. MemInitResult
  3331. Sema::BuildMemInitializer(Decl *ConstructorD,
  3332. Scope *S,
  3333. CXXScopeSpec &SS,
  3334. IdentifierInfo *MemberOrBase,
  3335. ParsedType TemplateTypeTy,
  3336. const DeclSpec &DS,
  3337. SourceLocation IdLoc,
  3338. Expr *Init,
  3339. SourceLocation EllipsisLoc) {
  3340. ExprResult Res = CorrectDelayedTyposInExpr(Init);
  3341. if (!Res.isUsable())
  3342. return true;
  3343. Init = Res.get();
  3344. if (!ConstructorD)
  3345. return true;
  3346. AdjustDeclIfTemplate(ConstructorD);
  3347. CXXConstructorDecl *Constructor
  3348. = dyn_cast<CXXConstructorDecl>(ConstructorD);
  3349. if (!Constructor) {
  3350. // The user wrote a constructor initializer on a function that is
  3351. // not a C++ constructor. Ignore the error for now, because we may
  3352. // have more member initializers coming; we'll diagnose it just
  3353. // once in ActOnMemInitializers.
  3354. return true;
  3355. }
  3356. CXXRecordDecl *ClassDecl = Constructor->getParent();
  3357. // C++ [class.base.init]p2:
  3358. // Names in a mem-initializer-id are looked up in the scope of the
  3359. // constructor's class and, if not found in that scope, are looked
  3360. // up in the scope containing the constructor's definition.
  3361. // [Note: if the constructor's class contains a member with the
  3362. // same name as a direct or virtual base class of the class, a
  3363. // mem-initializer-id naming the member or base class and composed
  3364. // of a single identifier refers to the class member. A
  3365. // mem-initializer-id for the hidden base class may be specified
  3366. // using a qualified name. ]
  3367. // Look for a member, first.
  3368. if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
  3369. ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
  3370. if (EllipsisLoc.isValid())
  3371. Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
  3372. << MemberOrBase
  3373. << SourceRange(IdLoc, Init->getSourceRange().getEnd());
  3374. return BuildMemberInitializer(Member, Init, IdLoc);
  3375. }
  3376. // It didn't name a member, so see if it names a class.
  3377. QualType BaseType;
  3378. TypeSourceInfo *TInfo = nullptr;
  3379. if (TemplateTypeTy) {
  3380. BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
  3381. } else if (DS.getTypeSpecType() == TST_decltype) {
  3382. BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
  3383. } else if (DS.getTypeSpecType() == TST_decltype_auto) {
  3384. Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
  3385. return true;
  3386. } else {
  3387. LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
  3388. LookupParsedName(R, S, &SS);
  3389. TypeDecl *TyD = R.getAsSingle<TypeDecl>();
  3390. if (!TyD) {
  3391. if (R.isAmbiguous()) return true;
  3392. // We don't want access-control diagnostics here.
  3393. R.suppressDiagnostics();
  3394. if (SS.isSet() && isDependentScopeSpecifier(SS)) {
  3395. bool NotUnknownSpecialization = false;
  3396. DeclContext *DC = computeDeclContext(SS, false);
  3397. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
  3398. NotUnknownSpecialization = !Record->hasAnyDependentBases();
  3399. if (!NotUnknownSpecialization) {
  3400. // When the scope specifier can refer to a member of an unknown
  3401. // specialization, we take it as a type name.
  3402. BaseType = CheckTypenameType(ETK_None, SourceLocation(),
  3403. SS.getWithLocInContext(Context),
  3404. *MemberOrBase, IdLoc);
  3405. if (BaseType.isNull())
  3406. return true;
  3407. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3408. DependentNameTypeLoc TL =
  3409. TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
  3410. if (!TL.isNull()) {
  3411. TL.setNameLoc(IdLoc);
  3412. TL.setElaboratedKeywordLoc(SourceLocation());
  3413. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3414. }
  3415. R.clear();
  3416. R.setLookupName(MemberOrBase);
  3417. }
  3418. }
  3419. // If no results were found, try to correct typos.
  3420. TypoCorrection Corr;
  3421. if (R.empty() && BaseType.isNull() &&
  3422. (Corr = CorrectTypo(
  3423. R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  3424. llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
  3425. CTK_ErrorRecovery, ClassDecl))) {
  3426. if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
  3427. // We have found a non-static data member with a similar
  3428. // name to what was typed; complain and initialize that
  3429. // member.
  3430. diagnoseTypo(Corr,
  3431. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3432. << MemberOrBase << true);
  3433. return BuildMemberInitializer(Member, Init, IdLoc);
  3434. } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
  3435. const CXXBaseSpecifier *DirectBaseSpec;
  3436. const CXXBaseSpecifier *VirtualBaseSpec;
  3437. if (FindBaseInitializer(*this, ClassDecl,
  3438. Context.getTypeDeclType(Type),
  3439. DirectBaseSpec, VirtualBaseSpec)) {
  3440. // We have found a direct or virtual base class with a
  3441. // similar name to what was typed; complain and initialize
  3442. // that base class.
  3443. diagnoseTypo(Corr,
  3444. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3445. << MemberOrBase << false,
  3446. PDiag() /*Suppress note, we provide our own.*/);
  3447. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
  3448. : VirtualBaseSpec;
  3449. Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
  3450. << BaseSpec->getType() << BaseSpec->getSourceRange();
  3451. TyD = Type;
  3452. }
  3453. }
  3454. }
  3455. if (!TyD && BaseType.isNull()) {
  3456. Diag(IdLoc, diag::err_mem_init_not_member_or_class)
  3457. << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
  3458. return true;
  3459. }
  3460. }
  3461. if (BaseType.isNull()) {
  3462. BaseType = Context.getTypeDeclType(TyD);
  3463. MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
  3464. if (SS.isSet()) {
  3465. BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
  3466. BaseType);
  3467. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3468. ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
  3469. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
  3470. TL.setElaboratedKeywordLoc(SourceLocation());
  3471. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3472. }
  3473. }
  3474. }
  3475. if (!TInfo)
  3476. TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
  3477. return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
  3478. }
  3479. MemInitResult
  3480. Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
  3481. SourceLocation IdLoc) {
  3482. FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
  3483. IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
  3484. assert((DirectMember || IndirectMember) &&
  3485. "Member must be a FieldDecl or IndirectFieldDecl");
  3486. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3487. return true;
  3488. if (Member->isInvalidDecl())
  3489. return true;
  3490. MultiExprArg Args;
  3491. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3492. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3493. } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  3494. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  3495. } else {
  3496. // Template instantiation doesn't reconstruct ParenListExprs for us.
  3497. Args = Init;
  3498. }
  3499. SourceRange InitRange = Init->getSourceRange();
  3500. if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
  3501. // Can't check initialization for a member of dependent type or when
  3502. // any of the arguments are type-dependent expressions.
  3503. DiscardCleanupsInEvaluationContext();
  3504. } else {
  3505. bool InitList = false;
  3506. if (isa<InitListExpr>(Init)) {
  3507. InitList = true;
  3508. Args = Init;
  3509. }
  3510. // Initialize the member.
  3511. InitializedEntity MemberEntity =
  3512. DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
  3513. : InitializedEntity::InitializeMember(IndirectMember,
  3514. nullptr);
  3515. InitializationKind Kind =
  3516. InitList ? InitializationKind::CreateDirectList(
  3517. IdLoc, Init->getBeginLoc(), Init->getEndLoc())
  3518. : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
  3519. InitRange.getEnd());
  3520. InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
  3521. ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
  3522. nullptr);
  3523. if (MemberInit.isInvalid())
  3524. return true;
  3525. // C++11 [class.base.init]p7:
  3526. // The initialization of each base and member constitutes a
  3527. // full-expression.
  3528. MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
  3529. if (MemberInit.isInvalid())
  3530. return true;
  3531. Init = MemberInit.get();
  3532. }
  3533. if (DirectMember) {
  3534. return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
  3535. InitRange.getBegin(), Init,
  3536. InitRange.getEnd());
  3537. } else {
  3538. return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
  3539. InitRange.getBegin(), Init,
  3540. InitRange.getEnd());
  3541. }
  3542. }
  3543. MemInitResult
  3544. Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
  3545. CXXRecordDecl *ClassDecl) {
  3546. SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3547. if (!LangOpts.CPlusPlus11)
  3548. return Diag(NameLoc, diag::err_delegating_ctor)
  3549. << TInfo->getTypeLoc().getLocalSourceRange();
  3550. Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
  3551. bool InitList = true;
  3552. MultiExprArg Args = Init;
  3553. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3554. InitList = false;
  3555. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3556. }
  3557. SourceRange InitRange = Init->getSourceRange();
  3558. // Initialize the object.
  3559. InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
  3560. QualType(ClassDecl->getTypeForDecl(), 0));
  3561. InitializationKind Kind =
  3562. InitList ? InitializationKind::CreateDirectList(
  3563. NameLoc, Init->getBeginLoc(), Init->getEndLoc())
  3564. : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
  3565. InitRange.getEnd());
  3566. InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
  3567. ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
  3568. Args, nullptr);
  3569. if (DelegationInit.isInvalid())
  3570. return true;
  3571. assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
  3572. "Delegating constructor with no target?");
  3573. // C++11 [class.base.init]p7:
  3574. // The initialization of each base and member constitutes a
  3575. // full-expression.
  3576. DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
  3577. InitRange.getBegin());
  3578. if (DelegationInit.isInvalid())
  3579. return true;
  3580. // If we are in a dependent context, template instantiation will
  3581. // perform this type-checking again. Just save the arguments that we
  3582. // received in a ParenListExpr.
  3583. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3584. // of the information that we have about the base
  3585. // initializer. However, deconstructing the ASTs is a dicey process,
  3586. // and this approach is far more likely to get the corner cases right.
  3587. if (CurContext->isDependentContext())
  3588. DelegationInit = Init;
  3589. return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
  3590. DelegationInit.getAs<Expr>(),
  3591. InitRange.getEnd());
  3592. }
  3593. MemInitResult
  3594. Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
  3595. Expr *Init, CXXRecordDecl *ClassDecl,
  3596. SourceLocation EllipsisLoc) {
  3597. SourceLocation BaseLoc
  3598. = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3599. if (!BaseType->isDependentType() && !BaseType->isRecordType())
  3600. return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
  3601. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3602. // C++ [class.base.init]p2:
  3603. // [...] Unless the mem-initializer-id names a nonstatic data
  3604. // member of the constructor's class or a direct or virtual base
  3605. // of that class, the mem-initializer is ill-formed. A
  3606. // mem-initializer-list can initialize a base class using any
  3607. // name that denotes that base class type.
  3608. bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
  3609. SourceRange InitRange = Init->getSourceRange();
  3610. if (EllipsisLoc.isValid()) {
  3611. // This is a pack expansion.
  3612. if (!BaseType->containsUnexpandedParameterPack()) {
  3613. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  3614. << SourceRange(BaseLoc, InitRange.getEnd());
  3615. EllipsisLoc = SourceLocation();
  3616. }
  3617. } else {
  3618. // Check for any unexpanded parameter packs.
  3619. if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
  3620. return true;
  3621. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3622. return true;
  3623. }
  3624. // Check for direct and virtual base classes.
  3625. const CXXBaseSpecifier *DirectBaseSpec = nullptr;
  3626. const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
  3627. if (!Dependent) {
  3628. if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
  3629. BaseType))
  3630. return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
  3631. FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
  3632. VirtualBaseSpec);
  3633. // C++ [base.class.init]p2:
  3634. // Unless the mem-initializer-id names a nonstatic data member of the
  3635. // constructor's class or a direct or virtual base of that class, the
  3636. // mem-initializer is ill-formed.
  3637. if (!DirectBaseSpec && !VirtualBaseSpec) {
  3638. // If the class has any dependent bases, then it's possible that
  3639. // one of those types will resolve to the same type as
  3640. // BaseType. Therefore, just treat this as a dependent base
  3641. // class initialization. FIXME: Should we try to check the
  3642. // initialization anyway? It seems odd.
  3643. if (ClassDecl->hasAnyDependentBases())
  3644. Dependent = true;
  3645. else
  3646. return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
  3647. << BaseType << Context.getTypeDeclType(ClassDecl)
  3648. << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3649. }
  3650. }
  3651. if (Dependent) {
  3652. DiscardCleanupsInEvaluationContext();
  3653. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3654. /*IsVirtual=*/false,
  3655. InitRange.getBegin(), Init,
  3656. InitRange.getEnd(), EllipsisLoc);
  3657. }
  3658. // C++ [base.class.init]p2:
  3659. // If a mem-initializer-id is ambiguous because it designates both
  3660. // a direct non-virtual base class and an inherited virtual base
  3661. // class, the mem-initializer is ill-formed.
  3662. if (DirectBaseSpec && VirtualBaseSpec)
  3663. return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
  3664. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3665. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
  3666. if (!BaseSpec)
  3667. BaseSpec = VirtualBaseSpec;
  3668. // Initialize the base.
  3669. bool InitList = true;
  3670. MultiExprArg Args = Init;
  3671. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3672. InitList = false;
  3673. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3674. }
  3675. InitializedEntity BaseEntity =
  3676. InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
  3677. InitializationKind Kind =
  3678. InitList ? InitializationKind::CreateDirectList(BaseLoc)
  3679. : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
  3680. InitRange.getEnd());
  3681. InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
  3682. ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
  3683. if (BaseInit.isInvalid())
  3684. return true;
  3685. // C++11 [class.base.init]p7:
  3686. // The initialization of each base and member constitutes a
  3687. // full-expression.
  3688. BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
  3689. if (BaseInit.isInvalid())
  3690. return true;
  3691. // If we are in a dependent context, template instantiation will
  3692. // perform this type-checking again. Just save the arguments that we
  3693. // received in a ParenListExpr.
  3694. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3695. // of the information that we have about the base
  3696. // initializer. However, deconstructing the ASTs is a dicey process,
  3697. // and this approach is far more likely to get the corner cases right.
  3698. if (CurContext->isDependentContext())
  3699. BaseInit = Init;
  3700. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3701. BaseSpec->isVirtual(),
  3702. InitRange.getBegin(),
  3703. BaseInit.getAs<Expr>(),
  3704. InitRange.getEnd(), EllipsisLoc);
  3705. }
  3706. // Create a static_cast\<T&&>(expr).
  3707. static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
  3708. if (T.isNull()) T = E->getType();
  3709. QualType TargetType = SemaRef.BuildReferenceType(
  3710. T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
  3711. SourceLocation ExprLoc = E->getBeginLoc();
  3712. TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
  3713. TargetType, ExprLoc);
  3714. return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  3715. SourceRange(ExprLoc, ExprLoc),
  3716. E->getSourceRange()).get();
  3717. }
  3718. /// ImplicitInitializerKind - How an implicit base or member initializer should
  3719. /// initialize its base or member.
  3720. enum ImplicitInitializerKind {
  3721. IIK_Default,
  3722. IIK_Copy,
  3723. IIK_Move,
  3724. IIK_Inherit
  3725. };
  3726. static bool
  3727. BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3728. ImplicitInitializerKind ImplicitInitKind,
  3729. CXXBaseSpecifier *BaseSpec,
  3730. bool IsInheritedVirtualBase,
  3731. CXXCtorInitializer *&CXXBaseInit) {
  3732. InitializedEntity InitEntity
  3733. = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
  3734. IsInheritedVirtualBase);
  3735. ExprResult BaseInit;
  3736. switch (ImplicitInitKind) {
  3737. case IIK_Inherit:
  3738. case IIK_Default: {
  3739. InitializationKind InitKind
  3740. = InitializationKind::CreateDefault(Constructor->getLocation());
  3741. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  3742. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  3743. break;
  3744. }
  3745. case IIK_Move:
  3746. case IIK_Copy: {
  3747. bool Moving = ImplicitInitKind == IIK_Move;
  3748. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3749. QualType ParamType = Param->getType().getNonReferenceType();
  3750. Expr *CopyCtorArg =
  3751. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3752. SourceLocation(), Param, false,
  3753. Constructor->getLocation(), ParamType,
  3754. VK_LValue, nullptr);
  3755. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
  3756. // Cast to the base class to avoid ambiguities.
  3757. QualType ArgTy =
  3758. SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
  3759. ParamType.getQualifiers());
  3760. if (Moving) {
  3761. CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
  3762. }
  3763. CXXCastPath BasePath;
  3764. BasePath.push_back(BaseSpec);
  3765. CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
  3766. CK_UncheckedDerivedToBase,
  3767. Moving ? VK_XValue : VK_LValue,
  3768. &BasePath).get();
  3769. InitializationKind InitKind
  3770. = InitializationKind::CreateDirect(Constructor->getLocation(),
  3771. SourceLocation(), SourceLocation());
  3772. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3773. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3774. break;
  3775. }
  3776. }
  3777. BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
  3778. if (BaseInit.isInvalid())
  3779. return true;
  3780. CXXBaseInit =
  3781. new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3782. SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
  3783. SourceLocation()),
  3784. BaseSpec->isVirtual(),
  3785. SourceLocation(),
  3786. BaseInit.getAs<Expr>(),
  3787. SourceLocation(),
  3788. SourceLocation());
  3789. return false;
  3790. }
  3791. static bool RefersToRValueRef(Expr *MemRef) {
  3792. ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
  3793. return Referenced->getType()->isRValueReferenceType();
  3794. }
  3795. static bool
  3796. BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3797. ImplicitInitializerKind ImplicitInitKind,
  3798. FieldDecl *Field, IndirectFieldDecl *Indirect,
  3799. CXXCtorInitializer *&CXXMemberInit) {
  3800. if (Field->isInvalidDecl())
  3801. return true;
  3802. SourceLocation Loc = Constructor->getLocation();
  3803. if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
  3804. bool Moving = ImplicitInitKind == IIK_Move;
  3805. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3806. QualType ParamType = Param->getType().getNonReferenceType();
  3807. // Suppress copying zero-width bitfields.
  3808. if (Field->isZeroLengthBitField(SemaRef.Context))
  3809. return false;
  3810. Expr *MemberExprBase =
  3811. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3812. SourceLocation(), Param, false,
  3813. Loc, ParamType, VK_LValue, nullptr);
  3814. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
  3815. if (Moving) {
  3816. MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
  3817. }
  3818. // Build a reference to this field within the parameter.
  3819. CXXScopeSpec SS;
  3820. LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
  3821. Sema::LookupMemberName);
  3822. MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
  3823. : cast<ValueDecl>(Field), AS_public);
  3824. MemberLookup.resolveKind();
  3825. ExprResult CtorArg
  3826. = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
  3827. ParamType, Loc,
  3828. /*IsArrow=*/false,
  3829. SS,
  3830. /*TemplateKWLoc=*/SourceLocation(),
  3831. /*FirstQualifierInScope=*/nullptr,
  3832. MemberLookup,
  3833. /*TemplateArgs=*/nullptr,
  3834. /*S*/nullptr);
  3835. if (CtorArg.isInvalid())
  3836. return true;
  3837. // C++11 [class.copy]p15:
  3838. // - if a member m has rvalue reference type T&&, it is direct-initialized
  3839. // with static_cast<T&&>(x.m);
  3840. if (RefersToRValueRef(CtorArg.get())) {
  3841. CtorArg = CastForMoving(SemaRef, CtorArg.get());
  3842. }
  3843. InitializedEntity Entity =
  3844. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  3845. /*Implicit*/ true)
  3846. : InitializedEntity::InitializeMember(Field, nullptr,
  3847. /*Implicit*/ true);
  3848. // Direct-initialize to use the copy constructor.
  3849. InitializationKind InitKind =
  3850. InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
  3851. Expr *CtorArgE = CtorArg.getAs<Expr>();
  3852. InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
  3853. ExprResult MemberInit =
  3854. InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
  3855. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  3856. if (MemberInit.isInvalid())
  3857. return true;
  3858. if (Indirect)
  3859. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  3860. SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  3861. else
  3862. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  3863. SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  3864. return false;
  3865. }
  3866. assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
  3867. "Unhandled implicit init kind!");
  3868. QualType FieldBaseElementType =
  3869. SemaRef.Context.getBaseElementType(Field->getType());
  3870. if (FieldBaseElementType->isRecordType()) {
  3871. InitializedEntity InitEntity =
  3872. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  3873. /*Implicit*/ true)
  3874. : InitializedEntity::InitializeMember(Field, nullptr,
  3875. /*Implicit*/ true);
  3876. InitializationKind InitKind =
  3877. InitializationKind::CreateDefault(Loc);
  3878. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  3879. ExprResult MemberInit =
  3880. InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  3881. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  3882. if (MemberInit.isInvalid())
  3883. return true;
  3884. if (Indirect)
  3885. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3886. Indirect, Loc,
  3887. Loc,
  3888. MemberInit.get(),
  3889. Loc);
  3890. else
  3891. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3892. Field, Loc, Loc,
  3893. MemberInit.get(),
  3894. Loc);
  3895. return false;
  3896. }
  3897. if (!Field->getParent()->isUnion()) {
  3898. if (FieldBaseElementType->isReferenceType()) {
  3899. SemaRef.Diag(Constructor->getLocation(),
  3900. diag::err_uninitialized_member_in_ctor)
  3901. << (int)Constructor->isImplicit()
  3902. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  3903. << 0 << Field->getDeclName();
  3904. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  3905. return true;
  3906. }
  3907. if (FieldBaseElementType.isConstQualified()) {
  3908. SemaRef.Diag(Constructor->getLocation(),
  3909. diag::err_uninitialized_member_in_ctor)
  3910. << (int)Constructor->isImplicit()
  3911. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  3912. << 1 << Field->getDeclName();
  3913. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  3914. return true;
  3915. }
  3916. }
  3917. if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
  3918. // ARC and Weak:
  3919. // Default-initialize Objective-C pointers to NULL.
  3920. CXXMemberInit
  3921. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
  3922. Loc, Loc,
  3923. new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
  3924. Loc);
  3925. return false;
  3926. }
  3927. // Nothing to initialize.
  3928. CXXMemberInit = nullptr;
  3929. return false;
  3930. }
  3931. namespace {
  3932. struct BaseAndFieldInfo {
  3933. Sema &S;
  3934. CXXConstructorDecl *Ctor;
  3935. bool AnyErrorsInInits;
  3936. ImplicitInitializerKind IIK;
  3937. llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
  3938. SmallVector<CXXCtorInitializer*, 8> AllToInit;
  3939. llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
  3940. BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
  3941. : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
  3942. bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
  3943. if (Ctor->getInheritedConstructor())
  3944. IIK = IIK_Inherit;
  3945. else if (Generated && Ctor->isCopyConstructor())
  3946. IIK = IIK_Copy;
  3947. else if (Generated && Ctor->isMoveConstructor())
  3948. IIK = IIK_Move;
  3949. else
  3950. IIK = IIK_Default;
  3951. }
  3952. bool isImplicitCopyOrMove() const {
  3953. switch (IIK) {
  3954. case IIK_Copy:
  3955. case IIK_Move:
  3956. return true;
  3957. case IIK_Default:
  3958. case IIK_Inherit:
  3959. return false;
  3960. }
  3961. llvm_unreachable("Invalid ImplicitInitializerKind!");
  3962. }
  3963. bool addFieldInitializer(CXXCtorInitializer *Init) {
  3964. AllToInit.push_back(Init);
  3965. // Check whether this initializer makes the field "used".
  3966. if (Init->getInit()->HasSideEffects(S.Context))
  3967. S.UnusedPrivateFields.remove(Init->getAnyMember());
  3968. return false;
  3969. }
  3970. bool isInactiveUnionMember(FieldDecl *Field) {
  3971. RecordDecl *Record = Field->getParent();
  3972. if (!Record->isUnion())
  3973. return false;
  3974. if (FieldDecl *Active =
  3975. ActiveUnionMember.lookup(Record->getCanonicalDecl()))
  3976. return Active != Field->getCanonicalDecl();
  3977. // In an implicit copy or move constructor, ignore any in-class initializer.
  3978. if (isImplicitCopyOrMove())
  3979. return true;
  3980. // If there's no explicit initialization, the field is active only if it
  3981. // has an in-class initializer...
  3982. if (Field->hasInClassInitializer())
  3983. return false;
  3984. // ... or it's an anonymous struct or union whose class has an in-class
  3985. // initializer.
  3986. if (!Field->isAnonymousStructOrUnion())
  3987. return true;
  3988. CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
  3989. return !FieldRD->hasInClassInitializer();
  3990. }
  3991. /// Determine whether the given field is, or is within, a union member
  3992. /// that is inactive (because there was an initializer given for a different
  3993. /// member of the union, or because the union was not initialized at all).
  3994. bool isWithinInactiveUnionMember(FieldDecl *Field,
  3995. IndirectFieldDecl *Indirect) {
  3996. if (!Indirect)
  3997. return isInactiveUnionMember(Field);
  3998. for (auto *C : Indirect->chain()) {
  3999. FieldDecl *Field = dyn_cast<FieldDecl>(C);
  4000. if (Field && isInactiveUnionMember(Field))
  4001. return true;
  4002. }
  4003. return false;
  4004. }
  4005. };
  4006. }
  4007. /// Determine whether the given type is an incomplete or zero-lenfgth
  4008. /// array type.
  4009. static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
  4010. if (T->isIncompleteArrayType())
  4011. return true;
  4012. while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
  4013. if (!ArrayT->getSize())
  4014. return true;
  4015. T = ArrayT->getElementType();
  4016. }
  4017. return false;
  4018. }
  4019. static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
  4020. FieldDecl *Field,
  4021. IndirectFieldDecl *Indirect = nullptr) {
  4022. if (Field->isInvalidDecl())
  4023. return false;
  4024. // Overwhelmingly common case: we have a direct initializer for this field.
  4025. if (CXXCtorInitializer *Init =
  4026. Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
  4027. return Info.addFieldInitializer(Init);
  4028. // C++11 [class.base.init]p8:
  4029. // if the entity is a non-static data member that has a
  4030. // brace-or-equal-initializer and either
  4031. // -- the constructor's class is a union and no other variant member of that
  4032. // union is designated by a mem-initializer-id or
  4033. // -- the constructor's class is not a union, and, if the entity is a member
  4034. // of an anonymous union, no other member of that union is designated by
  4035. // a mem-initializer-id,
  4036. // the entity is initialized as specified in [dcl.init].
  4037. //
  4038. // We also apply the same rules to handle anonymous structs within anonymous
  4039. // unions.
  4040. if (Info.isWithinInactiveUnionMember(Field, Indirect))
  4041. return false;
  4042. if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
  4043. ExprResult DIE =
  4044. SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
  4045. if (DIE.isInvalid())
  4046. return true;
  4047. auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
  4048. SemaRef.checkInitializerLifetime(Entity, DIE.get());
  4049. CXXCtorInitializer *Init;
  4050. if (Indirect)
  4051. Init = new (SemaRef.Context)
  4052. CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
  4053. SourceLocation(), DIE.get(), SourceLocation());
  4054. else
  4055. Init = new (SemaRef.Context)
  4056. CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
  4057. SourceLocation(), DIE.get(), SourceLocation());
  4058. return Info.addFieldInitializer(Init);
  4059. }
  4060. // Don't initialize incomplete or zero-length arrays.
  4061. if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
  4062. return false;
  4063. // Don't try to build an implicit initializer if there were semantic
  4064. // errors in any of the initializers (and therefore we might be
  4065. // missing some that the user actually wrote).
  4066. if (Info.AnyErrorsInInits)
  4067. return false;
  4068. CXXCtorInitializer *Init = nullptr;
  4069. if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
  4070. Indirect, Init))
  4071. return true;
  4072. if (!Init)
  4073. return false;
  4074. return Info.addFieldInitializer(Init);
  4075. }
  4076. bool
  4077. Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
  4078. CXXCtorInitializer *Initializer) {
  4079. assert(Initializer->isDelegatingInitializer());
  4080. Constructor->setNumCtorInitializers(1);
  4081. CXXCtorInitializer **initializer =
  4082. new (Context) CXXCtorInitializer*[1];
  4083. memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
  4084. Constructor->setCtorInitializers(initializer);
  4085. if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
  4086. MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
  4087. DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
  4088. }
  4089. DelegatingCtorDecls.push_back(Constructor);
  4090. DiagnoseUninitializedFields(*this, Constructor);
  4091. return false;
  4092. }
  4093. bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
  4094. ArrayRef<CXXCtorInitializer *> Initializers) {
  4095. if (Constructor->isDependentContext()) {
  4096. // Just store the initializers as written, they will be checked during
  4097. // instantiation.
  4098. if (!Initializers.empty()) {
  4099. Constructor->setNumCtorInitializers(Initializers.size());
  4100. CXXCtorInitializer **baseOrMemberInitializers =
  4101. new (Context) CXXCtorInitializer*[Initializers.size()];
  4102. memcpy(baseOrMemberInitializers, Initializers.data(),
  4103. Initializers.size() * sizeof(CXXCtorInitializer*));
  4104. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4105. }
  4106. // Let template instantiation know whether we had errors.
  4107. if (AnyErrors)
  4108. Constructor->setInvalidDecl();
  4109. return false;
  4110. }
  4111. BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
  4112. // We need to build the initializer AST according to order of construction
  4113. // and not what user specified in the Initializers list.
  4114. CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
  4115. if (!ClassDecl)
  4116. return true;
  4117. bool HadError = false;
  4118. for (unsigned i = 0; i < Initializers.size(); i++) {
  4119. CXXCtorInitializer *Member = Initializers[i];
  4120. if (Member->isBaseInitializer())
  4121. Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
  4122. else {
  4123. Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
  4124. if (IndirectFieldDecl *F = Member->getIndirectMember()) {
  4125. for (auto *C : F->chain()) {
  4126. FieldDecl *FD = dyn_cast<FieldDecl>(C);
  4127. if (FD && FD->getParent()->isUnion())
  4128. Info.ActiveUnionMember.insert(std::make_pair(
  4129. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4130. }
  4131. } else if (FieldDecl *FD = Member->getMember()) {
  4132. if (FD->getParent()->isUnion())
  4133. Info.ActiveUnionMember.insert(std::make_pair(
  4134. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4135. }
  4136. }
  4137. }
  4138. // Keep track of the direct virtual bases.
  4139. llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
  4140. for (auto &I : ClassDecl->bases()) {
  4141. if (I.isVirtual())
  4142. DirectVBases.insert(&I);
  4143. }
  4144. // Push virtual bases before others.
  4145. for (auto &VBase : ClassDecl->vbases()) {
  4146. if (CXXCtorInitializer *Value
  4147. = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
  4148. // [class.base.init]p7, per DR257:
  4149. // A mem-initializer where the mem-initializer-id names a virtual base
  4150. // class is ignored during execution of a constructor of any class that
  4151. // is not the most derived class.
  4152. if (ClassDecl->isAbstract()) {
  4153. // FIXME: Provide a fixit to remove the base specifier. This requires
  4154. // tracking the location of the associated comma for a base specifier.
  4155. Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
  4156. << VBase.getType() << ClassDecl;
  4157. DiagnoseAbstractType(ClassDecl);
  4158. }
  4159. Info.AllToInit.push_back(Value);
  4160. } else if (!AnyErrors && !ClassDecl->isAbstract()) {
  4161. // [class.base.init]p8, per DR257:
  4162. // If a given [...] base class is not named by a mem-initializer-id
  4163. // [...] and the entity is not a virtual base class of an abstract
  4164. // class, then [...] the entity is default-initialized.
  4165. bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
  4166. CXXCtorInitializer *CXXBaseInit;
  4167. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4168. &VBase, IsInheritedVirtualBase,
  4169. CXXBaseInit)) {
  4170. HadError = true;
  4171. continue;
  4172. }
  4173. Info.AllToInit.push_back(CXXBaseInit);
  4174. }
  4175. }
  4176. // Non-virtual bases.
  4177. for (auto &Base : ClassDecl->bases()) {
  4178. // Virtuals are in the virtual base list and already constructed.
  4179. if (Base.isVirtual())
  4180. continue;
  4181. if (CXXCtorInitializer *Value
  4182. = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
  4183. Info.AllToInit.push_back(Value);
  4184. } else if (!AnyErrors) {
  4185. CXXCtorInitializer *CXXBaseInit;
  4186. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4187. &Base, /*IsInheritedVirtualBase=*/false,
  4188. CXXBaseInit)) {
  4189. HadError = true;
  4190. continue;
  4191. }
  4192. Info.AllToInit.push_back(CXXBaseInit);
  4193. }
  4194. }
  4195. // Fields.
  4196. for (auto *Mem : ClassDecl->decls()) {
  4197. if (auto *F = dyn_cast<FieldDecl>(Mem)) {
  4198. // C++ [class.bit]p2:
  4199. // A declaration for a bit-field that omits the identifier declares an
  4200. // unnamed bit-field. Unnamed bit-fields are not members and cannot be
  4201. // initialized.
  4202. if (F->isUnnamedBitfield())
  4203. continue;
  4204. // If we're not generating the implicit copy/move constructor, then we'll
  4205. // handle anonymous struct/union fields based on their individual
  4206. // indirect fields.
  4207. if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
  4208. continue;
  4209. if (CollectFieldInitializer(*this, Info, F))
  4210. HadError = true;
  4211. continue;
  4212. }
  4213. // Beyond this point, we only consider default initialization.
  4214. if (Info.isImplicitCopyOrMove())
  4215. continue;
  4216. if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
  4217. if (F->getType()->isIncompleteArrayType()) {
  4218. assert(ClassDecl->hasFlexibleArrayMember() &&
  4219. "Incomplete array type is not valid");
  4220. continue;
  4221. }
  4222. // Initialize each field of an anonymous struct individually.
  4223. if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
  4224. HadError = true;
  4225. continue;
  4226. }
  4227. }
  4228. unsigned NumInitializers = Info.AllToInit.size();
  4229. if (NumInitializers > 0) {
  4230. Constructor->setNumCtorInitializers(NumInitializers);
  4231. CXXCtorInitializer **baseOrMemberInitializers =
  4232. new (Context) CXXCtorInitializer*[NumInitializers];
  4233. memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
  4234. NumInitializers * sizeof(CXXCtorInitializer*));
  4235. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4236. // Constructors implicitly reference the base and member
  4237. // destructors.
  4238. MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
  4239. Constructor->getParent());
  4240. }
  4241. return HadError;
  4242. }
  4243. static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
  4244. if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
  4245. const RecordDecl *RD = RT->getDecl();
  4246. if (RD->isAnonymousStructOrUnion()) {
  4247. for (auto *Field : RD->fields())
  4248. PopulateKeysForFields(Field, IdealInits);
  4249. return;
  4250. }
  4251. }
  4252. IdealInits.push_back(Field->getCanonicalDecl());
  4253. }
  4254. static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
  4255. return Context.getCanonicalType(BaseType).getTypePtr();
  4256. }
  4257. static const void *GetKeyForMember(ASTContext &Context,
  4258. CXXCtorInitializer *Member) {
  4259. if (!Member->isAnyMemberInitializer())
  4260. return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
  4261. return Member->getAnyMember()->getCanonicalDecl();
  4262. }
  4263. static void DiagnoseBaseOrMemInitializerOrder(
  4264. Sema &SemaRef, const CXXConstructorDecl *Constructor,
  4265. ArrayRef<CXXCtorInitializer *> Inits) {
  4266. if (Constructor->getDeclContext()->isDependentContext())
  4267. return;
  4268. // Don't check initializers order unless the warning is enabled at the
  4269. // location of at least one initializer.
  4270. bool ShouldCheckOrder = false;
  4271. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4272. CXXCtorInitializer *Init = Inits[InitIndex];
  4273. if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
  4274. Init->getSourceLocation())) {
  4275. ShouldCheckOrder = true;
  4276. break;
  4277. }
  4278. }
  4279. if (!ShouldCheckOrder)
  4280. return;
  4281. // Build the list of bases and members in the order that they'll
  4282. // actually be initialized. The explicit initializers should be in
  4283. // this same order but may be missing things.
  4284. SmallVector<const void*, 32> IdealInitKeys;
  4285. const CXXRecordDecl *ClassDecl = Constructor->getParent();
  4286. // 1. Virtual bases.
  4287. for (const auto &VBase : ClassDecl->vbases())
  4288. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
  4289. // 2. Non-virtual bases.
  4290. for (const auto &Base : ClassDecl->bases()) {
  4291. if (Base.isVirtual())
  4292. continue;
  4293. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
  4294. }
  4295. // 3. Direct fields.
  4296. for (auto *Field : ClassDecl->fields()) {
  4297. if (Field->isUnnamedBitfield())
  4298. continue;
  4299. PopulateKeysForFields(Field, IdealInitKeys);
  4300. }
  4301. unsigned NumIdealInits = IdealInitKeys.size();
  4302. unsigned IdealIndex = 0;
  4303. CXXCtorInitializer *PrevInit = nullptr;
  4304. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4305. CXXCtorInitializer *Init = Inits[InitIndex];
  4306. const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
  4307. // Scan forward to try to find this initializer in the idealized
  4308. // initializers list.
  4309. for (; IdealIndex != NumIdealInits; ++IdealIndex)
  4310. if (InitKey == IdealInitKeys[IdealIndex])
  4311. break;
  4312. // If we didn't find this initializer, it must be because we
  4313. // scanned past it on a previous iteration. That can only
  4314. // happen if we're out of order; emit a warning.
  4315. if (IdealIndex == NumIdealInits && PrevInit) {
  4316. Sema::SemaDiagnosticBuilder D =
  4317. SemaRef.Diag(PrevInit->getSourceLocation(),
  4318. diag::warn_initializer_out_of_order);
  4319. if (PrevInit->isAnyMemberInitializer())
  4320. D << 0 << PrevInit->getAnyMember()->getDeclName();
  4321. else
  4322. D << 1 << PrevInit->getTypeSourceInfo()->getType();
  4323. if (Init->isAnyMemberInitializer())
  4324. D << 0 << Init->getAnyMember()->getDeclName();
  4325. else
  4326. D << 1 << Init->getTypeSourceInfo()->getType();
  4327. // Move back to the initializer's location in the ideal list.
  4328. for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
  4329. if (InitKey == IdealInitKeys[IdealIndex])
  4330. break;
  4331. assert(IdealIndex < NumIdealInits &&
  4332. "initializer not found in initializer list");
  4333. }
  4334. PrevInit = Init;
  4335. }
  4336. }
  4337. namespace {
  4338. bool CheckRedundantInit(Sema &S,
  4339. CXXCtorInitializer *Init,
  4340. CXXCtorInitializer *&PrevInit) {
  4341. if (!PrevInit) {
  4342. PrevInit = Init;
  4343. return false;
  4344. }
  4345. if (FieldDecl *Field = Init->getAnyMember())
  4346. S.Diag(Init->getSourceLocation(),
  4347. diag::err_multiple_mem_initialization)
  4348. << Field->getDeclName()
  4349. << Init->getSourceRange();
  4350. else {
  4351. const Type *BaseClass = Init->getBaseClass();
  4352. assert(BaseClass && "neither field nor base");
  4353. S.Diag(Init->getSourceLocation(),
  4354. diag::err_multiple_base_initialization)
  4355. << QualType(BaseClass, 0)
  4356. << Init->getSourceRange();
  4357. }
  4358. S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
  4359. << 0 << PrevInit->getSourceRange();
  4360. return true;
  4361. }
  4362. typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
  4363. typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
  4364. bool CheckRedundantUnionInit(Sema &S,
  4365. CXXCtorInitializer *Init,
  4366. RedundantUnionMap &Unions) {
  4367. FieldDecl *Field = Init->getAnyMember();
  4368. RecordDecl *Parent = Field->getParent();
  4369. NamedDecl *Child = Field;
  4370. while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
  4371. if (Parent->isUnion()) {
  4372. UnionEntry &En = Unions[Parent];
  4373. if (En.first && En.first != Child) {
  4374. S.Diag(Init->getSourceLocation(),
  4375. diag::err_multiple_mem_union_initialization)
  4376. << Field->getDeclName()
  4377. << Init->getSourceRange();
  4378. S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
  4379. << 0 << En.second->getSourceRange();
  4380. return true;
  4381. }
  4382. if (!En.first) {
  4383. En.first = Child;
  4384. En.second = Init;
  4385. }
  4386. if (!Parent->isAnonymousStructOrUnion())
  4387. return false;
  4388. }
  4389. Child = Parent;
  4390. Parent = cast<RecordDecl>(Parent->getDeclContext());
  4391. }
  4392. return false;
  4393. }
  4394. }
  4395. /// ActOnMemInitializers - Handle the member initializers for a constructor.
  4396. void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
  4397. SourceLocation ColonLoc,
  4398. ArrayRef<CXXCtorInitializer*> MemInits,
  4399. bool AnyErrors) {
  4400. if (!ConstructorDecl)
  4401. return;
  4402. AdjustDeclIfTemplate(ConstructorDecl);
  4403. CXXConstructorDecl *Constructor
  4404. = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
  4405. if (!Constructor) {
  4406. Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
  4407. return;
  4408. }
  4409. // Mapping for the duplicate initializers check.
  4410. // For member initializers, this is keyed with a FieldDecl*.
  4411. // For base initializers, this is keyed with a Type*.
  4412. llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
  4413. // Mapping for the inconsistent anonymous-union initializers check.
  4414. RedundantUnionMap MemberUnions;
  4415. bool HadError = false;
  4416. for (unsigned i = 0; i < MemInits.size(); i++) {
  4417. CXXCtorInitializer *Init = MemInits[i];
  4418. // Set the source order index.
  4419. Init->setSourceOrder(i);
  4420. if (Init->isAnyMemberInitializer()) {
  4421. const void *Key = GetKeyForMember(Context, Init);
  4422. if (CheckRedundantInit(*this, Init, Members[Key]) ||
  4423. CheckRedundantUnionInit(*this, Init, MemberUnions))
  4424. HadError = true;
  4425. } else if (Init->isBaseInitializer()) {
  4426. const void *Key = GetKeyForMember(Context, Init);
  4427. if (CheckRedundantInit(*this, Init, Members[Key]))
  4428. HadError = true;
  4429. } else {
  4430. assert(Init->isDelegatingInitializer());
  4431. // This must be the only initializer
  4432. if (MemInits.size() != 1) {
  4433. Diag(Init->getSourceLocation(),
  4434. diag::err_delegating_initializer_alone)
  4435. << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
  4436. // We will treat this as being the only initializer.
  4437. }
  4438. SetDelegatingInitializer(Constructor, MemInits[i]);
  4439. // Return immediately as the initializer is set.
  4440. return;
  4441. }
  4442. }
  4443. if (HadError)
  4444. return;
  4445. DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
  4446. SetCtorInitializers(Constructor, AnyErrors, MemInits);
  4447. DiagnoseUninitializedFields(*this, Constructor);
  4448. }
  4449. void
  4450. Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
  4451. CXXRecordDecl *ClassDecl) {
  4452. // Ignore dependent contexts. Also ignore unions, since their members never
  4453. // have destructors implicitly called.
  4454. if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
  4455. return;
  4456. // FIXME: all the access-control diagnostics are positioned on the
  4457. // field/base declaration. That's probably good; that said, the
  4458. // user might reasonably want to know why the destructor is being
  4459. // emitted, and we currently don't say.
  4460. // Non-static data members.
  4461. for (auto *Field : ClassDecl->fields()) {
  4462. if (Field->isInvalidDecl())
  4463. continue;
  4464. // Don't destroy incomplete or zero-length arrays.
  4465. if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
  4466. continue;
  4467. QualType FieldType = Context.getBaseElementType(Field->getType());
  4468. const RecordType* RT = FieldType->getAs<RecordType>();
  4469. if (!RT)
  4470. continue;
  4471. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4472. if (FieldClassDecl->isInvalidDecl())
  4473. continue;
  4474. if (FieldClassDecl->hasIrrelevantDestructor())
  4475. continue;
  4476. // The destructor for an implicit anonymous union member is never invoked.
  4477. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  4478. continue;
  4479. CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
  4480. assert(Dtor && "No dtor found for FieldClassDecl!");
  4481. CheckDestructorAccess(Field->getLocation(), Dtor,
  4482. PDiag(diag::err_access_dtor_field)
  4483. << Field->getDeclName()
  4484. << FieldType);
  4485. MarkFunctionReferenced(Location, Dtor);
  4486. DiagnoseUseOfDecl(Dtor, Location);
  4487. }
  4488. // We only potentially invoke the destructors of potentially constructed
  4489. // subobjects.
  4490. bool VisitVirtualBases = !ClassDecl->isAbstract();
  4491. llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
  4492. // Bases.
  4493. for (const auto &Base : ClassDecl->bases()) {
  4494. // Bases are always records in a well-formed non-dependent class.
  4495. const RecordType *RT = Base.getType()->getAs<RecordType>();
  4496. // Remember direct virtual bases.
  4497. if (Base.isVirtual()) {
  4498. if (!VisitVirtualBases)
  4499. continue;
  4500. DirectVirtualBases.insert(RT);
  4501. }
  4502. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4503. // If our base class is invalid, we probably can't get its dtor anyway.
  4504. if (BaseClassDecl->isInvalidDecl())
  4505. continue;
  4506. if (BaseClassDecl->hasIrrelevantDestructor())
  4507. continue;
  4508. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4509. assert(Dtor && "No dtor found for BaseClassDecl!");
  4510. // FIXME: caret should be on the start of the class name
  4511. CheckDestructorAccess(Base.getBeginLoc(), Dtor,
  4512. PDiag(diag::err_access_dtor_base)
  4513. << Base.getType() << Base.getSourceRange(),
  4514. Context.getTypeDeclType(ClassDecl));
  4515. MarkFunctionReferenced(Location, Dtor);
  4516. DiagnoseUseOfDecl(Dtor, Location);
  4517. }
  4518. if (!VisitVirtualBases)
  4519. return;
  4520. // Virtual bases.
  4521. for (const auto &VBase : ClassDecl->vbases()) {
  4522. // Bases are always records in a well-formed non-dependent class.
  4523. const RecordType *RT = VBase.getType()->castAs<RecordType>();
  4524. // Ignore direct virtual bases.
  4525. if (DirectVirtualBases.count(RT))
  4526. continue;
  4527. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4528. // If our base class is invalid, we probably can't get its dtor anyway.
  4529. if (BaseClassDecl->isInvalidDecl())
  4530. continue;
  4531. if (BaseClassDecl->hasIrrelevantDestructor())
  4532. continue;
  4533. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4534. assert(Dtor && "No dtor found for BaseClassDecl!");
  4535. if (CheckDestructorAccess(
  4536. ClassDecl->getLocation(), Dtor,
  4537. PDiag(diag::err_access_dtor_vbase)
  4538. << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
  4539. Context.getTypeDeclType(ClassDecl)) ==
  4540. AR_accessible) {
  4541. CheckDerivedToBaseConversion(
  4542. Context.getTypeDeclType(ClassDecl), VBase.getType(),
  4543. diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
  4544. SourceRange(), DeclarationName(), nullptr);
  4545. }
  4546. MarkFunctionReferenced(Location, Dtor);
  4547. DiagnoseUseOfDecl(Dtor, Location);
  4548. }
  4549. }
  4550. void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
  4551. if (!CDtorDecl)
  4552. return;
  4553. if (CXXConstructorDecl *Constructor
  4554. = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
  4555. SetCtorInitializers(Constructor, /*AnyErrors=*/false);
  4556. DiagnoseUninitializedFields(*this, Constructor);
  4557. }
  4558. }
  4559. bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
  4560. if (!getLangOpts().CPlusPlus)
  4561. return false;
  4562. const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
  4563. if (!RD)
  4564. return false;
  4565. // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
  4566. // class template specialization here, but doing so breaks a lot of code.
  4567. // We can't answer whether something is abstract until it has a
  4568. // definition. If it's currently being defined, we'll walk back
  4569. // over all the declarations when we have a full definition.
  4570. const CXXRecordDecl *Def = RD->getDefinition();
  4571. if (!Def || Def->isBeingDefined())
  4572. return false;
  4573. return RD->isAbstract();
  4574. }
  4575. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  4576. TypeDiagnoser &Diagnoser) {
  4577. if (!isAbstractType(Loc, T))
  4578. return false;
  4579. T = Context.getBaseElementType(T);
  4580. Diagnoser.diagnose(*this, Loc, T);
  4581. DiagnoseAbstractType(T->getAsCXXRecordDecl());
  4582. return true;
  4583. }
  4584. void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
  4585. // Check if we've already emitted the list of pure virtual functions
  4586. // for this class.
  4587. if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
  4588. return;
  4589. // If the diagnostic is suppressed, don't emit the notes. We're only
  4590. // going to emit them once, so try to attach them to a diagnostic we're
  4591. // actually going to show.
  4592. if (Diags.isLastDiagnosticIgnored())
  4593. return;
  4594. CXXFinalOverriderMap FinalOverriders;
  4595. RD->getFinalOverriders(FinalOverriders);
  4596. // Keep a set of seen pure methods so we won't diagnose the same method
  4597. // more than once.
  4598. llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
  4599. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  4600. MEnd = FinalOverriders.end();
  4601. M != MEnd;
  4602. ++M) {
  4603. for (OverridingMethods::iterator SO = M->second.begin(),
  4604. SOEnd = M->second.end();
  4605. SO != SOEnd; ++SO) {
  4606. // C++ [class.abstract]p4:
  4607. // A class is abstract if it contains or inherits at least one
  4608. // pure virtual function for which the final overrider is pure
  4609. // virtual.
  4610. //
  4611. if (SO->second.size() != 1)
  4612. continue;
  4613. if (!SO->second.front().Method->isPure())
  4614. continue;
  4615. if (!SeenPureMethods.insert(SO->second.front().Method).second)
  4616. continue;
  4617. Diag(SO->second.front().Method->getLocation(),
  4618. diag::note_pure_virtual_function)
  4619. << SO->second.front().Method->getDeclName() << RD->getDeclName();
  4620. }
  4621. }
  4622. if (!PureVirtualClassDiagSet)
  4623. PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
  4624. PureVirtualClassDiagSet->insert(RD);
  4625. }
  4626. namespace {
  4627. struct AbstractUsageInfo {
  4628. Sema &S;
  4629. CXXRecordDecl *Record;
  4630. CanQualType AbstractType;
  4631. bool Invalid;
  4632. AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
  4633. : S(S), Record(Record),
  4634. AbstractType(S.Context.getCanonicalType(
  4635. S.Context.getTypeDeclType(Record))),
  4636. Invalid(false) {}
  4637. void DiagnoseAbstractType() {
  4638. if (Invalid) return;
  4639. S.DiagnoseAbstractType(Record);
  4640. Invalid = true;
  4641. }
  4642. void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
  4643. };
  4644. struct CheckAbstractUsage {
  4645. AbstractUsageInfo &Info;
  4646. const NamedDecl *Ctx;
  4647. CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
  4648. : Info(Info), Ctx(Ctx) {}
  4649. void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4650. switch (TL.getTypeLocClass()) {
  4651. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  4652. #define TYPELOC(CLASS, PARENT) \
  4653. case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
  4654. #include "clang/AST/TypeLocNodes.def"
  4655. }
  4656. }
  4657. void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4658. Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
  4659. for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
  4660. if (!TL.getParam(I))
  4661. continue;
  4662. TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
  4663. if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
  4664. }
  4665. }
  4666. void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4667. Visit(TL.getElementLoc(), Sema::AbstractArrayType);
  4668. }
  4669. void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4670. // Visit the type parameters from a permissive context.
  4671. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
  4672. TemplateArgumentLoc TAL = TL.getArgLoc(I);
  4673. if (TAL.getArgument().getKind() == TemplateArgument::Type)
  4674. if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
  4675. Visit(TSI->getTypeLoc(), Sema::AbstractNone);
  4676. // TODO: other template argument types?
  4677. }
  4678. }
  4679. // Visit pointee types from a permissive context.
  4680. #define CheckPolymorphic(Type) \
  4681. void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
  4682. Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
  4683. }
  4684. CheckPolymorphic(PointerTypeLoc)
  4685. CheckPolymorphic(ReferenceTypeLoc)
  4686. CheckPolymorphic(MemberPointerTypeLoc)
  4687. CheckPolymorphic(BlockPointerTypeLoc)
  4688. CheckPolymorphic(AtomicTypeLoc)
  4689. /// Handle all the types we haven't given a more specific
  4690. /// implementation for above.
  4691. void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4692. // Every other kind of type that we haven't called out already
  4693. // that has an inner type is either (1) sugar or (2) contains that
  4694. // inner type in some way as a subobject.
  4695. if (TypeLoc Next = TL.getNextTypeLoc())
  4696. return Visit(Next, Sel);
  4697. // If there's no inner type and we're in a permissive context,
  4698. // don't diagnose.
  4699. if (Sel == Sema::AbstractNone) return;
  4700. // Check whether the type matches the abstract type.
  4701. QualType T = TL.getType();
  4702. if (T->isArrayType()) {
  4703. Sel = Sema::AbstractArrayType;
  4704. T = Info.S.Context.getBaseElementType(T);
  4705. }
  4706. CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
  4707. if (CT != Info.AbstractType) return;
  4708. // It matched; do some magic.
  4709. if (Sel == Sema::AbstractArrayType) {
  4710. Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
  4711. << T << TL.getSourceRange();
  4712. } else {
  4713. Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
  4714. << Sel << T << TL.getSourceRange();
  4715. }
  4716. Info.DiagnoseAbstractType();
  4717. }
  4718. };
  4719. void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
  4720. Sema::AbstractDiagSelID Sel) {
  4721. CheckAbstractUsage(*this, D).Visit(TL, Sel);
  4722. }
  4723. }
  4724. /// Check for invalid uses of an abstract type in a method declaration.
  4725. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4726. CXXMethodDecl *MD) {
  4727. // No need to do the check on definitions, which require that
  4728. // the return/param types be complete.
  4729. if (MD->doesThisDeclarationHaveABody())
  4730. return;
  4731. // For safety's sake, just ignore it if we don't have type source
  4732. // information. This should never happen for non-implicit methods,
  4733. // but...
  4734. if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
  4735. Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
  4736. }
  4737. /// Check for invalid uses of an abstract type within a class definition.
  4738. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4739. CXXRecordDecl *RD) {
  4740. for (auto *D : RD->decls()) {
  4741. if (D->isImplicit()) continue;
  4742. // Methods and method templates.
  4743. if (isa<CXXMethodDecl>(D)) {
  4744. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
  4745. } else if (isa<FunctionTemplateDecl>(D)) {
  4746. FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
  4747. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
  4748. // Fields and static variables.
  4749. } else if (isa<FieldDecl>(D)) {
  4750. FieldDecl *FD = cast<FieldDecl>(D);
  4751. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  4752. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
  4753. } else if (isa<VarDecl>(D)) {
  4754. VarDecl *VD = cast<VarDecl>(D);
  4755. if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
  4756. Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
  4757. // Nested classes and class templates.
  4758. } else if (isa<CXXRecordDecl>(D)) {
  4759. CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
  4760. } else if (isa<ClassTemplateDecl>(D)) {
  4761. CheckAbstractClassUsage(Info,
  4762. cast<ClassTemplateDecl>(D)->getTemplatedDecl());
  4763. }
  4764. }
  4765. }
  4766. static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
  4767. Attr *ClassAttr = getDLLAttr(Class);
  4768. if (!ClassAttr)
  4769. return;
  4770. assert(ClassAttr->getKind() == attr::DLLExport);
  4771. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  4772. if (TSK == TSK_ExplicitInstantiationDeclaration)
  4773. // Don't go any further if this is just an explicit instantiation
  4774. // declaration.
  4775. return;
  4776. for (Decl *Member : Class->decls()) {
  4777. // Defined static variables that are members of an exported base
  4778. // class must be marked export too.
  4779. auto *VD = dyn_cast<VarDecl>(Member);
  4780. if (VD && Member->getAttr<DLLExportAttr>() &&
  4781. VD->getStorageClass() == SC_Static &&
  4782. TSK == TSK_ImplicitInstantiation)
  4783. S.MarkVariableReferenced(VD->getLocation(), VD);
  4784. auto *MD = dyn_cast<CXXMethodDecl>(Member);
  4785. if (!MD)
  4786. continue;
  4787. if (Member->getAttr<DLLExportAttr>()) {
  4788. if (MD->isUserProvided()) {
  4789. // Instantiate non-default class member functions ...
  4790. // .. except for certain kinds of template specializations.
  4791. if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
  4792. continue;
  4793. S.MarkFunctionReferenced(Class->getLocation(), MD);
  4794. // The function will be passed to the consumer when its definition is
  4795. // encountered.
  4796. } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
  4797. MD->isCopyAssignmentOperator() ||
  4798. MD->isMoveAssignmentOperator()) {
  4799. // Synthesize and instantiate non-trivial implicit methods, explicitly
  4800. // defaulted methods, and the copy and move assignment operators. The
  4801. // latter are exported even if they are trivial, because the address of
  4802. // an operator can be taken and should compare equal across libraries.
  4803. DiagnosticErrorTrap Trap(S.Diags);
  4804. S.MarkFunctionReferenced(Class->getLocation(), MD);
  4805. if (Trap.hasErrorOccurred()) {
  4806. S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
  4807. << Class << !S.getLangOpts().CPlusPlus11;
  4808. break;
  4809. }
  4810. // There is no later point when we will see the definition of this
  4811. // function, so pass it to the consumer now.
  4812. S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
  4813. }
  4814. }
  4815. }
  4816. }
  4817. static void checkForMultipleExportedDefaultConstructors(Sema &S,
  4818. CXXRecordDecl *Class) {
  4819. // Only the MS ABI has default constructor closures, so we don't need to do
  4820. // this semantic checking anywhere else.
  4821. if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
  4822. return;
  4823. CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
  4824. for (Decl *Member : Class->decls()) {
  4825. // Look for exported default constructors.
  4826. auto *CD = dyn_cast<CXXConstructorDecl>(Member);
  4827. if (!CD || !CD->isDefaultConstructor())
  4828. continue;
  4829. auto *Attr = CD->getAttr<DLLExportAttr>();
  4830. if (!Attr)
  4831. continue;
  4832. // If the class is non-dependent, mark the default arguments as ODR-used so
  4833. // that we can properly codegen the constructor closure.
  4834. if (!Class->isDependentContext()) {
  4835. for (ParmVarDecl *PD : CD->parameters()) {
  4836. (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
  4837. S.DiscardCleanupsInEvaluationContext();
  4838. }
  4839. }
  4840. if (LastExportedDefaultCtor) {
  4841. S.Diag(LastExportedDefaultCtor->getLocation(),
  4842. diag::err_attribute_dll_ambiguous_default_ctor)
  4843. << Class;
  4844. S.Diag(CD->getLocation(), diag::note_entity_declared_at)
  4845. << CD->getDeclName();
  4846. return;
  4847. }
  4848. LastExportedDefaultCtor = CD;
  4849. }
  4850. }
  4851. void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
  4852. // Mark any compiler-generated routines with the implicit code_seg attribute.
  4853. for (auto *Method : Class->methods()) {
  4854. if (Method->isUserProvided())
  4855. continue;
  4856. if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
  4857. Method->addAttr(A);
  4858. }
  4859. }
  4860. /// Check class-level dllimport/dllexport attribute.
  4861. void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
  4862. Attr *ClassAttr = getDLLAttr(Class);
  4863. // MSVC inherits DLL attributes to partial class template specializations.
  4864. if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
  4865. if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
  4866. if (Attr *TemplateAttr =
  4867. getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
  4868. auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
  4869. A->setInherited(true);
  4870. ClassAttr = A;
  4871. }
  4872. }
  4873. }
  4874. if (!ClassAttr)
  4875. return;
  4876. if (!Class->isExternallyVisible()) {
  4877. Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
  4878. << Class << ClassAttr;
  4879. return;
  4880. }
  4881. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  4882. !ClassAttr->isInherited()) {
  4883. // Diagnose dll attributes on members of class with dll attribute.
  4884. for (Decl *Member : Class->decls()) {
  4885. if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
  4886. continue;
  4887. InheritableAttr *MemberAttr = getDLLAttr(Member);
  4888. if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
  4889. continue;
  4890. Diag(MemberAttr->getLocation(),
  4891. diag::err_attribute_dll_member_of_dll_class)
  4892. << MemberAttr << ClassAttr;
  4893. Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
  4894. Member->setInvalidDecl();
  4895. }
  4896. }
  4897. if (Class->getDescribedClassTemplate())
  4898. // Don't inherit dll attribute until the template is instantiated.
  4899. return;
  4900. // The class is either imported or exported.
  4901. const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
  4902. // Check if this was a dllimport attribute propagated from a derived class to
  4903. // a base class template specialization. We don't apply these attributes to
  4904. // static data members.
  4905. const bool PropagatedImport =
  4906. !ClassExported &&
  4907. cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
  4908. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  4909. // Ignore explicit dllexport on explicit class template instantiation declarations.
  4910. if (ClassExported && !ClassAttr->isInherited() &&
  4911. TSK == TSK_ExplicitInstantiationDeclaration) {
  4912. Class->dropAttr<DLLExportAttr>();
  4913. return;
  4914. }
  4915. // Force declaration of implicit members so they can inherit the attribute.
  4916. ForceDeclarationOfImplicitMembers(Class);
  4917. // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
  4918. // seem to be true in practice?
  4919. for (Decl *Member : Class->decls()) {
  4920. VarDecl *VD = dyn_cast<VarDecl>(Member);
  4921. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
  4922. // Only methods and static fields inherit the attributes.
  4923. if (!VD && !MD)
  4924. continue;
  4925. if (MD) {
  4926. // Don't process deleted methods.
  4927. if (MD->isDeleted())
  4928. continue;
  4929. if (MD->isInlined()) {
  4930. // MinGW does not import or export inline methods.
  4931. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  4932. !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
  4933. continue;
  4934. // MSVC versions before 2015 don't export the move assignment operators
  4935. // and move constructor, so don't attempt to import/export them if
  4936. // we have a definition.
  4937. auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
  4938. if ((MD->isMoveAssignmentOperator() ||
  4939. (Ctor && Ctor->isMoveConstructor())) &&
  4940. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
  4941. continue;
  4942. // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
  4943. // operator is exported anyway.
  4944. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  4945. (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
  4946. continue;
  4947. }
  4948. }
  4949. // Don't apply dllimport attributes to static data members of class template
  4950. // instantiations when the attribute is propagated from a derived class.
  4951. if (VD && PropagatedImport)
  4952. continue;
  4953. if (!cast<NamedDecl>(Member)->isExternallyVisible())
  4954. continue;
  4955. if (!getDLLAttr(Member)) {
  4956. InheritableAttr *NewAttr = nullptr;
  4957. // Do not export/import inline function when -fno-dllexport-inlines is
  4958. // passed. But add attribute for later local static var check.
  4959. if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
  4960. TSK != TSK_ExplicitInstantiationDeclaration &&
  4961. TSK != TSK_ExplicitInstantiationDefinition) {
  4962. if (ClassExported) {
  4963. NewAttr = ::new (getASTContext())
  4964. DLLExportStaticLocalAttr(ClassAttr->getRange(),
  4965. getASTContext(),
  4966. ClassAttr->getSpellingListIndex());
  4967. } else {
  4968. NewAttr = ::new (getASTContext())
  4969. DLLImportStaticLocalAttr(ClassAttr->getRange(),
  4970. getASTContext(),
  4971. ClassAttr->getSpellingListIndex());
  4972. }
  4973. } else {
  4974. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  4975. }
  4976. NewAttr->setInherited(true);
  4977. Member->addAttr(NewAttr);
  4978. if (MD) {
  4979. // Propagate DLLAttr to friend re-declarations of MD that have already
  4980. // been constructed.
  4981. for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
  4982. FD = FD->getPreviousDecl()) {
  4983. if (FD->getFriendObjectKind() == Decl::FOK_None)
  4984. continue;
  4985. assert(!getDLLAttr(FD) &&
  4986. "friend re-decl should not already have a DLLAttr");
  4987. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  4988. NewAttr->setInherited(true);
  4989. FD->addAttr(NewAttr);
  4990. }
  4991. }
  4992. }
  4993. }
  4994. if (ClassExported)
  4995. DelayedDllExportClasses.push_back(Class);
  4996. }
  4997. /// Perform propagation of DLL attributes from a derived class to a
  4998. /// templated base class for MS compatibility.
  4999. void Sema::propagateDLLAttrToBaseClassTemplate(
  5000. CXXRecordDecl *Class, Attr *ClassAttr,
  5001. ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
  5002. if (getDLLAttr(
  5003. BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
  5004. // If the base class template has a DLL attribute, don't try to change it.
  5005. return;
  5006. }
  5007. auto TSK = BaseTemplateSpec->getSpecializationKind();
  5008. if (!getDLLAttr(BaseTemplateSpec) &&
  5009. (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
  5010. TSK == TSK_ImplicitInstantiation)) {
  5011. // The template hasn't been instantiated yet (or it has, but only as an
  5012. // explicit instantiation declaration or implicit instantiation, which means
  5013. // we haven't codegenned any members yet), so propagate the attribute.
  5014. auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5015. NewAttr->setInherited(true);
  5016. BaseTemplateSpec->addAttr(NewAttr);
  5017. // If this was an import, mark that we propagated it from a derived class to
  5018. // a base class template specialization.
  5019. if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
  5020. ImportAttr->setPropagatedToBaseTemplate();
  5021. // If the template is already instantiated, checkDLLAttributeRedeclaration()
  5022. // needs to be run again to work see the new attribute. Otherwise this will
  5023. // get run whenever the template is instantiated.
  5024. if (TSK != TSK_Undeclared)
  5025. checkClassLevelDLLAttribute(BaseTemplateSpec);
  5026. return;
  5027. }
  5028. if (getDLLAttr(BaseTemplateSpec)) {
  5029. // The template has already been specialized or instantiated with an
  5030. // attribute, explicitly or through propagation. We should not try to change
  5031. // it.
  5032. return;
  5033. }
  5034. // The template was previously instantiated or explicitly specialized without
  5035. // a dll attribute, It's too late for us to add an attribute, so warn that
  5036. // this is unsupported.
  5037. Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
  5038. << BaseTemplateSpec->isExplicitSpecialization();
  5039. Diag(ClassAttr->getLocation(), diag::note_attribute);
  5040. if (BaseTemplateSpec->isExplicitSpecialization()) {
  5041. Diag(BaseTemplateSpec->getLocation(),
  5042. diag::note_template_class_explicit_specialization_was_here)
  5043. << BaseTemplateSpec;
  5044. } else {
  5045. Diag(BaseTemplateSpec->getPointOfInstantiation(),
  5046. diag::note_template_class_instantiation_was_here)
  5047. << BaseTemplateSpec;
  5048. }
  5049. }
  5050. static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
  5051. SourceLocation DefaultLoc) {
  5052. switch (S.getSpecialMember(MD)) {
  5053. case Sema::CXXDefaultConstructor:
  5054. S.DefineImplicitDefaultConstructor(DefaultLoc,
  5055. cast<CXXConstructorDecl>(MD));
  5056. break;
  5057. case Sema::CXXCopyConstructor:
  5058. S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  5059. break;
  5060. case Sema::CXXCopyAssignment:
  5061. S.DefineImplicitCopyAssignment(DefaultLoc, MD);
  5062. break;
  5063. case Sema::CXXDestructor:
  5064. S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
  5065. break;
  5066. case Sema::CXXMoveConstructor:
  5067. S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  5068. break;
  5069. case Sema::CXXMoveAssignment:
  5070. S.DefineImplicitMoveAssignment(DefaultLoc, MD);
  5071. break;
  5072. case Sema::CXXInvalid:
  5073. llvm_unreachable("Invalid special member.");
  5074. }
  5075. }
  5076. /// Determine whether a type is permitted to be passed or returned in
  5077. /// registers, per C++ [class.temporary]p3.
  5078. static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
  5079. TargetInfo::CallingConvKind CCK) {
  5080. if (D->isDependentType() || D->isInvalidDecl())
  5081. return false;
  5082. // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
  5083. // The PS4 platform ABI follows the behavior of Clang 3.2.
  5084. if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
  5085. return !D->hasNonTrivialDestructorForCall() &&
  5086. !D->hasNonTrivialCopyConstructorForCall();
  5087. if (CCK == TargetInfo::CCK_MicrosoftWin64) {
  5088. bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
  5089. bool DtorIsTrivialForCall = false;
  5090. // If a class has at least one non-deleted, trivial copy constructor, it
  5091. // is passed according to the C ABI. Otherwise, it is passed indirectly.
  5092. //
  5093. // Note: This permits classes with non-trivial copy or move ctors to be
  5094. // passed in registers, so long as they *also* have a trivial copy ctor,
  5095. // which is non-conforming.
  5096. if (D->needsImplicitCopyConstructor()) {
  5097. if (!D->defaultedCopyConstructorIsDeleted()) {
  5098. if (D->hasTrivialCopyConstructor())
  5099. CopyCtorIsTrivial = true;
  5100. if (D->hasTrivialCopyConstructorForCall())
  5101. CopyCtorIsTrivialForCall = true;
  5102. }
  5103. } else {
  5104. for (const CXXConstructorDecl *CD : D->ctors()) {
  5105. if (CD->isCopyConstructor() && !CD->isDeleted()) {
  5106. if (CD->isTrivial())
  5107. CopyCtorIsTrivial = true;
  5108. if (CD->isTrivialForCall())
  5109. CopyCtorIsTrivialForCall = true;
  5110. }
  5111. }
  5112. }
  5113. if (D->needsImplicitDestructor()) {
  5114. if (!D->defaultedDestructorIsDeleted() &&
  5115. D->hasTrivialDestructorForCall())
  5116. DtorIsTrivialForCall = true;
  5117. } else if (const auto *DD = D->getDestructor()) {
  5118. if (!DD->isDeleted() && DD->isTrivialForCall())
  5119. DtorIsTrivialForCall = true;
  5120. }
  5121. // If the copy ctor and dtor are both trivial-for-calls, pass direct.
  5122. if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
  5123. return true;
  5124. // If a class has a destructor, we'd really like to pass it indirectly
  5125. // because it allows us to elide copies. Unfortunately, MSVC makes that
  5126. // impossible for small types, which it will pass in a single register or
  5127. // stack slot. Most objects with dtors are large-ish, so handle that early.
  5128. // We can't call out all large objects as being indirect because there are
  5129. // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
  5130. // how we pass large POD types.
  5131. // Note: This permits small classes with nontrivial destructors to be
  5132. // passed in registers, which is non-conforming.
  5133. if (CopyCtorIsTrivial &&
  5134. S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
  5135. return true;
  5136. return false;
  5137. }
  5138. // Per C++ [class.temporary]p3, the relevant condition is:
  5139. // each copy constructor, move constructor, and destructor of X is
  5140. // either trivial or deleted, and X has at least one non-deleted copy
  5141. // or move constructor
  5142. bool HasNonDeletedCopyOrMove = false;
  5143. if (D->needsImplicitCopyConstructor() &&
  5144. !D->defaultedCopyConstructorIsDeleted()) {
  5145. if (!D->hasTrivialCopyConstructorForCall())
  5146. return false;
  5147. HasNonDeletedCopyOrMove = true;
  5148. }
  5149. if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
  5150. !D->defaultedMoveConstructorIsDeleted()) {
  5151. if (!D->hasTrivialMoveConstructorForCall())
  5152. return false;
  5153. HasNonDeletedCopyOrMove = true;
  5154. }
  5155. if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
  5156. !D->hasTrivialDestructorForCall())
  5157. return false;
  5158. for (const CXXMethodDecl *MD : D->methods()) {
  5159. if (MD->isDeleted())
  5160. continue;
  5161. auto *CD = dyn_cast<CXXConstructorDecl>(MD);
  5162. if (CD && CD->isCopyOrMoveConstructor())
  5163. HasNonDeletedCopyOrMove = true;
  5164. else if (!isa<CXXDestructorDecl>(MD))
  5165. continue;
  5166. if (!MD->isTrivialForCall())
  5167. return false;
  5168. }
  5169. return HasNonDeletedCopyOrMove;
  5170. }
  5171. /// Perform semantic checks on a class definition that has been
  5172. /// completing, introducing implicitly-declared members, checking for
  5173. /// abstract types, etc.
  5174. void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
  5175. if (!Record)
  5176. return;
  5177. if (Record->isAbstract() && !Record->isInvalidDecl()) {
  5178. AbstractUsageInfo Info(*this, Record);
  5179. CheckAbstractClassUsage(Info, Record);
  5180. }
  5181. // If this is not an aggregate type and has no user-declared constructor,
  5182. // complain about any non-static data members of reference or const scalar
  5183. // type, since they will never get initializers.
  5184. if (!Record->isInvalidDecl() && !Record->isDependentType() &&
  5185. !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
  5186. !Record->isLambda()) {
  5187. bool Complained = false;
  5188. for (const auto *F : Record->fields()) {
  5189. if (F->hasInClassInitializer() || F->isUnnamedBitfield())
  5190. continue;
  5191. if (F->getType()->isReferenceType() ||
  5192. (F->getType().isConstQualified() && F->getType()->isScalarType())) {
  5193. if (!Complained) {
  5194. Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
  5195. << Record->getTagKind() << Record;
  5196. Complained = true;
  5197. }
  5198. Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
  5199. << F->getType()->isReferenceType()
  5200. << F->getDeclName();
  5201. }
  5202. }
  5203. }
  5204. if (Record->getIdentifier()) {
  5205. // C++ [class.mem]p13:
  5206. // If T is the name of a class, then each of the following shall have a
  5207. // name different from T:
  5208. // - every member of every anonymous union that is a member of class T.
  5209. //
  5210. // C++ [class.mem]p14:
  5211. // In addition, if class T has a user-declared constructor (12.1), every
  5212. // non-static data member of class T shall have a name different from T.
  5213. DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
  5214. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
  5215. ++I) {
  5216. NamedDecl *D = (*I)->getUnderlyingDecl();
  5217. if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
  5218. Record->hasUserDeclaredConstructor()) ||
  5219. isa<IndirectFieldDecl>(D)) {
  5220. Diag((*I)->getLocation(), diag::err_member_name_of_class)
  5221. << D->getDeclName();
  5222. break;
  5223. }
  5224. }
  5225. }
  5226. // Warn if the class has virtual methods but non-virtual public destructor.
  5227. if (Record->isPolymorphic() && !Record->isDependentType()) {
  5228. CXXDestructorDecl *dtor = Record->getDestructor();
  5229. if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
  5230. !Record->hasAttr<FinalAttr>())
  5231. Diag(dtor ? dtor->getLocation() : Record->getLocation(),
  5232. diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
  5233. }
  5234. if (Record->isAbstract()) {
  5235. if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
  5236. Diag(Record->getLocation(), diag::warn_abstract_final_class)
  5237. << FA->isSpelledAsSealed();
  5238. DiagnoseAbstractType(Record);
  5239. }
  5240. }
  5241. // See if trivial_abi has to be dropped.
  5242. if (Record->hasAttr<TrivialABIAttr>())
  5243. checkIllFormedTrivialABIStruct(*Record);
  5244. // Set HasTrivialSpecialMemberForCall if the record has attribute
  5245. // "trivial_abi".
  5246. bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
  5247. if (HasTrivialABI)
  5248. Record->setHasTrivialSpecialMemberForCall();
  5249. bool HasMethodWithOverrideControl = false,
  5250. HasOverridingMethodWithoutOverrideControl = false;
  5251. if (!Record->isDependentType()) {
  5252. for (auto *M : Record->methods()) {
  5253. // See if a method overloads virtual methods in a base
  5254. // class without overriding any.
  5255. if (!M->isStatic())
  5256. DiagnoseHiddenVirtualMethods(M);
  5257. if (M->hasAttr<OverrideAttr>())
  5258. HasMethodWithOverrideControl = true;
  5259. else if (M->size_overridden_methods() > 0)
  5260. HasOverridingMethodWithoutOverrideControl = true;
  5261. // Check whether the explicitly-defaulted special members are valid.
  5262. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
  5263. CheckExplicitlyDefaultedSpecialMember(M);
  5264. // For an explicitly defaulted or deleted special member, we defer
  5265. // determining triviality until the class is complete. That time is now!
  5266. CXXSpecialMember CSM = getSpecialMember(M);
  5267. if (!M->isImplicit() && !M->isUserProvided()) {
  5268. if (CSM != CXXInvalid) {
  5269. M->setTrivial(SpecialMemberIsTrivial(M, CSM));
  5270. // Inform the class that we've finished declaring this member.
  5271. Record->finishedDefaultedOrDeletedMember(M);
  5272. M->setTrivialForCall(
  5273. HasTrivialABI ||
  5274. SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
  5275. Record->setTrivialForCallFlags(M);
  5276. }
  5277. }
  5278. // Set triviality for the purpose of calls if this is a user-provided
  5279. // copy/move constructor or destructor.
  5280. if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
  5281. CSM == CXXDestructor) && M->isUserProvided()) {
  5282. M->setTrivialForCall(HasTrivialABI);
  5283. Record->setTrivialForCallFlags(M);
  5284. }
  5285. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
  5286. M->hasAttr<DLLExportAttr>()) {
  5287. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  5288. M->isTrivial() &&
  5289. (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
  5290. CSM == CXXDestructor))
  5291. M->dropAttr<DLLExportAttr>();
  5292. if (M->hasAttr<DLLExportAttr>()) {
  5293. DefineImplicitSpecialMember(*this, M, M->getLocation());
  5294. ActOnFinishInlineFunctionDef(M);
  5295. }
  5296. }
  5297. }
  5298. }
  5299. if (HasMethodWithOverrideControl &&
  5300. HasOverridingMethodWithoutOverrideControl) {
  5301. // At least one method has the 'override' control declared.
  5302. // Diagnose all other overridden methods which do not have 'override' specified on them.
  5303. for (auto *M : Record->methods())
  5304. DiagnoseAbsenceOfOverrideControl(M);
  5305. }
  5306. // ms_struct is a request to use the same ABI rules as MSVC. Check
  5307. // whether this class uses any C++ features that are implemented
  5308. // completely differently in MSVC, and if so, emit a diagnostic.
  5309. // That diagnostic defaults to an error, but we allow projects to
  5310. // map it down to a warning (or ignore it). It's a fairly common
  5311. // practice among users of the ms_struct pragma to mass-annotate
  5312. // headers, sweeping up a bunch of types that the project doesn't
  5313. // really rely on MSVC-compatible layout for. We must therefore
  5314. // support "ms_struct except for C++ stuff" as a secondary ABI.
  5315. if (Record->isMsStruct(Context) &&
  5316. (Record->isPolymorphic() || Record->getNumBases())) {
  5317. Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
  5318. }
  5319. checkClassLevelDLLAttribute(Record);
  5320. checkClassLevelCodeSegAttribute(Record);
  5321. bool ClangABICompat4 =
  5322. Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
  5323. TargetInfo::CallingConvKind CCK =
  5324. Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
  5325. bool CanPass = canPassInRegisters(*this, Record, CCK);
  5326. // Do not change ArgPassingRestrictions if it has already been set to
  5327. // APK_CanNeverPassInRegs.
  5328. if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
  5329. Record->setArgPassingRestrictions(CanPass
  5330. ? RecordDecl::APK_CanPassInRegs
  5331. : RecordDecl::APK_CannotPassInRegs);
  5332. // If canPassInRegisters returns true despite the record having a non-trivial
  5333. // destructor, the record is destructed in the callee. This happens only when
  5334. // the record or one of its subobjects has a field annotated with trivial_abi
  5335. // or a field qualified with ObjC __strong/__weak.
  5336. if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
  5337. Record->setParamDestroyedInCallee(true);
  5338. else if (Record->hasNonTrivialDestructor())
  5339. Record->setParamDestroyedInCallee(CanPass);
  5340. if (getLangOpts().ForceEmitVTables) {
  5341. // If we want to emit all the vtables, we need to mark it as used. This
  5342. // is especially required for cases like vtable assumption loads.
  5343. MarkVTableUsed(Record->getInnerLocStart(), Record);
  5344. }
  5345. }
  5346. /// Look up the special member function that would be called by a special
  5347. /// member function for a subobject of class type.
  5348. ///
  5349. /// \param Class The class type of the subobject.
  5350. /// \param CSM The kind of special member function.
  5351. /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
  5352. /// \param ConstRHS True if this is a copy operation with a const object
  5353. /// on its RHS, that is, if the argument to the outer special member
  5354. /// function is 'const' and this is not a field marked 'mutable'.
  5355. static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
  5356. Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
  5357. unsigned FieldQuals, bool ConstRHS) {
  5358. unsigned LHSQuals = 0;
  5359. if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
  5360. LHSQuals = FieldQuals;
  5361. unsigned RHSQuals = FieldQuals;
  5362. if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
  5363. RHSQuals = 0;
  5364. else if (ConstRHS)
  5365. RHSQuals |= Qualifiers::Const;
  5366. return S.LookupSpecialMember(Class, CSM,
  5367. RHSQuals & Qualifiers::Const,
  5368. RHSQuals & Qualifiers::Volatile,
  5369. false,
  5370. LHSQuals & Qualifiers::Const,
  5371. LHSQuals & Qualifiers::Volatile);
  5372. }
  5373. class Sema::InheritedConstructorInfo {
  5374. Sema &S;
  5375. SourceLocation UseLoc;
  5376. /// A mapping from the base classes through which the constructor was
  5377. /// inherited to the using shadow declaration in that base class (or a null
  5378. /// pointer if the constructor was declared in that base class).
  5379. llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
  5380. InheritedFromBases;
  5381. public:
  5382. InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
  5383. ConstructorUsingShadowDecl *Shadow)
  5384. : S(S), UseLoc(UseLoc) {
  5385. bool DiagnosedMultipleConstructedBases = false;
  5386. CXXRecordDecl *ConstructedBase = nullptr;
  5387. UsingDecl *ConstructedBaseUsing = nullptr;
  5388. // Find the set of such base class subobjects and check that there's a
  5389. // unique constructed subobject.
  5390. for (auto *D : Shadow->redecls()) {
  5391. auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
  5392. auto *DNominatedBase = DShadow->getNominatedBaseClass();
  5393. auto *DConstructedBase = DShadow->getConstructedBaseClass();
  5394. InheritedFromBases.insert(
  5395. std::make_pair(DNominatedBase->getCanonicalDecl(),
  5396. DShadow->getNominatedBaseClassShadowDecl()));
  5397. if (DShadow->constructsVirtualBase())
  5398. InheritedFromBases.insert(
  5399. std::make_pair(DConstructedBase->getCanonicalDecl(),
  5400. DShadow->getConstructedBaseClassShadowDecl()));
  5401. else
  5402. assert(DNominatedBase == DConstructedBase);
  5403. // [class.inhctor.init]p2:
  5404. // If the constructor was inherited from multiple base class subobjects
  5405. // of type B, the program is ill-formed.
  5406. if (!ConstructedBase) {
  5407. ConstructedBase = DConstructedBase;
  5408. ConstructedBaseUsing = D->getUsingDecl();
  5409. } else if (ConstructedBase != DConstructedBase &&
  5410. !Shadow->isInvalidDecl()) {
  5411. if (!DiagnosedMultipleConstructedBases) {
  5412. S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
  5413. << Shadow->getTargetDecl();
  5414. S.Diag(ConstructedBaseUsing->getLocation(),
  5415. diag::note_ambiguous_inherited_constructor_using)
  5416. << ConstructedBase;
  5417. DiagnosedMultipleConstructedBases = true;
  5418. }
  5419. S.Diag(D->getUsingDecl()->getLocation(),
  5420. diag::note_ambiguous_inherited_constructor_using)
  5421. << DConstructedBase;
  5422. }
  5423. }
  5424. if (DiagnosedMultipleConstructedBases)
  5425. Shadow->setInvalidDecl();
  5426. }
  5427. /// Find the constructor to use for inherited construction of a base class,
  5428. /// and whether that base class constructor inherits the constructor from a
  5429. /// virtual base class (in which case it won't actually invoke it).
  5430. std::pair<CXXConstructorDecl *, bool>
  5431. findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
  5432. auto It = InheritedFromBases.find(Base->getCanonicalDecl());
  5433. if (It == InheritedFromBases.end())
  5434. return std::make_pair(nullptr, false);
  5435. // This is an intermediary class.
  5436. if (It->second)
  5437. return std::make_pair(
  5438. S.findInheritingConstructor(UseLoc, Ctor, It->second),
  5439. It->second->constructsVirtualBase());
  5440. // This is the base class from which the constructor was inherited.
  5441. return std::make_pair(Ctor, false);
  5442. }
  5443. };
  5444. /// Is the special member function which would be selected to perform the
  5445. /// specified operation on the specified class type a constexpr constructor?
  5446. static bool
  5447. specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
  5448. Sema::CXXSpecialMember CSM, unsigned Quals,
  5449. bool ConstRHS,
  5450. CXXConstructorDecl *InheritedCtor = nullptr,
  5451. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5452. // If we're inheriting a constructor, see if we need to call it for this base
  5453. // class.
  5454. if (InheritedCtor) {
  5455. assert(CSM == Sema::CXXDefaultConstructor);
  5456. auto BaseCtor =
  5457. Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
  5458. if (BaseCtor)
  5459. return BaseCtor->isConstexpr();
  5460. }
  5461. if (CSM == Sema::CXXDefaultConstructor)
  5462. return ClassDecl->hasConstexprDefaultConstructor();
  5463. Sema::SpecialMemberOverloadResult SMOR =
  5464. lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
  5465. if (!SMOR.getMethod())
  5466. // A constructor we wouldn't select can't be "involved in initializing"
  5467. // anything.
  5468. return true;
  5469. return SMOR.getMethod()->isConstexpr();
  5470. }
  5471. /// Determine whether the specified special member function would be constexpr
  5472. /// if it were implicitly defined.
  5473. static bool defaultedSpecialMemberIsConstexpr(
  5474. Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
  5475. bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
  5476. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5477. if (!S.getLangOpts().CPlusPlus11)
  5478. return false;
  5479. // C++11 [dcl.constexpr]p4:
  5480. // In the definition of a constexpr constructor [...]
  5481. bool Ctor = true;
  5482. switch (CSM) {
  5483. case Sema::CXXDefaultConstructor:
  5484. if (Inherited)
  5485. break;
  5486. // Since default constructor lookup is essentially trivial (and cannot
  5487. // involve, for instance, template instantiation), we compute whether a
  5488. // defaulted default constructor is constexpr directly within CXXRecordDecl.
  5489. //
  5490. // This is important for performance; we need to know whether the default
  5491. // constructor is constexpr to determine whether the type is a literal type.
  5492. return ClassDecl->defaultedDefaultConstructorIsConstexpr();
  5493. case Sema::CXXCopyConstructor:
  5494. case Sema::CXXMoveConstructor:
  5495. // For copy or move constructors, we need to perform overload resolution.
  5496. break;
  5497. case Sema::CXXCopyAssignment:
  5498. case Sema::CXXMoveAssignment:
  5499. if (!S.getLangOpts().CPlusPlus14)
  5500. return false;
  5501. // In C++1y, we need to perform overload resolution.
  5502. Ctor = false;
  5503. break;
  5504. case Sema::CXXDestructor:
  5505. case Sema::CXXInvalid:
  5506. return false;
  5507. }
  5508. // -- if the class is a non-empty union, or for each non-empty anonymous
  5509. // union member of a non-union class, exactly one non-static data member
  5510. // shall be initialized; [DR1359]
  5511. //
  5512. // If we squint, this is guaranteed, since exactly one non-static data member
  5513. // will be initialized (if the constructor isn't deleted), we just don't know
  5514. // which one.
  5515. if (Ctor && ClassDecl->isUnion())
  5516. return CSM == Sema::CXXDefaultConstructor
  5517. ? ClassDecl->hasInClassInitializer() ||
  5518. !ClassDecl->hasVariantMembers()
  5519. : true;
  5520. // -- the class shall not have any virtual base classes;
  5521. if (Ctor && ClassDecl->getNumVBases())
  5522. return false;
  5523. // C++1y [class.copy]p26:
  5524. // -- [the class] is a literal type, and
  5525. if (!Ctor && !ClassDecl->isLiteral())
  5526. return false;
  5527. // -- every constructor involved in initializing [...] base class
  5528. // sub-objects shall be a constexpr constructor;
  5529. // -- the assignment operator selected to copy/move each direct base
  5530. // class is a constexpr function, and
  5531. for (const auto &B : ClassDecl->bases()) {
  5532. const RecordType *BaseType = B.getType()->getAs<RecordType>();
  5533. if (!BaseType) continue;
  5534. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  5535. if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
  5536. InheritedCtor, Inherited))
  5537. return false;
  5538. }
  5539. // -- every constructor involved in initializing non-static data members
  5540. // [...] shall be a constexpr constructor;
  5541. // -- every non-static data member and base class sub-object shall be
  5542. // initialized
  5543. // -- for each non-static data member of X that is of class type (or array
  5544. // thereof), the assignment operator selected to copy/move that member is
  5545. // a constexpr function
  5546. for (const auto *F : ClassDecl->fields()) {
  5547. if (F->isInvalidDecl())
  5548. continue;
  5549. if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
  5550. continue;
  5551. QualType BaseType = S.Context.getBaseElementType(F->getType());
  5552. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  5553. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  5554. if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
  5555. BaseType.getCVRQualifiers(),
  5556. ConstArg && !F->isMutable()))
  5557. return false;
  5558. } else if (CSM == Sema::CXXDefaultConstructor) {
  5559. return false;
  5560. }
  5561. }
  5562. // All OK, it's constexpr!
  5563. return true;
  5564. }
  5565. static Sema::ImplicitExceptionSpecification
  5566. ComputeDefaultedSpecialMemberExceptionSpec(
  5567. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  5568. Sema::InheritedConstructorInfo *ICI);
  5569. static Sema::ImplicitExceptionSpecification
  5570. computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
  5571. auto CSM = S.getSpecialMember(MD);
  5572. if (CSM != Sema::CXXInvalid)
  5573. return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
  5574. auto *CD = cast<CXXConstructorDecl>(MD);
  5575. assert(CD->getInheritedConstructor() &&
  5576. "only special members have implicit exception specs");
  5577. Sema::InheritedConstructorInfo ICI(
  5578. S, Loc, CD->getInheritedConstructor().getShadowDecl());
  5579. return ComputeDefaultedSpecialMemberExceptionSpec(
  5580. S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
  5581. }
  5582. static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
  5583. CXXMethodDecl *MD) {
  5584. FunctionProtoType::ExtProtoInfo EPI;
  5585. // Build an exception specification pointing back at this member.
  5586. EPI.ExceptionSpec.Type = EST_Unevaluated;
  5587. EPI.ExceptionSpec.SourceDecl = MD;
  5588. // Set the calling convention to the default for C++ instance methods.
  5589. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
  5590. S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  5591. /*IsCXXMethod=*/true));
  5592. return EPI;
  5593. }
  5594. void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
  5595. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  5596. if (FPT->getExceptionSpecType() != EST_Unevaluated)
  5597. return;
  5598. // Evaluate the exception specification.
  5599. auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
  5600. auto ESI = IES.getExceptionSpec();
  5601. // Update the type of the special member to use it.
  5602. UpdateExceptionSpec(MD, ESI);
  5603. // A user-provided destructor can be defined outside the class. When that
  5604. // happens, be sure to update the exception specification on both
  5605. // declarations.
  5606. const FunctionProtoType *CanonicalFPT =
  5607. MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
  5608. if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
  5609. UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
  5610. }
  5611. void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
  5612. CXXRecordDecl *RD = MD->getParent();
  5613. CXXSpecialMember CSM = getSpecialMember(MD);
  5614. assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
  5615. "not an explicitly-defaulted special member");
  5616. // Whether this was the first-declared instance of the constructor.
  5617. // This affects whether we implicitly add an exception spec and constexpr.
  5618. bool First = MD == MD->getCanonicalDecl();
  5619. bool HadError = false;
  5620. // C++11 [dcl.fct.def.default]p1:
  5621. // A function that is explicitly defaulted shall
  5622. // -- be a special member function (checked elsewhere),
  5623. // -- have the same type (except for ref-qualifiers, and except that a
  5624. // copy operation can take a non-const reference) as an implicit
  5625. // declaration, and
  5626. // -- not have default arguments.
  5627. // C++2a changes the second bullet to instead delete the function if it's
  5628. // defaulted on its first declaration, unless it's "an assignment operator,
  5629. // and its return type differs or its parameter type is not a reference".
  5630. bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
  5631. bool ShouldDeleteForTypeMismatch = false;
  5632. unsigned ExpectedParams = 1;
  5633. if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
  5634. ExpectedParams = 0;
  5635. if (MD->getNumParams() != ExpectedParams) {
  5636. // This checks for default arguments: a copy or move constructor with a
  5637. // default argument is classified as a default constructor, and assignment
  5638. // operations and destructors can't have default arguments.
  5639. Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
  5640. << CSM << MD->getSourceRange();
  5641. HadError = true;
  5642. } else if (MD->isVariadic()) {
  5643. if (DeleteOnTypeMismatch)
  5644. ShouldDeleteForTypeMismatch = true;
  5645. else {
  5646. Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
  5647. << CSM << MD->getSourceRange();
  5648. HadError = true;
  5649. }
  5650. }
  5651. const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
  5652. bool CanHaveConstParam = false;
  5653. if (CSM == CXXCopyConstructor)
  5654. CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
  5655. else if (CSM == CXXCopyAssignment)
  5656. CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
  5657. QualType ReturnType = Context.VoidTy;
  5658. if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
  5659. // Check for return type matching.
  5660. ReturnType = Type->getReturnType();
  5661. QualType ExpectedReturnType =
  5662. Context.getLValueReferenceType(Context.getTypeDeclType(RD));
  5663. if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
  5664. Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
  5665. << (CSM == CXXMoveAssignment) << ExpectedReturnType;
  5666. HadError = true;
  5667. }
  5668. // A defaulted special member cannot have cv-qualifiers.
  5669. if (Type->getTypeQuals()) {
  5670. if (DeleteOnTypeMismatch)
  5671. ShouldDeleteForTypeMismatch = true;
  5672. else {
  5673. Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
  5674. << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
  5675. HadError = true;
  5676. }
  5677. }
  5678. }
  5679. // Check for parameter type matching.
  5680. QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
  5681. bool HasConstParam = false;
  5682. if (ExpectedParams && ArgType->isReferenceType()) {
  5683. // Argument must be reference to possibly-const T.
  5684. QualType ReferentType = ArgType->getPointeeType();
  5685. HasConstParam = ReferentType.isConstQualified();
  5686. if (ReferentType.isVolatileQualified()) {
  5687. if (DeleteOnTypeMismatch)
  5688. ShouldDeleteForTypeMismatch = true;
  5689. else {
  5690. Diag(MD->getLocation(),
  5691. diag::err_defaulted_special_member_volatile_param) << CSM;
  5692. HadError = true;
  5693. }
  5694. }
  5695. if (HasConstParam && !CanHaveConstParam) {
  5696. if (DeleteOnTypeMismatch)
  5697. ShouldDeleteForTypeMismatch = true;
  5698. else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
  5699. Diag(MD->getLocation(),
  5700. diag::err_defaulted_special_member_copy_const_param)
  5701. << (CSM == CXXCopyAssignment);
  5702. // FIXME: Explain why this special member can't be const.
  5703. HadError = true;
  5704. } else {
  5705. Diag(MD->getLocation(),
  5706. diag::err_defaulted_special_member_move_const_param)
  5707. << (CSM == CXXMoveAssignment);
  5708. HadError = true;
  5709. }
  5710. }
  5711. } else if (ExpectedParams) {
  5712. // A copy assignment operator can take its argument by value, but a
  5713. // defaulted one cannot.
  5714. assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
  5715. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
  5716. HadError = true;
  5717. }
  5718. // C++11 [dcl.fct.def.default]p2:
  5719. // An explicitly-defaulted function may be declared constexpr only if it
  5720. // would have been implicitly declared as constexpr,
  5721. // Do not apply this rule to members of class templates, since core issue 1358
  5722. // makes such functions always instantiate to constexpr functions. For
  5723. // functions which cannot be constexpr (for non-constructors in C++11 and for
  5724. // destructors in C++1y), this is checked elsewhere.
  5725. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
  5726. HasConstParam);
  5727. if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
  5728. : isa<CXXConstructorDecl>(MD)) &&
  5729. MD->isConstexpr() && !Constexpr &&
  5730. MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
  5731. Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
  5732. // FIXME: Explain why the special member can't be constexpr.
  5733. HadError = true;
  5734. }
  5735. // and may have an explicit exception-specification only if it is compatible
  5736. // with the exception-specification on the implicit declaration.
  5737. if (Type->hasExceptionSpec()) {
  5738. // Delay the check if this is the first declaration of the special member,
  5739. // since we may not have parsed some necessary in-class initializers yet.
  5740. if (First) {
  5741. // If the exception specification needs to be instantiated, do so now,
  5742. // before we clobber it with an EST_Unevaluated specification below.
  5743. if (Type->getExceptionSpecType() == EST_Uninstantiated) {
  5744. InstantiateExceptionSpec(MD->getBeginLoc(), MD);
  5745. Type = MD->getType()->getAs<FunctionProtoType>();
  5746. }
  5747. DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
  5748. } else
  5749. CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
  5750. }
  5751. // If a function is explicitly defaulted on its first declaration,
  5752. if (First) {
  5753. // -- it is implicitly considered to be constexpr if the implicit
  5754. // definition would be,
  5755. MD->setConstexpr(Constexpr);
  5756. // -- it is implicitly considered to have the same exception-specification
  5757. // as if it had been implicitly declared,
  5758. FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
  5759. EPI.ExceptionSpec.Type = EST_Unevaluated;
  5760. EPI.ExceptionSpec.SourceDecl = MD;
  5761. MD->setType(Context.getFunctionType(ReturnType,
  5762. llvm::makeArrayRef(&ArgType,
  5763. ExpectedParams),
  5764. EPI));
  5765. }
  5766. if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
  5767. if (First) {
  5768. SetDeclDeleted(MD, MD->getLocation());
  5769. if (!inTemplateInstantiation() && !HadError) {
  5770. Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
  5771. if (ShouldDeleteForTypeMismatch) {
  5772. Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
  5773. } else {
  5774. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  5775. }
  5776. }
  5777. if (ShouldDeleteForTypeMismatch && !HadError) {
  5778. Diag(MD->getLocation(),
  5779. diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
  5780. }
  5781. } else {
  5782. // C++11 [dcl.fct.def.default]p4:
  5783. // [For a] user-provided explicitly-defaulted function [...] if such a
  5784. // function is implicitly defined as deleted, the program is ill-formed.
  5785. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
  5786. assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
  5787. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  5788. HadError = true;
  5789. }
  5790. }
  5791. if (HadError)
  5792. MD->setInvalidDecl();
  5793. }
  5794. /// Check whether the exception specification provided for an
  5795. /// explicitly-defaulted special member matches the exception specification
  5796. /// that would have been generated for an implicit special member, per
  5797. /// C++11 [dcl.fct.def.default]p2.
  5798. void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
  5799. CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
  5800. // If the exception specification was explicitly specified but hadn't been
  5801. // parsed when the method was defaulted, grab it now.
  5802. if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
  5803. SpecifiedType =
  5804. MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
  5805. // Compute the implicit exception specification.
  5806. CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  5807. /*IsCXXMethod=*/true);
  5808. FunctionProtoType::ExtProtoInfo EPI(CC);
  5809. auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
  5810. EPI.ExceptionSpec = IES.getExceptionSpec();
  5811. const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
  5812. Context.getFunctionType(Context.VoidTy, None, EPI));
  5813. // Ensure that it matches.
  5814. CheckEquivalentExceptionSpec(
  5815. PDiag(diag::err_incorrect_defaulted_exception_spec)
  5816. << getSpecialMember(MD), PDiag(),
  5817. ImplicitType, SourceLocation(),
  5818. SpecifiedType, MD->getLocation());
  5819. }
  5820. void Sema::CheckDelayedMemberExceptionSpecs() {
  5821. decltype(DelayedOverridingExceptionSpecChecks) Overriding;
  5822. decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
  5823. decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted;
  5824. std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
  5825. std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
  5826. std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs);
  5827. // Perform any deferred checking of exception specifications for virtual
  5828. // destructors.
  5829. for (auto &Check : Overriding)
  5830. CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
  5831. // Perform any deferred checking of exception specifications for befriended
  5832. // special members.
  5833. for (auto &Check : Equivalent)
  5834. CheckEquivalentExceptionSpec(Check.second, Check.first);
  5835. // Check that any explicitly-defaulted methods have exception specifications
  5836. // compatible with their implicit exception specifications.
  5837. for (auto &Spec : Defaulted)
  5838. CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
  5839. }
  5840. namespace {
  5841. /// CRTP base class for visiting operations performed by a special member
  5842. /// function (or inherited constructor).
  5843. template<typename Derived>
  5844. struct SpecialMemberVisitor {
  5845. Sema &S;
  5846. CXXMethodDecl *MD;
  5847. Sema::CXXSpecialMember CSM;
  5848. Sema::InheritedConstructorInfo *ICI;
  5849. // Properties of the special member, computed for convenience.
  5850. bool IsConstructor = false, IsAssignment = false, ConstArg = false;
  5851. SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  5852. Sema::InheritedConstructorInfo *ICI)
  5853. : S(S), MD(MD), CSM(CSM), ICI(ICI) {
  5854. switch (CSM) {
  5855. case Sema::CXXDefaultConstructor:
  5856. case Sema::CXXCopyConstructor:
  5857. case Sema::CXXMoveConstructor:
  5858. IsConstructor = true;
  5859. break;
  5860. case Sema::CXXCopyAssignment:
  5861. case Sema::CXXMoveAssignment:
  5862. IsAssignment = true;
  5863. break;
  5864. case Sema::CXXDestructor:
  5865. break;
  5866. case Sema::CXXInvalid:
  5867. llvm_unreachable("invalid special member kind");
  5868. }
  5869. if (MD->getNumParams()) {
  5870. if (const ReferenceType *RT =
  5871. MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
  5872. ConstArg = RT->getPointeeType().isConstQualified();
  5873. }
  5874. }
  5875. Derived &getDerived() { return static_cast<Derived&>(*this); }
  5876. /// Is this a "move" special member?
  5877. bool isMove() const {
  5878. return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
  5879. }
  5880. /// Look up the corresponding special member in the given class.
  5881. Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
  5882. unsigned Quals, bool IsMutable) {
  5883. return lookupCallFromSpecialMember(S, Class, CSM, Quals,
  5884. ConstArg && !IsMutable);
  5885. }
  5886. /// Look up the constructor for the specified base class to see if it's
  5887. /// overridden due to this being an inherited constructor.
  5888. Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
  5889. if (!ICI)
  5890. return {};
  5891. assert(CSM == Sema::CXXDefaultConstructor);
  5892. auto *BaseCtor =
  5893. cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
  5894. if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
  5895. return MD;
  5896. return {};
  5897. }
  5898. /// A base or member subobject.
  5899. typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
  5900. /// Get the location to use for a subobject in diagnostics.
  5901. static SourceLocation getSubobjectLoc(Subobject Subobj) {
  5902. // FIXME: For an indirect virtual base, the direct base leading to
  5903. // the indirect virtual base would be a more useful choice.
  5904. if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
  5905. return B->getBaseTypeLoc();
  5906. else
  5907. return Subobj.get<FieldDecl*>()->getLocation();
  5908. }
  5909. enum BasesToVisit {
  5910. /// Visit all non-virtual (direct) bases.
  5911. VisitNonVirtualBases,
  5912. /// Visit all direct bases, virtual or not.
  5913. VisitDirectBases,
  5914. /// Visit all non-virtual bases, and all virtual bases if the class
  5915. /// is not abstract.
  5916. VisitPotentiallyConstructedBases,
  5917. /// Visit all direct or virtual bases.
  5918. VisitAllBases
  5919. };
  5920. // Visit the bases and members of the class.
  5921. bool visit(BasesToVisit Bases) {
  5922. CXXRecordDecl *RD = MD->getParent();
  5923. if (Bases == VisitPotentiallyConstructedBases)
  5924. Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
  5925. for (auto &B : RD->bases())
  5926. if ((Bases == VisitDirectBases || !B.isVirtual()) &&
  5927. getDerived().visitBase(&B))
  5928. return true;
  5929. if (Bases == VisitAllBases)
  5930. for (auto &B : RD->vbases())
  5931. if (getDerived().visitBase(&B))
  5932. return true;
  5933. for (auto *F : RD->fields())
  5934. if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
  5935. getDerived().visitField(F))
  5936. return true;
  5937. return false;
  5938. }
  5939. };
  5940. }
  5941. namespace {
  5942. struct SpecialMemberDeletionInfo
  5943. : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
  5944. bool Diagnose;
  5945. SourceLocation Loc;
  5946. bool AllFieldsAreConst;
  5947. SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
  5948. Sema::CXXSpecialMember CSM,
  5949. Sema::InheritedConstructorInfo *ICI, bool Diagnose)
  5950. : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
  5951. Loc(MD->getLocation()), AllFieldsAreConst(true) {}
  5952. bool inUnion() const { return MD->getParent()->isUnion(); }
  5953. Sema::CXXSpecialMember getEffectiveCSM() {
  5954. return ICI ? Sema::CXXInvalid : CSM;
  5955. }
  5956. bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
  5957. bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
  5958. bool shouldDeleteForBase(CXXBaseSpecifier *Base);
  5959. bool shouldDeleteForField(FieldDecl *FD);
  5960. bool shouldDeleteForAllConstMembers();
  5961. bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  5962. unsigned Quals);
  5963. bool shouldDeleteForSubobjectCall(Subobject Subobj,
  5964. Sema::SpecialMemberOverloadResult SMOR,
  5965. bool IsDtorCallInCtor);
  5966. bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
  5967. };
  5968. }
  5969. /// Is the given special member inaccessible when used on the given
  5970. /// sub-object.
  5971. bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
  5972. CXXMethodDecl *target) {
  5973. /// If we're operating on a base class, the object type is the
  5974. /// type of this special member.
  5975. QualType objectTy;
  5976. AccessSpecifier access = target->getAccess();
  5977. if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
  5978. objectTy = S.Context.getTypeDeclType(MD->getParent());
  5979. access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
  5980. // If we're operating on a field, the object type is the type of the field.
  5981. } else {
  5982. objectTy = S.Context.getTypeDeclType(target->getParent());
  5983. }
  5984. return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
  5985. }
  5986. /// Check whether we should delete a special member due to the implicit
  5987. /// definition containing a call to a special member of a subobject.
  5988. bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
  5989. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
  5990. bool IsDtorCallInCtor) {
  5991. CXXMethodDecl *Decl = SMOR.getMethod();
  5992. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  5993. int DiagKind = -1;
  5994. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
  5995. DiagKind = !Decl ? 0 : 1;
  5996. else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  5997. DiagKind = 2;
  5998. else if (!isAccessible(Subobj, Decl))
  5999. DiagKind = 3;
  6000. else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
  6001. !Decl->isTrivial()) {
  6002. // A member of a union must have a trivial corresponding special member.
  6003. // As a weird special case, a destructor call from a union's constructor
  6004. // must be accessible and non-deleted, but need not be trivial. Such a
  6005. // destructor is never actually called, but is semantically checked as
  6006. // if it were.
  6007. DiagKind = 4;
  6008. }
  6009. if (DiagKind == -1)
  6010. return false;
  6011. if (Diagnose) {
  6012. if (Field) {
  6013. S.Diag(Field->getLocation(),
  6014. diag::note_deleted_special_member_class_subobject)
  6015. << getEffectiveCSM() << MD->getParent() << /*IsField*/true
  6016. << Field << DiagKind << IsDtorCallInCtor;
  6017. } else {
  6018. CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
  6019. S.Diag(Base->getBeginLoc(),
  6020. diag::note_deleted_special_member_class_subobject)
  6021. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  6022. << Base->getType() << DiagKind << IsDtorCallInCtor;
  6023. }
  6024. if (DiagKind == 1)
  6025. S.NoteDeletedFunction(Decl);
  6026. // FIXME: Explain inaccessibility if DiagKind == 3.
  6027. }
  6028. return true;
  6029. }
  6030. /// Check whether we should delete a special member function due to having a
  6031. /// direct or virtual base class or non-static data member of class type M.
  6032. bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
  6033. CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
  6034. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  6035. bool IsMutable = Field && Field->isMutable();
  6036. // C++11 [class.ctor]p5:
  6037. // -- any direct or virtual base class, or non-static data member with no
  6038. // brace-or-equal-initializer, has class type M (or array thereof) and
  6039. // either M has no default constructor or overload resolution as applied
  6040. // to M's default constructor results in an ambiguity or in a function
  6041. // that is deleted or inaccessible
  6042. // C++11 [class.copy]p11, C++11 [class.copy]p23:
  6043. // -- a direct or virtual base class B that cannot be copied/moved because
  6044. // overload resolution, as applied to B's corresponding special member,
  6045. // results in an ambiguity or a function that is deleted or inaccessible
  6046. // from the defaulted special member
  6047. // C++11 [class.dtor]p5:
  6048. // -- any direct or virtual base class [...] has a type with a destructor
  6049. // that is deleted or inaccessible
  6050. if (!(CSM == Sema::CXXDefaultConstructor &&
  6051. Field && Field->hasInClassInitializer()) &&
  6052. shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
  6053. false))
  6054. return true;
  6055. // C++11 [class.ctor]p5, C++11 [class.copy]p11:
  6056. // -- any direct or virtual base class or non-static data member has a
  6057. // type with a destructor that is deleted or inaccessible
  6058. if (IsConstructor) {
  6059. Sema::SpecialMemberOverloadResult SMOR =
  6060. S.LookupSpecialMember(Class, Sema::CXXDestructor,
  6061. false, false, false, false, false);
  6062. if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
  6063. return true;
  6064. }
  6065. return false;
  6066. }
  6067. /// Check whether we should delete a special member function due to the class
  6068. /// having a particular direct or virtual base class.
  6069. bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
  6070. CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
  6071. // If program is correct, BaseClass cannot be null, but if it is, the error
  6072. // must be reported elsewhere.
  6073. if (!BaseClass)
  6074. return false;
  6075. // If we have an inheriting constructor, check whether we're calling an
  6076. // inherited constructor instead of a default constructor.
  6077. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  6078. if (auto *BaseCtor = SMOR.getMethod()) {
  6079. // Note that we do not check access along this path; other than that,
  6080. // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
  6081. // FIXME: Check that the base has a usable destructor! Sink this into
  6082. // shouldDeleteForClassSubobject.
  6083. if (BaseCtor->isDeleted() && Diagnose) {
  6084. S.Diag(Base->getBeginLoc(),
  6085. diag::note_deleted_special_member_class_subobject)
  6086. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  6087. << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false;
  6088. S.NoteDeletedFunction(BaseCtor);
  6089. }
  6090. return BaseCtor->isDeleted();
  6091. }
  6092. return shouldDeleteForClassSubobject(BaseClass, Base, 0);
  6093. }
  6094. /// Check whether we should delete a special member function due to the class
  6095. /// having a particular non-static data member.
  6096. bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
  6097. QualType FieldType = S.Context.getBaseElementType(FD->getType());
  6098. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  6099. if (CSM == Sema::CXXDefaultConstructor) {
  6100. // For a default constructor, all references must be initialized in-class
  6101. // and, if a union, it must have a non-const member.
  6102. if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
  6103. if (Diagnose)
  6104. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  6105. << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
  6106. return true;
  6107. }
  6108. // C++11 [class.ctor]p5: any non-variant non-static data member of
  6109. // const-qualified type (or array thereof) with no
  6110. // brace-or-equal-initializer does not have a user-provided default
  6111. // constructor.
  6112. if (!inUnion() && FieldType.isConstQualified() &&
  6113. !FD->hasInClassInitializer() &&
  6114. (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
  6115. if (Diagnose)
  6116. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  6117. << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
  6118. return true;
  6119. }
  6120. if (inUnion() && !FieldType.isConstQualified())
  6121. AllFieldsAreConst = false;
  6122. } else if (CSM == Sema::CXXCopyConstructor) {
  6123. // For a copy constructor, data members must not be of rvalue reference
  6124. // type.
  6125. if (FieldType->isRValueReferenceType()) {
  6126. if (Diagnose)
  6127. S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
  6128. << MD->getParent() << FD << FieldType;
  6129. return true;
  6130. }
  6131. } else if (IsAssignment) {
  6132. // For an assignment operator, data members must not be of reference type.
  6133. if (FieldType->isReferenceType()) {
  6134. if (Diagnose)
  6135. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  6136. << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
  6137. return true;
  6138. }
  6139. if (!FieldRecord && FieldType.isConstQualified()) {
  6140. // C++11 [class.copy]p23:
  6141. // -- a non-static data member of const non-class type (or array thereof)
  6142. if (Diagnose)
  6143. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  6144. << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
  6145. return true;
  6146. }
  6147. }
  6148. if (FieldRecord) {
  6149. // Some additional restrictions exist on the variant members.
  6150. if (!inUnion() && FieldRecord->isUnion() &&
  6151. FieldRecord->isAnonymousStructOrUnion()) {
  6152. bool AllVariantFieldsAreConst = true;
  6153. // FIXME: Handle anonymous unions declared within anonymous unions.
  6154. for (auto *UI : FieldRecord->fields()) {
  6155. QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
  6156. if (!UnionFieldType.isConstQualified())
  6157. AllVariantFieldsAreConst = false;
  6158. CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
  6159. if (UnionFieldRecord &&
  6160. shouldDeleteForClassSubobject(UnionFieldRecord, UI,
  6161. UnionFieldType.getCVRQualifiers()))
  6162. return true;
  6163. }
  6164. // At least one member in each anonymous union must be non-const
  6165. if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
  6166. !FieldRecord->field_empty()) {
  6167. if (Diagnose)
  6168. S.Diag(FieldRecord->getLocation(),
  6169. diag::note_deleted_default_ctor_all_const)
  6170. << !!ICI << MD->getParent() << /*anonymous union*/1;
  6171. return true;
  6172. }
  6173. // Don't check the implicit member of the anonymous union type.
  6174. // This is technically non-conformant, but sanity demands it.
  6175. return false;
  6176. }
  6177. if (shouldDeleteForClassSubobject(FieldRecord, FD,
  6178. FieldType.getCVRQualifiers()))
  6179. return true;
  6180. }
  6181. return false;
  6182. }
  6183. /// C++11 [class.ctor] p5:
  6184. /// A defaulted default constructor for a class X is defined as deleted if
  6185. /// X is a union and all of its variant members are of const-qualified type.
  6186. bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
  6187. // This is a silly definition, because it gives an empty union a deleted
  6188. // default constructor. Don't do that.
  6189. if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
  6190. bool AnyFields = false;
  6191. for (auto *F : MD->getParent()->fields())
  6192. if ((AnyFields = !F->isUnnamedBitfield()))
  6193. break;
  6194. if (!AnyFields)
  6195. return false;
  6196. if (Diagnose)
  6197. S.Diag(MD->getParent()->getLocation(),
  6198. diag::note_deleted_default_ctor_all_const)
  6199. << !!ICI << MD->getParent() << /*not anonymous union*/0;
  6200. return true;
  6201. }
  6202. return false;
  6203. }
  6204. /// Determine whether a defaulted special member function should be defined as
  6205. /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
  6206. /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
  6207. bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
  6208. InheritedConstructorInfo *ICI,
  6209. bool Diagnose) {
  6210. if (MD->isInvalidDecl())
  6211. return false;
  6212. CXXRecordDecl *RD = MD->getParent();
  6213. assert(!RD->isDependentType() && "do deletion after instantiation");
  6214. if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
  6215. return false;
  6216. // C++11 [expr.lambda.prim]p19:
  6217. // The closure type associated with a lambda-expression has a
  6218. // deleted (8.4.3) default constructor and a deleted copy
  6219. // assignment operator.
  6220. // C++2a adds back these operators if the lambda has no capture-default.
  6221. if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
  6222. (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
  6223. if (Diagnose)
  6224. Diag(RD->getLocation(), diag::note_lambda_decl);
  6225. return true;
  6226. }
  6227. // For an anonymous struct or union, the copy and assignment special members
  6228. // will never be used, so skip the check. For an anonymous union declared at
  6229. // namespace scope, the constructor and destructor are used.
  6230. if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
  6231. RD->isAnonymousStructOrUnion())
  6232. return false;
  6233. // C++11 [class.copy]p7, p18:
  6234. // If the class definition declares a move constructor or move assignment
  6235. // operator, an implicitly declared copy constructor or copy assignment
  6236. // operator is defined as deleted.
  6237. if (MD->isImplicit() &&
  6238. (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
  6239. CXXMethodDecl *UserDeclaredMove = nullptr;
  6240. // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
  6241. // deletion of the corresponding copy operation, not both copy operations.
  6242. // MSVC 2015 has adopted the standards conforming behavior.
  6243. bool DeletesOnlyMatchingCopy =
  6244. getLangOpts().MSVCCompat &&
  6245. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
  6246. if (RD->hasUserDeclaredMoveConstructor() &&
  6247. (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
  6248. if (!Diagnose) return true;
  6249. // Find any user-declared move constructor.
  6250. for (auto *I : RD->ctors()) {
  6251. if (I->isMoveConstructor()) {
  6252. UserDeclaredMove = I;
  6253. break;
  6254. }
  6255. }
  6256. assert(UserDeclaredMove);
  6257. } else if (RD->hasUserDeclaredMoveAssignment() &&
  6258. (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
  6259. if (!Diagnose) return true;
  6260. // Find any user-declared move assignment operator.
  6261. for (auto *I : RD->methods()) {
  6262. if (I->isMoveAssignmentOperator()) {
  6263. UserDeclaredMove = I;
  6264. break;
  6265. }
  6266. }
  6267. assert(UserDeclaredMove);
  6268. }
  6269. if (UserDeclaredMove) {
  6270. Diag(UserDeclaredMove->getLocation(),
  6271. diag::note_deleted_copy_user_declared_move)
  6272. << (CSM == CXXCopyAssignment) << RD
  6273. << UserDeclaredMove->isMoveAssignmentOperator();
  6274. return true;
  6275. }
  6276. }
  6277. // Do access control from the special member function
  6278. ContextRAII MethodContext(*this, MD);
  6279. // C++11 [class.dtor]p5:
  6280. // -- for a virtual destructor, lookup of the non-array deallocation function
  6281. // results in an ambiguity or in a function that is deleted or inaccessible
  6282. if (CSM == CXXDestructor && MD->isVirtual()) {
  6283. FunctionDecl *OperatorDelete = nullptr;
  6284. DeclarationName Name =
  6285. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  6286. if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
  6287. OperatorDelete, /*Diagnose*/false)) {
  6288. if (Diagnose)
  6289. Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
  6290. return true;
  6291. }
  6292. }
  6293. SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
  6294. // Per DR1611, do not consider virtual bases of constructors of abstract
  6295. // classes, since we are not going to construct them.
  6296. // Per DR1658, do not consider virtual bases of destructors of abstract
  6297. // classes either.
  6298. // Per DR2180, for assignment operators we only assign (and thus only
  6299. // consider) direct bases.
  6300. if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
  6301. : SMI.VisitPotentiallyConstructedBases))
  6302. return true;
  6303. if (SMI.shouldDeleteForAllConstMembers())
  6304. return true;
  6305. if (getLangOpts().CUDA) {
  6306. // We should delete the special member in CUDA mode if target inference
  6307. // failed.
  6308. // For inherited constructors (non-null ICI), CSM may be passed so that MD
  6309. // is treated as certain special member, which may not reflect what special
  6310. // member MD really is. However inferCUDATargetForImplicitSpecialMember
  6311. // expects CSM to match MD, therefore recalculate CSM.
  6312. assert(ICI || CSM == getSpecialMember(MD));
  6313. auto RealCSM = CSM;
  6314. if (ICI)
  6315. RealCSM = getSpecialMember(MD);
  6316. return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
  6317. SMI.ConstArg, Diagnose);
  6318. }
  6319. return false;
  6320. }
  6321. /// Perform lookup for a special member of the specified kind, and determine
  6322. /// whether it is trivial. If the triviality can be determined without the
  6323. /// lookup, skip it. This is intended for use when determining whether a
  6324. /// special member of a containing object is trivial, and thus does not ever
  6325. /// perform overload resolution for default constructors.
  6326. ///
  6327. /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
  6328. /// member that was most likely to be intended to be trivial, if any.
  6329. ///
  6330. /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
  6331. /// determine whether the special member is trivial.
  6332. static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
  6333. Sema::CXXSpecialMember CSM, unsigned Quals,
  6334. bool ConstRHS,
  6335. Sema::TrivialABIHandling TAH,
  6336. CXXMethodDecl **Selected) {
  6337. if (Selected)
  6338. *Selected = nullptr;
  6339. switch (CSM) {
  6340. case Sema::CXXInvalid:
  6341. llvm_unreachable("not a special member");
  6342. case Sema::CXXDefaultConstructor:
  6343. // C++11 [class.ctor]p5:
  6344. // A default constructor is trivial if:
  6345. // - all the [direct subobjects] have trivial default constructors
  6346. //
  6347. // Note, no overload resolution is performed in this case.
  6348. if (RD->hasTrivialDefaultConstructor())
  6349. return true;
  6350. if (Selected) {
  6351. // If there's a default constructor which could have been trivial, dig it
  6352. // out. Otherwise, if there's any user-provided default constructor, point
  6353. // to that as an example of why there's not a trivial one.
  6354. CXXConstructorDecl *DefCtor = nullptr;
  6355. if (RD->needsImplicitDefaultConstructor())
  6356. S.DeclareImplicitDefaultConstructor(RD);
  6357. for (auto *CI : RD->ctors()) {
  6358. if (!CI->isDefaultConstructor())
  6359. continue;
  6360. DefCtor = CI;
  6361. if (!DefCtor->isUserProvided())
  6362. break;
  6363. }
  6364. *Selected = DefCtor;
  6365. }
  6366. return false;
  6367. case Sema::CXXDestructor:
  6368. // C++11 [class.dtor]p5:
  6369. // A destructor is trivial if:
  6370. // - all the direct [subobjects] have trivial destructors
  6371. if (RD->hasTrivialDestructor() ||
  6372. (TAH == Sema::TAH_ConsiderTrivialABI &&
  6373. RD->hasTrivialDestructorForCall()))
  6374. return true;
  6375. if (Selected) {
  6376. if (RD->needsImplicitDestructor())
  6377. S.DeclareImplicitDestructor(RD);
  6378. *Selected = RD->getDestructor();
  6379. }
  6380. return false;
  6381. case Sema::CXXCopyConstructor:
  6382. // C++11 [class.copy]p12:
  6383. // A copy constructor is trivial if:
  6384. // - the constructor selected to copy each direct [subobject] is trivial
  6385. if (RD->hasTrivialCopyConstructor() ||
  6386. (TAH == Sema::TAH_ConsiderTrivialABI &&
  6387. RD->hasTrivialCopyConstructorForCall())) {
  6388. if (Quals == Qualifiers::Const)
  6389. // We must either select the trivial copy constructor or reach an
  6390. // ambiguity; no need to actually perform overload resolution.
  6391. return true;
  6392. } else if (!Selected) {
  6393. return false;
  6394. }
  6395. // In C++98, we are not supposed to perform overload resolution here, but we
  6396. // treat that as a language defect, as suggested on cxx-abi-dev, to treat
  6397. // cases like B as having a non-trivial copy constructor:
  6398. // struct A { template<typename T> A(T&); };
  6399. // struct B { mutable A a; };
  6400. goto NeedOverloadResolution;
  6401. case Sema::CXXCopyAssignment:
  6402. // C++11 [class.copy]p25:
  6403. // A copy assignment operator is trivial if:
  6404. // - the assignment operator selected to copy each direct [subobject] is
  6405. // trivial
  6406. if (RD->hasTrivialCopyAssignment()) {
  6407. if (Quals == Qualifiers::Const)
  6408. return true;
  6409. } else if (!Selected) {
  6410. return false;
  6411. }
  6412. // In C++98, we are not supposed to perform overload resolution here, but we
  6413. // treat that as a language defect.
  6414. goto NeedOverloadResolution;
  6415. case Sema::CXXMoveConstructor:
  6416. case Sema::CXXMoveAssignment:
  6417. NeedOverloadResolution:
  6418. Sema::SpecialMemberOverloadResult SMOR =
  6419. lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
  6420. // The standard doesn't describe how to behave if the lookup is ambiguous.
  6421. // We treat it as not making the member non-trivial, just like the standard
  6422. // mandates for the default constructor. This should rarely matter, because
  6423. // the member will also be deleted.
  6424. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  6425. return true;
  6426. if (!SMOR.getMethod()) {
  6427. assert(SMOR.getKind() ==
  6428. Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
  6429. return false;
  6430. }
  6431. // We deliberately don't check if we found a deleted special member. We're
  6432. // not supposed to!
  6433. if (Selected)
  6434. *Selected = SMOR.getMethod();
  6435. if (TAH == Sema::TAH_ConsiderTrivialABI &&
  6436. (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
  6437. return SMOR.getMethod()->isTrivialForCall();
  6438. return SMOR.getMethod()->isTrivial();
  6439. }
  6440. llvm_unreachable("unknown special method kind");
  6441. }
  6442. static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
  6443. for (auto *CI : RD->ctors())
  6444. if (!CI->isImplicit())
  6445. return CI;
  6446. // Look for constructor templates.
  6447. typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
  6448. for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
  6449. if (CXXConstructorDecl *CD =
  6450. dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
  6451. return CD;
  6452. }
  6453. return nullptr;
  6454. }
  6455. /// The kind of subobject we are checking for triviality. The values of this
  6456. /// enumeration are used in diagnostics.
  6457. enum TrivialSubobjectKind {
  6458. /// The subobject is a base class.
  6459. TSK_BaseClass,
  6460. /// The subobject is a non-static data member.
  6461. TSK_Field,
  6462. /// The object is actually the complete object.
  6463. TSK_CompleteObject
  6464. };
  6465. /// Check whether the special member selected for a given type would be trivial.
  6466. static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
  6467. QualType SubType, bool ConstRHS,
  6468. Sema::CXXSpecialMember CSM,
  6469. TrivialSubobjectKind Kind,
  6470. Sema::TrivialABIHandling TAH, bool Diagnose) {
  6471. CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
  6472. if (!SubRD)
  6473. return true;
  6474. CXXMethodDecl *Selected;
  6475. if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
  6476. ConstRHS, TAH, Diagnose ? &Selected : nullptr))
  6477. return true;
  6478. if (Diagnose) {
  6479. if (ConstRHS)
  6480. SubType.addConst();
  6481. if (!Selected && CSM == Sema::CXXDefaultConstructor) {
  6482. S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
  6483. << Kind << SubType.getUnqualifiedType();
  6484. if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
  6485. S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
  6486. } else if (!Selected)
  6487. S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
  6488. << Kind << SubType.getUnqualifiedType() << CSM << SubType;
  6489. else if (Selected->isUserProvided()) {
  6490. if (Kind == TSK_CompleteObject)
  6491. S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
  6492. << Kind << SubType.getUnqualifiedType() << CSM;
  6493. else {
  6494. S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
  6495. << Kind << SubType.getUnqualifiedType() << CSM;
  6496. S.Diag(Selected->getLocation(), diag::note_declared_at);
  6497. }
  6498. } else {
  6499. if (Kind != TSK_CompleteObject)
  6500. S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
  6501. << Kind << SubType.getUnqualifiedType() << CSM;
  6502. // Explain why the defaulted or deleted special member isn't trivial.
  6503. S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
  6504. Diagnose);
  6505. }
  6506. }
  6507. return false;
  6508. }
  6509. /// Check whether the members of a class type allow a special member to be
  6510. /// trivial.
  6511. static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
  6512. Sema::CXXSpecialMember CSM,
  6513. bool ConstArg,
  6514. Sema::TrivialABIHandling TAH,
  6515. bool Diagnose) {
  6516. for (const auto *FI : RD->fields()) {
  6517. if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
  6518. continue;
  6519. QualType FieldType = S.Context.getBaseElementType(FI->getType());
  6520. // Pretend anonymous struct or union members are members of this class.
  6521. if (FI->isAnonymousStructOrUnion()) {
  6522. if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
  6523. CSM, ConstArg, TAH, Diagnose))
  6524. return false;
  6525. continue;
  6526. }
  6527. // C++11 [class.ctor]p5:
  6528. // A default constructor is trivial if [...]
  6529. // -- no non-static data member of its class has a
  6530. // brace-or-equal-initializer
  6531. if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
  6532. if (Diagnose)
  6533. S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
  6534. return false;
  6535. }
  6536. // Objective C ARC 4.3.5:
  6537. // [...] nontrivally ownership-qualified types are [...] not trivially
  6538. // default constructible, copy constructible, move constructible, copy
  6539. // assignable, move assignable, or destructible [...]
  6540. if (FieldType.hasNonTrivialObjCLifetime()) {
  6541. if (Diagnose)
  6542. S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
  6543. << RD << FieldType.getObjCLifetime();
  6544. return false;
  6545. }
  6546. bool ConstRHS = ConstArg && !FI->isMutable();
  6547. if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
  6548. CSM, TSK_Field, TAH, Diagnose))
  6549. return false;
  6550. }
  6551. return true;
  6552. }
  6553. /// Diagnose why the specified class does not have a trivial special member of
  6554. /// the given kind.
  6555. void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
  6556. QualType Ty = Context.getRecordType(RD);
  6557. bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
  6558. checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
  6559. TSK_CompleteObject, TAH_IgnoreTrivialABI,
  6560. /*Diagnose*/true);
  6561. }
  6562. /// Determine whether a defaulted or deleted special member function is trivial,
  6563. /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
  6564. /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
  6565. bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
  6566. TrivialABIHandling TAH, bool Diagnose) {
  6567. assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
  6568. CXXRecordDecl *RD = MD->getParent();
  6569. bool ConstArg = false;
  6570. // C++11 [class.copy]p12, p25: [DR1593]
  6571. // A [special member] is trivial if [...] its parameter-type-list is
  6572. // equivalent to the parameter-type-list of an implicit declaration [...]
  6573. switch (CSM) {
  6574. case CXXDefaultConstructor:
  6575. case CXXDestructor:
  6576. // Trivial default constructors and destructors cannot have parameters.
  6577. break;
  6578. case CXXCopyConstructor:
  6579. case CXXCopyAssignment: {
  6580. // Trivial copy operations always have const, non-volatile parameter types.
  6581. ConstArg = true;
  6582. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6583. const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
  6584. if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
  6585. if (Diagnose)
  6586. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6587. << Param0->getSourceRange() << Param0->getType()
  6588. << Context.getLValueReferenceType(
  6589. Context.getRecordType(RD).withConst());
  6590. return false;
  6591. }
  6592. break;
  6593. }
  6594. case CXXMoveConstructor:
  6595. case CXXMoveAssignment: {
  6596. // Trivial move operations always have non-cv-qualified parameters.
  6597. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6598. const RValueReferenceType *RT =
  6599. Param0->getType()->getAs<RValueReferenceType>();
  6600. if (!RT || RT->getPointeeType().getCVRQualifiers()) {
  6601. if (Diagnose)
  6602. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6603. << Param0->getSourceRange() << Param0->getType()
  6604. << Context.getRValueReferenceType(Context.getRecordType(RD));
  6605. return false;
  6606. }
  6607. break;
  6608. }
  6609. case CXXInvalid:
  6610. llvm_unreachable("not a special member");
  6611. }
  6612. if (MD->getMinRequiredArguments() < MD->getNumParams()) {
  6613. if (Diagnose)
  6614. Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
  6615. diag::note_nontrivial_default_arg)
  6616. << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
  6617. return false;
  6618. }
  6619. if (MD->isVariadic()) {
  6620. if (Diagnose)
  6621. Diag(MD->getLocation(), diag::note_nontrivial_variadic);
  6622. return false;
  6623. }
  6624. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6625. // A copy/move [constructor or assignment operator] is trivial if
  6626. // -- the [member] selected to copy/move each direct base class subobject
  6627. // is trivial
  6628. //
  6629. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6630. // A [default constructor or destructor] is trivial if
  6631. // -- all the direct base classes have trivial [default constructors or
  6632. // destructors]
  6633. for (const auto &BI : RD->bases())
  6634. if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
  6635. ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
  6636. return false;
  6637. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6638. // A copy/move [constructor or assignment operator] for a class X is
  6639. // trivial if
  6640. // -- for each non-static data member of X that is of class type (or array
  6641. // thereof), the constructor selected to copy/move that member is
  6642. // trivial
  6643. //
  6644. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6645. // A [default constructor or destructor] is trivial if
  6646. // -- for all of the non-static data members of its class that are of class
  6647. // type (or array thereof), each such class has a trivial [default
  6648. // constructor or destructor]
  6649. if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
  6650. return false;
  6651. // C++11 [class.dtor]p5:
  6652. // A destructor is trivial if [...]
  6653. // -- the destructor is not virtual
  6654. if (CSM == CXXDestructor && MD->isVirtual()) {
  6655. if (Diagnose)
  6656. Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
  6657. return false;
  6658. }
  6659. // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
  6660. // A [special member] for class X is trivial if [...]
  6661. // -- class X has no virtual functions and no virtual base classes
  6662. if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
  6663. if (!Diagnose)
  6664. return false;
  6665. if (RD->getNumVBases()) {
  6666. // Check for virtual bases. We already know that the corresponding
  6667. // member in all bases is trivial, so vbases must all be direct.
  6668. CXXBaseSpecifier &BS = *RD->vbases_begin();
  6669. assert(BS.isVirtual());
  6670. Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
  6671. return false;
  6672. }
  6673. // Must have a virtual method.
  6674. for (const auto *MI : RD->methods()) {
  6675. if (MI->isVirtual()) {
  6676. SourceLocation MLoc = MI->getBeginLoc();
  6677. Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
  6678. return false;
  6679. }
  6680. }
  6681. llvm_unreachable("dynamic class with no vbases and no virtual functions");
  6682. }
  6683. // Looks like it's trivial!
  6684. return true;
  6685. }
  6686. namespace {
  6687. struct FindHiddenVirtualMethod {
  6688. Sema *S;
  6689. CXXMethodDecl *Method;
  6690. llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
  6691. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  6692. private:
  6693. /// Check whether any most overriden method from MD in Methods
  6694. static bool CheckMostOverridenMethods(
  6695. const CXXMethodDecl *MD,
  6696. const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
  6697. if (MD->size_overridden_methods() == 0)
  6698. return Methods.count(MD->getCanonicalDecl());
  6699. for (const CXXMethodDecl *O : MD->overridden_methods())
  6700. if (CheckMostOverridenMethods(O, Methods))
  6701. return true;
  6702. return false;
  6703. }
  6704. public:
  6705. /// Member lookup function that determines whether a given C++
  6706. /// method overloads virtual methods in a base class without overriding any,
  6707. /// to be used with CXXRecordDecl::lookupInBases().
  6708. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6709. RecordDecl *BaseRecord =
  6710. Specifier->getType()->getAs<RecordType>()->getDecl();
  6711. DeclarationName Name = Method->getDeclName();
  6712. assert(Name.getNameKind() == DeclarationName::Identifier);
  6713. bool foundSameNameMethod = false;
  6714. SmallVector<CXXMethodDecl *, 8> overloadedMethods;
  6715. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6716. Path.Decls = Path.Decls.slice(1)) {
  6717. NamedDecl *D = Path.Decls.front();
  6718. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6719. MD = MD->getCanonicalDecl();
  6720. foundSameNameMethod = true;
  6721. // Interested only in hidden virtual methods.
  6722. if (!MD->isVirtual())
  6723. continue;
  6724. // If the method we are checking overrides a method from its base
  6725. // don't warn about the other overloaded methods. Clang deviates from
  6726. // GCC by only diagnosing overloads of inherited virtual functions that
  6727. // do not override any other virtual functions in the base. GCC's
  6728. // -Woverloaded-virtual diagnoses any derived function hiding a virtual
  6729. // function from a base class. These cases may be better served by a
  6730. // warning (not specific to virtual functions) on call sites when the
  6731. // call would select a different function from the base class, were it
  6732. // visible.
  6733. // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
  6734. if (!S->IsOverload(Method, MD, false))
  6735. return true;
  6736. // Collect the overload only if its hidden.
  6737. if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
  6738. overloadedMethods.push_back(MD);
  6739. }
  6740. }
  6741. if (foundSameNameMethod)
  6742. OverloadedMethods.append(overloadedMethods.begin(),
  6743. overloadedMethods.end());
  6744. return foundSameNameMethod;
  6745. }
  6746. };
  6747. } // end anonymous namespace
  6748. /// Add the most overriden methods from MD to Methods
  6749. static void AddMostOverridenMethods(const CXXMethodDecl *MD,
  6750. llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
  6751. if (MD->size_overridden_methods() == 0)
  6752. Methods.insert(MD->getCanonicalDecl());
  6753. else
  6754. for (const CXXMethodDecl *O : MD->overridden_methods())
  6755. AddMostOverridenMethods(O, Methods);
  6756. }
  6757. /// Check if a method overloads virtual methods in a base class without
  6758. /// overriding any.
  6759. void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
  6760. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  6761. if (!MD->getDeclName().isIdentifier())
  6762. return;
  6763. CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
  6764. /*bool RecordPaths=*/false,
  6765. /*bool DetectVirtual=*/false);
  6766. FindHiddenVirtualMethod FHVM;
  6767. FHVM.Method = MD;
  6768. FHVM.S = this;
  6769. // Keep the base methods that were overriden or introduced in the subclass
  6770. // by 'using' in a set. A base method not in this set is hidden.
  6771. CXXRecordDecl *DC = MD->getParent();
  6772. DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
  6773. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
  6774. NamedDecl *ND = *I;
  6775. if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
  6776. ND = shad->getTargetDecl();
  6777. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  6778. AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
  6779. }
  6780. if (DC->lookupInBases(FHVM, Paths))
  6781. OverloadedMethods = FHVM.OverloadedMethods;
  6782. }
  6783. void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
  6784. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  6785. for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
  6786. CXXMethodDecl *overloadedMD = OverloadedMethods[i];
  6787. PartialDiagnostic PD = PDiag(
  6788. diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
  6789. HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
  6790. Diag(overloadedMD->getLocation(), PD);
  6791. }
  6792. }
  6793. /// Diagnose methods which overload virtual methods in a base class
  6794. /// without overriding any.
  6795. void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
  6796. if (MD->isInvalidDecl())
  6797. return;
  6798. if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
  6799. return;
  6800. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  6801. FindHiddenVirtualMethods(MD, OverloadedMethods);
  6802. if (!OverloadedMethods.empty()) {
  6803. Diag(MD->getLocation(), diag::warn_overloaded_virtual)
  6804. << MD << (OverloadedMethods.size() > 1);
  6805. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  6806. }
  6807. }
  6808. void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
  6809. auto PrintDiagAndRemoveAttr = [&]() {
  6810. // No diagnostics if this is a template instantiation.
  6811. if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
  6812. Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
  6813. diag::ext_cannot_use_trivial_abi) << &RD;
  6814. RD.dropAttr<TrivialABIAttr>();
  6815. };
  6816. // Ill-formed if the struct has virtual functions.
  6817. if (RD.isPolymorphic()) {
  6818. PrintDiagAndRemoveAttr();
  6819. return;
  6820. }
  6821. for (const auto &B : RD.bases()) {
  6822. // Ill-formed if the base class is non-trivial for the purpose of calls or a
  6823. // virtual base.
  6824. if ((!B.getType()->isDependentType() &&
  6825. !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
  6826. B.isVirtual()) {
  6827. PrintDiagAndRemoveAttr();
  6828. return;
  6829. }
  6830. }
  6831. for (const auto *FD : RD.fields()) {
  6832. // Ill-formed if the field is an ObjectiveC pointer or of a type that is
  6833. // non-trivial for the purpose of calls.
  6834. QualType FT = FD->getType();
  6835. if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
  6836. PrintDiagAndRemoveAttr();
  6837. return;
  6838. }
  6839. if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
  6840. if (!RT->isDependentType() &&
  6841. !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
  6842. PrintDiagAndRemoveAttr();
  6843. return;
  6844. }
  6845. }
  6846. }
  6847. void Sema::ActOnFinishCXXMemberSpecification(
  6848. Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
  6849. SourceLocation RBrac, const ParsedAttributesView &AttrList) {
  6850. if (!TagDecl)
  6851. return;
  6852. AdjustDeclIfTemplate(TagDecl);
  6853. for (const ParsedAttr &AL : AttrList) {
  6854. if (AL.getKind() != ParsedAttr::AT_Visibility)
  6855. continue;
  6856. AL.setInvalid();
  6857. Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
  6858. << AL.getName();
  6859. }
  6860. ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
  6861. // strict aliasing violation!
  6862. reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
  6863. FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
  6864. CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
  6865. }
  6866. /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
  6867. /// special functions, such as the default constructor, copy
  6868. /// constructor, or destructor, to the given C++ class (C++
  6869. /// [special]p1). This routine can only be executed just before the
  6870. /// definition of the class is complete.
  6871. void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
  6872. if (ClassDecl->needsImplicitDefaultConstructor()) {
  6873. ++ASTContext::NumImplicitDefaultConstructors;
  6874. if (ClassDecl->hasInheritedConstructor())
  6875. DeclareImplicitDefaultConstructor(ClassDecl);
  6876. }
  6877. if (ClassDecl->needsImplicitCopyConstructor()) {
  6878. ++ASTContext::NumImplicitCopyConstructors;
  6879. // If the properties or semantics of the copy constructor couldn't be
  6880. // determined while the class was being declared, force a declaration
  6881. // of it now.
  6882. if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
  6883. ClassDecl->hasInheritedConstructor())
  6884. DeclareImplicitCopyConstructor(ClassDecl);
  6885. // For the MS ABI we need to know whether the copy ctor is deleted. A
  6886. // prerequisite for deleting the implicit copy ctor is that the class has a
  6887. // move ctor or move assignment that is either user-declared or whose
  6888. // semantics are inherited from a subobject. FIXME: We should provide a more
  6889. // direct way for CodeGen to ask whether the constructor was deleted.
  6890. else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  6891. (ClassDecl->hasUserDeclaredMoveConstructor() ||
  6892. ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  6893. ClassDecl->hasUserDeclaredMoveAssignment() ||
  6894. ClassDecl->needsOverloadResolutionForMoveAssignment()))
  6895. DeclareImplicitCopyConstructor(ClassDecl);
  6896. }
  6897. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
  6898. ++ASTContext::NumImplicitMoveConstructors;
  6899. if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  6900. ClassDecl->hasInheritedConstructor())
  6901. DeclareImplicitMoveConstructor(ClassDecl);
  6902. }
  6903. if (ClassDecl->needsImplicitCopyAssignment()) {
  6904. ++ASTContext::NumImplicitCopyAssignmentOperators;
  6905. // If we have a dynamic class, then the copy assignment operator may be
  6906. // virtual, so we have to declare it immediately. This ensures that, e.g.,
  6907. // it shows up in the right place in the vtable and that we diagnose
  6908. // problems with the implicit exception specification.
  6909. if (ClassDecl->isDynamicClass() ||
  6910. ClassDecl->needsOverloadResolutionForCopyAssignment() ||
  6911. ClassDecl->hasInheritedAssignment())
  6912. DeclareImplicitCopyAssignment(ClassDecl);
  6913. }
  6914. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
  6915. ++ASTContext::NumImplicitMoveAssignmentOperators;
  6916. // Likewise for the move assignment operator.
  6917. if (ClassDecl->isDynamicClass() ||
  6918. ClassDecl->needsOverloadResolutionForMoveAssignment() ||
  6919. ClassDecl->hasInheritedAssignment())
  6920. DeclareImplicitMoveAssignment(ClassDecl);
  6921. }
  6922. if (ClassDecl->needsImplicitDestructor()) {
  6923. ++ASTContext::NumImplicitDestructors;
  6924. // If we have a dynamic class, then the destructor may be virtual, so we
  6925. // have to declare the destructor immediately. This ensures that, e.g., it
  6926. // shows up in the right place in the vtable and that we diagnose problems
  6927. // with the implicit exception specification.
  6928. if (ClassDecl->isDynamicClass() ||
  6929. ClassDecl->needsOverloadResolutionForDestructor())
  6930. DeclareImplicitDestructor(ClassDecl);
  6931. }
  6932. }
  6933. unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
  6934. if (!D)
  6935. return 0;
  6936. // The order of template parameters is not important here. All names
  6937. // get added to the same scope.
  6938. SmallVector<TemplateParameterList *, 4> ParameterLists;
  6939. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  6940. D = TD->getTemplatedDecl();
  6941. if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
  6942. ParameterLists.push_back(PSD->getTemplateParameters());
  6943. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  6944. for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
  6945. ParameterLists.push_back(DD->getTemplateParameterList(i));
  6946. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  6947. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  6948. ParameterLists.push_back(FTD->getTemplateParameters());
  6949. }
  6950. }
  6951. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  6952. for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
  6953. ParameterLists.push_back(TD->getTemplateParameterList(i));
  6954. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
  6955. if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
  6956. ParameterLists.push_back(CTD->getTemplateParameters());
  6957. }
  6958. }
  6959. unsigned Count = 0;
  6960. for (TemplateParameterList *Params : ParameterLists) {
  6961. if (Params->size() > 0)
  6962. // Ignore explicit specializations; they don't contribute to the template
  6963. // depth.
  6964. ++Count;
  6965. for (NamedDecl *Param : *Params) {
  6966. if (Param->getDeclName()) {
  6967. S->AddDecl(Param);
  6968. IdResolver.AddDecl(Param);
  6969. }
  6970. }
  6971. }
  6972. return Count;
  6973. }
  6974. void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  6975. if (!RecordD) return;
  6976. AdjustDeclIfTemplate(RecordD);
  6977. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
  6978. PushDeclContext(S, Record);
  6979. }
  6980. void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  6981. if (!RecordD) return;
  6982. PopDeclContext();
  6983. }
  6984. /// This is used to implement the constant expression evaluation part of the
  6985. /// attribute enable_if extension. There is nothing in standard C++ which would
  6986. /// require reentering parameters.
  6987. void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
  6988. if (!Param)
  6989. return;
  6990. S->AddDecl(Param);
  6991. if (Param->getDeclName())
  6992. IdResolver.AddDecl(Param);
  6993. }
  6994. /// ActOnStartDelayedCXXMethodDeclaration - We have completed
  6995. /// parsing a top-level (non-nested) C++ class, and we are now
  6996. /// parsing those parts of the given Method declaration that could
  6997. /// not be parsed earlier (C++ [class.mem]p2), such as default
  6998. /// arguments. This action should enter the scope of the given
  6999. /// Method declaration as if we had just parsed the qualified method
  7000. /// name. However, it should not bring the parameters into scope;
  7001. /// that will be performed by ActOnDelayedCXXMethodParameter.
  7002. void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  7003. }
  7004. /// ActOnDelayedCXXMethodParameter - We've already started a delayed
  7005. /// C++ method declaration. We're (re-)introducing the given
  7006. /// function parameter into scope for use in parsing later parts of
  7007. /// the method declaration. For example, we could see an
  7008. /// ActOnParamDefaultArgument event for this parameter.
  7009. void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
  7010. if (!ParamD)
  7011. return;
  7012. ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
  7013. // If this parameter has an unparsed default argument, clear it out
  7014. // to make way for the parsed default argument.
  7015. if (Param->hasUnparsedDefaultArg())
  7016. Param->setDefaultArg(nullptr);
  7017. S->AddDecl(Param);
  7018. if (Param->getDeclName())
  7019. IdResolver.AddDecl(Param);
  7020. }
  7021. /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
  7022. /// processing the delayed method declaration for Method. The method
  7023. /// declaration is now considered finished. There may be a separate
  7024. /// ActOnStartOfFunctionDef action later (not necessarily
  7025. /// immediately!) for this method, if it was also defined inside the
  7026. /// class body.
  7027. void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  7028. if (!MethodD)
  7029. return;
  7030. AdjustDeclIfTemplate(MethodD);
  7031. FunctionDecl *Method = cast<FunctionDecl>(MethodD);
  7032. // Now that we have our default arguments, check the constructor
  7033. // again. It could produce additional diagnostics or affect whether
  7034. // the class has implicitly-declared destructors, among other
  7035. // things.
  7036. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
  7037. CheckConstructor(Constructor);
  7038. // Check the default arguments, which we may have added.
  7039. if (!Method->isInvalidDecl())
  7040. CheckCXXDefaultArguments(Method);
  7041. }
  7042. /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
  7043. /// the well-formedness of the constructor declarator @p D with type @p
  7044. /// R. If there are any errors in the declarator, this routine will
  7045. /// emit diagnostics and set the invalid bit to true. In any case, the type
  7046. /// will be updated to reflect a well-formed type for the constructor and
  7047. /// returned.
  7048. QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
  7049. StorageClass &SC) {
  7050. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7051. // C++ [class.ctor]p3:
  7052. // A constructor shall not be virtual (10.3) or static (9.4). A
  7053. // constructor can be invoked for a const, volatile or const
  7054. // volatile object. A constructor shall not be declared const,
  7055. // volatile, or const volatile (9.3.2).
  7056. if (isVirtual) {
  7057. if (!D.isInvalidType())
  7058. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  7059. << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
  7060. << SourceRange(D.getIdentifierLoc());
  7061. D.setInvalidType();
  7062. }
  7063. if (SC == SC_Static) {
  7064. if (!D.isInvalidType())
  7065. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  7066. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7067. << SourceRange(D.getIdentifierLoc());
  7068. D.setInvalidType();
  7069. SC = SC_None;
  7070. }
  7071. if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  7072. diagnoseIgnoredQualifiers(
  7073. diag::err_constructor_return_type, TypeQuals, SourceLocation(),
  7074. D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
  7075. D.getDeclSpec().getRestrictSpecLoc(),
  7076. D.getDeclSpec().getAtomicSpecLoc());
  7077. D.setInvalidType();
  7078. }
  7079. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7080. if (FTI.TypeQuals != 0) {
  7081. if (FTI.TypeQuals & Qualifiers::Const)
  7082. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  7083. << "const" << SourceRange(D.getIdentifierLoc());
  7084. if (FTI.TypeQuals & Qualifiers::Volatile)
  7085. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  7086. << "volatile" << SourceRange(D.getIdentifierLoc());
  7087. if (FTI.TypeQuals & Qualifiers::Restrict)
  7088. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  7089. << "restrict" << SourceRange(D.getIdentifierLoc());
  7090. D.setInvalidType();
  7091. }
  7092. // C++0x [class.ctor]p4:
  7093. // A constructor shall not be declared with a ref-qualifier.
  7094. if (FTI.hasRefQualifier()) {
  7095. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
  7096. << FTI.RefQualifierIsLValueRef
  7097. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  7098. D.setInvalidType();
  7099. }
  7100. // Rebuild the function type "R" without any type qualifiers (in
  7101. // case any of the errors above fired) and with "void" as the
  7102. // return type, since constructors don't have return types.
  7103. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7104. if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
  7105. return R;
  7106. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  7107. EPI.TypeQuals = 0;
  7108. EPI.RefQualifier = RQ_None;
  7109. return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
  7110. }
  7111. /// CheckConstructor - Checks a fully-formed constructor for
  7112. /// well-formedness, issuing any diagnostics required. Returns true if
  7113. /// the constructor declarator is invalid.
  7114. void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
  7115. CXXRecordDecl *ClassDecl
  7116. = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
  7117. if (!ClassDecl)
  7118. return Constructor->setInvalidDecl();
  7119. // C++ [class.copy]p3:
  7120. // A declaration of a constructor for a class X is ill-formed if
  7121. // its first parameter is of type (optionally cv-qualified) X and
  7122. // either there are no other parameters or else all other
  7123. // parameters have default arguments.
  7124. if (!Constructor->isInvalidDecl() &&
  7125. ((Constructor->getNumParams() == 1) ||
  7126. (Constructor->getNumParams() > 1 &&
  7127. Constructor->getParamDecl(1)->hasDefaultArg())) &&
  7128. Constructor->getTemplateSpecializationKind()
  7129. != TSK_ImplicitInstantiation) {
  7130. QualType ParamType = Constructor->getParamDecl(0)->getType();
  7131. QualType ClassTy = Context.getTagDeclType(ClassDecl);
  7132. if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
  7133. SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
  7134. const char *ConstRef
  7135. = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
  7136. : " const &";
  7137. Diag(ParamLoc, diag::err_constructor_byvalue_arg)
  7138. << FixItHint::CreateInsertion(ParamLoc, ConstRef);
  7139. // FIXME: Rather that making the constructor invalid, we should endeavor
  7140. // to fix the type.
  7141. Constructor->setInvalidDecl();
  7142. }
  7143. }
  7144. }
  7145. /// CheckDestructor - Checks a fully-formed destructor definition for
  7146. /// well-formedness, issuing any diagnostics required. Returns true
  7147. /// on error.
  7148. bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
  7149. CXXRecordDecl *RD = Destructor->getParent();
  7150. if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
  7151. SourceLocation Loc;
  7152. if (!Destructor->isImplicit())
  7153. Loc = Destructor->getLocation();
  7154. else
  7155. Loc = RD->getLocation();
  7156. // If we have a virtual destructor, look up the deallocation function
  7157. if (FunctionDecl *OperatorDelete =
  7158. FindDeallocationFunctionForDestructor(Loc, RD)) {
  7159. Expr *ThisArg = nullptr;
  7160. // If the notional 'delete this' expression requires a non-trivial
  7161. // conversion from 'this' to the type of a destroying operator delete's
  7162. // first parameter, perform that conversion now.
  7163. if (OperatorDelete->isDestroyingOperatorDelete()) {
  7164. QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
  7165. if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
  7166. // C++ [class.dtor]p13:
  7167. // ... as if for the expression 'delete this' appearing in a
  7168. // non-virtual destructor of the destructor's class.
  7169. ContextRAII SwitchContext(*this, Destructor);
  7170. ExprResult This =
  7171. ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
  7172. assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
  7173. This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
  7174. if (This.isInvalid()) {
  7175. // FIXME: Register this as a context note so that it comes out
  7176. // in the right order.
  7177. Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
  7178. return true;
  7179. }
  7180. ThisArg = This.get();
  7181. }
  7182. }
  7183. MarkFunctionReferenced(Loc, OperatorDelete);
  7184. Destructor->setOperatorDelete(OperatorDelete, ThisArg);
  7185. }
  7186. }
  7187. return false;
  7188. }
  7189. /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
  7190. /// the well-formednes of the destructor declarator @p D with type @p
  7191. /// R. If there are any errors in the declarator, this routine will
  7192. /// emit diagnostics and set the declarator to invalid. Even if this happens,
  7193. /// will be updated to reflect a well-formed type for the destructor and
  7194. /// returned.
  7195. QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
  7196. StorageClass& SC) {
  7197. // C++ [class.dtor]p1:
  7198. // [...] A typedef-name that names a class is a class-name
  7199. // (7.1.3); however, a typedef-name that names a class shall not
  7200. // be used as the identifier in the declarator for a destructor
  7201. // declaration.
  7202. QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
  7203. if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
  7204. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  7205. << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
  7206. else if (const TemplateSpecializationType *TST =
  7207. DeclaratorType->getAs<TemplateSpecializationType>())
  7208. if (TST->isTypeAlias())
  7209. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  7210. << DeclaratorType << 1;
  7211. // C++ [class.dtor]p2:
  7212. // A destructor is used to destroy objects of its class type. A
  7213. // destructor takes no parameters, and no return type can be
  7214. // specified for it (not even void). The address of a destructor
  7215. // shall not be taken. A destructor shall not be static. A
  7216. // destructor can be invoked for a const, volatile or const
  7217. // volatile object. A destructor shall not be declared const,
  7218. // volatile or const volatile (9.3.2).
  7219. if (SC == SC_Static) {
  7220. if (!D.isInvalidType())
  7221. Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
  7222. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7223. << SourceRange(D.getIdentifierLoc())
  7224. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7225. SC = SC_None;
  7226. }
  7227. if (!D.isInvalidType()) {
  7228. // Destructors don't have return types, but the parser will
  7229. // happily parse something like:
  7230. //
  7231. // class X {
  7232. // float ~X();
  7233. // };
  7234. //
  7235. // The return type will be eliminated later.
  7236. if (D.getDeclSpec().hasTypeSpecifier())
  7237. Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
  7238. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7239. << SourceRange(D.getIdentifierLoc());
  7240. else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  7241. diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
  7242. SourceLocation(),
  7243. D.getDeclSpec().getConstSpecLoc(),
  7244. D.getDeclSpec().getVolatileSpecLoc(),
  7245. D.getDeclSpec().getRestrictSpecLoc(),
  7246. D.getDeclSpec().getAtomicSpecLoc());
  7247. D.setInvalidType();
  7248. }
  7249. }
  7250. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7251. if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
  7252. if (FTI.TypeQuals & Qualifiers::Const)
  7253. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  7254. << "const" << SourceRange(D.getIdentifierLoc());
  7255. if (FTI.TypeQuals & Qualifiers::Volatile)
  7256. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  7257. << "volatile" << SourceRange(D.getIdentifierLoc());
  7258. if (FTI.TypeQuals & Qualifiers::Restrict)
  7259. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  7260. << "restrict" << SourceRange(D.getIdentifierLoc());
  7261. D.setInvalidType();
  7262. }
  7263. // C++0x [class.dtor]p2:
  7264. // A destructor shall not be declared with a ref-qualifier.
  7265. if (FTI.hasRefQualifier()) {
  7266. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
  7267. << FTI.RefQualifierIsLValueRef
  7268. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  7269. D.setInvalidType();
  7270. }
  7271. // Make sure we don't have any parameters.
  7272. if (FTIHasNonVoidParameters(FTI)) {
  7273. Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
  7274. // Delete the parameters.
  7275. FTI.freeParams();
  7276. D.setInvalidType();
  7277. }
  7278. // Make sure the destructor isn't variadic.
  7279. if (FTI.isVariadic) {
  7280. Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
  7281. D.setInvalidType();
  7282. }
  7283. // Rebuild the function type "R" without any type qualifiers or
  7284. // parameters (in case any of the errors above fired) and with
  7285. // "void" as the return type, since destructors don't have return
  7286. // types.
  7287. if (!D.isInvalidType())
  7288. return R;
  7289. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7290. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  7291. EPI.Variadic = false;
  7292. EPI.TypeQuals = 0;
  7293. EPI.RefQualifier = RQ_None;
  7294. return Context.getFunctionType(Context.VoidTy, None, EPI);
  7295. }
  7296. static void extendLeft(SourceRange &R, SourceRange Before) {
  7297. if (Before.isInvalid())
  7298. return;
  7299. R.setBegin(Before.getBegin());
  7300. if (R.getEnd().isInvalid())
  7301. R.setEnd(Before.getEnd());
  7302. }
  7303. static void extendRight(SourceRange &R, SourceRange After) {
  7304. if (After.isInvalid())
  7305. return;
  7306. if (R.getBegin().isInvalid())
  7307. R.setBegin(After.getBegin());
  7308. R.setEnd(After.getEnd());
  7309. }
  7310. /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
  7311. /// well-formednes of the conversion function declarator @p D with
  7312. /// type @p R. If there are any errors in the declarator, this routine
  7313. /// will emit diagnostics and return true. Otherwise, it will return
  7314. /// false. Either way, the type @p R will be updated to reflect a
  7315. /// well-formed type for the conversion operator.
  7316. void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
  7317. StorageClass& SC) {
  7318. // C++ [class.conv.fct]p1:
  7319. // Neither parameter types nor return type can be specified. The
  7320. // type of a conversion function (8.3.5) is "function taking no
  7321. // parameter returning conversion-type-id."
  7322. if (SC == SC_Static) {
  7323. if (!D.isInvalidType())
  7324. Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
  7325. << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  7326. << D.getName().getSourceRange();
  7327. D.setInvalidType();
  7328. SC = SC_None;
  7329. }
  7330. TypeSourceInfo *ConvTSI = nullptr;
  7331. QualType ConvType =
  7332. GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
  7333. const DeclSpec &DS = D.getDeclSpec();
  7334. if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
  7335. // Conversion functions don't have return types, but the parser will
  7336. // happily parse something like:
  7337. //
  7338. // class X {
  7339. // float operator bool();
  7340. // };
  7341. //
  7342. // The return type will be changed later anyway.
  7343. Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
  7344. << SourceRange(DS.getTypeSpecTypeLoc())
  7345. << SourceRange(D.getIdentifierLoc());
  7346. D.setInvalidType();
  7347. } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
  7348. // It's also plausible that the user writes type qualifiers in the wrong
  7349. // place, such as:
  7350. // struct S { const operator int(); };
  7351. // FIXME: we could provide a fixit to move the qualifiers onto the
  7352. // conversion type.
  7353. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
  7354. << SourceRange(D.getIdentifierLoc()) << 0;
  7355. D.setInvalidType();
  7356. }
  7357. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  7358. // Make sure we don't have any parameters.
  7359. if (Proto->getNumParams() > 0) {
  7360. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
  7361. // Delete the parameters.
  7362. D.getFunctionTypeInfo().freeParams();
  7363. D.setInvalidType();
  7364. } else if (Proto->isVariadic()) {
  7365. Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
  7366. D.setInvalidType();
  7367. }
  7368. // Diagnose "&operator bool()" and other such nonsense. This
  7369. // is actually a gcc extension which we don't support.
  7370. if (Proto->getReturnType() != ConvType) {
  7371. bool NeedsTypedef = false;
  7372. SourceRange Before, After;
  7373. // Walk the chunks and extract information on them for our diagnostic.
  7374. bool PastFunctionChunk = false;
  7375. for (auto &Chunk : D.type_objects()) {
  7376. switch (Chunk.Kind) {
  7377. case DeclaratorChunk::Function:
  7378. if (!PastFunctionChunk) {
  7379. if (Chunk.Fun.HasTrailingReturnType) {
  7380. TypeSourceInfo *TRT = nullptr;
  7381. GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
  7382. if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
  7383. }
  7384. PastFunctionChunk = true;
  7385. break;
  7386. }
  7387. LLVM_FALLTHROUGH;
  7388. case DeclaratorChunk::Array:
  7389. NeedsTypedef = true;
  7390. extendRight(After, Chunk.getSourceRange());
  7391. break;
  7392. case DeclaratorChunk::Pointer:
  7393. case DeclaratorChunk::BlockPointer:
  7394. case DeclaratorChunk::Reference:
  7395. case DeclaratorChunk::MemberPointer:
  7396. case DeclaratorChunk::Pipe:
  7397. extendLeft(Before, Chunk.getSourceRange());
  7398. break;
  7399. case DeclaratorChunk::Paren:
  7400. extendLeft(Before, Chunk.Loc);
  7401. extendRight(After, Chunk.EndLoc);
  7402. break;
  7403. }
  7404. }
  7405. SourceLocation Loc = Before.isValid() ? Before.getBegin() :
  7406. After.isValid() ? After.getBegin() :
  7407. D.getIdentifierLoc();
  7408. auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
  7409. DB << Before << After;
  7410. if (!NeedsTypedef) {
  7411. DB << /*don't need a typedef*/0;
  7412. // If we can provide a correct fix-it hint, do so.
  7413. if (After.isInvalid() && ConvTSI) {
  7414. SourceLocation InsertLoc =
  7415. getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
  7416. DB << FixItHint::CreateInsertion(InsertLoc, " ")
  7417. << FixItHint::CreateInsertionFromRange(
  7418. InsertLoc, CharSourceRange::getTokenRange(Before))
  7419. << FixItHint::CreateRemoval(Before);
  7420. }
  7421. } else if (!Proto->getReturnType()->isDependentType()) {
  7422. DB << /*typedef*/1 << Proto->getReturnType();
  7423. } else if (getLangOpts().CPlusPlus11) {
  7424. DB << /*alias template*/2 << Proto->getReturnType();
  7425. } else {
  7426. DB << /*might not be fixable*/3;
  7427. }
  7428. // Recover by incorporating the other type chunks into the result type.
  7429. // Note, this does *not* change the name of the function. This is compatible
  7430. // with the GCC extension:
  7431. // struct S { &operator int(); } s;
  7432. // int &r = s.operator int(); // ok in GCC
  7433. // S::operator int&() {} // error in GCC, function name is 'operator int'.
  7434. ConvType = Proto->getReturnType();
  7435. }
  7436. // C++ [class.conv.fct]p4:
  7437. // The conversion-type-id shall not represent a function type nor
  7438. // an array type.
  7439. if (ConvType->isArrayType()) {
  7440. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
  7441. ConvType = Context.getPointerType(ConvType);
  7442. D.setInvalidType();
  7443. } else if (ConvType->isFunctionType()) {
  7444. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
  7445. ConvType = Context.getPointerType(ConvType);
  7446. D.setInvalidType();
  7447. }
  7448. // Rebuild the function type "R" without any parameters (in case any
  7449. // of the errors above fired) and with the conversion type as the
  7450. // return type.
  7451. if (D.isInvalidType())
  7452. R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
  7453. // C++0x explicit conversion operators.
  7454. if (DS.isExplicitSpecified())
  7455. Diag(DS.getExplicitSpecLoc(),
  7456. getLangOpts().CPlusPlus11
  7457. ? diag::warn_cxx98_compat_explicit_conversion_functions
  7458. : diag::ext_explicit_conversion_functions)
  7459. << SourceRange(DS.getExplicitSpecLoc());
  7460. }
  7461. /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
  7462. /// the declaration of the given C++ conversion function. This routine
  7463. /// is responsible for recording the conversion function in the C++
  7464. /// class, if possible.
  7465. Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
  7466. assert(Conversion && "Expected to receive a conversion function declaration");
  7467. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
  7468. // Make sure we aren't redeclaring the conversion function.
  7469. QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
  7470. // C++ [class.conv.fct]p1:
  7471. // [...] A conversion function is never used to convert a
  7472. // (possibly cv-qualified) object to the (possibly cv-qualified)
  7473. // same object type (or a reference to it), to a (possibly
  7474. // cv-qualified) base class of that type (or a reference to it),
  7475. // or to (possibly cv-qualified) void.
  7476. // FIXME: Suppress this warning if the conversion function ends up being a
  7477. // virtual function that overrides a virtual function in a base class.
  7478. QualType ClassType
  7479. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  7480. if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
  7481. ConvType = ConvTypeRef->getPointeeType();
  7482. if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
  7483. Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  7484. /* Suppress diagnostics for instantiations. */;
  7485. else if (ConvType->isRecordType()) {
  7486. ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
  7487. if (ConvType == ClassType)
  7488. Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
  7489. << ClassType;
  7490. else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
  7491. Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
  7492. << ClassType << ConvType;
  7493. } else if (ConvType->isVoidType()) {
  7494. Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
  7495. << ClassType << ConvType;
  7496. }
  7497. if (FunctionTemplateDecl *ConversionTemplate
  7498. = Conversion->getDescribedFunctionTemplate())
  7499. return ConversionTemplate;
  7500. return Conversion;
  7501. }
  7502. namespace {
  7503. /// Utility class to accumulate and print a diagnostic listing the invalid
  7504. /// specifier(s) on a declaration.
  7505. struct BadSpecifierDiagnoser {
  7506. BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
  7507. : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
  7508. ~BadSpecifierDiagnoser() {
  7509. Diagnostic << Specifiers;
  7510. }
  7511. template<typename T> void check(SourceLocation SpecLoc, T Spec) {
  7512. return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
  7513. }
  7514. void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
  7515. return check(SpecLoc,
  7516. DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
  7517. }
  7518. void check(SourceLocation SpecLoc, const char *Spec) {
  7519. if (SpecLoc.isInvalid()) return;
  7520. Diagnostic << SourceRange(SpecLoc, SpecLoc);
  7521. if (!Specifiers.empty()) Specifiers += " ";
  7522. Specifiers += Spec;
  7523. }
  7524. Sema &S;
  7525. Sema::SemaDiagnosticBuilder Diagnostic;
  7526. std::string Specifiers;
  7527. };
  7528. }
  7529. /// Check the validity of a declarator that we parsed for a deduction-guide.
  7530. /// These aren't actually declarators in the grammar, so we need to check that
  7531. /// the user didn't specify any pieces that are not part of the deduction-guide
  7532. /// grammar.
  7533. void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
  7534. StorageClass &SC) {
  7535. TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
  7536. TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
  7537. assert(GuidedTemplateDecl && "missing template decl for deduction guide");
  7538. // C++ [temp.deduct.guide]p3:
  7539. // A deduction-gide shall be declared in the same scope as the
  7540. // corresponding class template.
  7541. if (!CurContext->getRedeclContext()->Equals(
  7542. GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
  7543. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
  7544. << GuidedTemplateDecl;
  7545. Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
  7546. }
  7547. auto &DS = D.getMutableDeclSpec();
  7548. // We leave 'friend' and 'virtual' to be rejected in the normal way.
  7549. if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
  7550. DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
  7551. DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
  7552. BadSpecifierDiagnoser Diagnoser(
  7553. *this, D.getIdentifierLoc(),
  7554. diag::err_deduction_guide_invalid_specifier);
  7555. Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
  7556. DS.ClearStorageClassSpecs();
  7557. SC = SC_None;
  7558. // 'explicit' is permitted.
  7559. Diagnoser.check(DS.getInlineSpecLoc(), "inline");
  7560. Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
  7561. Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
  7562. DS.ClearConstexprSpec();
  7563. Diagnoser.check(DS.getConstSpecLoc(), "const");
  7564. Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
  7565. Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
  7566. Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
  7567. Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
  7568. DS.ClearTypeQualifiers();
  7569. Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
  7570. Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
  7571. Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
  7572. Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
  7573. DS.ClearTypeSpecType();
  7574. }
  7575. if (D.isInvalidType())
  7576. return;
  7577. // Check the declarator is simple enough.
  7578. bool FoundFunction = false;
  7579. for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
  7580. if (Chunk.Kind == DeclaratorChunk::Paren)
  7581. continue;
  7582. if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
  7583. Diag(D.getDeclSpec().getBeginLoc(),
  7584. diag::err_deduction_guide_with_complex_decl)
  7585. << D.getSourceRange();
  7586. break;
  7587. }
  7588. if (!Chunk.Fun.hasTrailingReturnType()) {
  7589. Diag(D.getName().getBeginLoc(),
  7590. diag::err_deduction_guide_no_trailing_return_type);
  7591. break;
  7592. }
  7593. // Check that the return type is written as a specialization of
  7594. // the template specified as the deduction-guide's name.
  7595. ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
  7596. TypeSourceInfo *TSI = nullptr;
  7597. QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
  7598. assert(TSI && "deduction guide has valid type but invalid return type?");
  7599. bool AcceptableReturnType = false;
  7600. bool MightInstantiateToSpecialization = false;
  7601. if (auto RetTST =
  7602. TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
  7603. TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
  7604. bool TemplateMatches =
  7605. Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
  7606. if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
  7607. AcceptableReturnType = true;
  7608. else {
  7609. // This could still instantiate to the right type, unless we know it
  7610. // names the wrong class template.
  7611. auto *TD = SpecifiedName.getAsTemplateDecl();
  7612. MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
  7613. !TemplateMatches);
  7614. }
  7615. } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
  7616. MightInstantiateToSpecialization = true;
  7617. }
  7618. if (!AcceptableReturnType) {
  7619. Diag(TSI->getTypeLoc().getBeginLoc(),
  7620. diag::err_deduction_guide_bad_trailing_return_type)
  7621. << GuidedTemplate << TSI->getType()
  7622. << MightInstantiateToSpecialization
  7623. << TSI->getTypeLoc().getSourceRange();
  7624. }
  7625. // Keep going to check that we don't have any inner declarator pieces (we
  7626. // could still have a function returning a pointer to a function).
  7627. FoundFunction = true;
  7628. }
  7629. if (D.isFunctionDefinition())
  7630. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
  7631. }
  7632. //===----------------------------------------------------------------------===//
  7633. // Namespace Handling
  7634. //===----------------------------------------------------------------------===//
  7635. /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
  7636. /// reopened.
  7637. static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
  7638. SourceLocation Loc,
  7639. IdentifierInfo *II, bool *IsInline,
  7640. NamespaceDecl *PrevNS) {
  7641. assert(*IsInline != PrevNS->isInline());
  7642. // HACK: Work around a bug in libstdc++4.6's <atomic>, where
  7643. // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
  7644. // inline namespaces, with the intention of bringing names into namespace std.
  7645. //
  7646. // We support this just well enough to get that case working; this is not
  7647. // sufficient to support reopening namespaces as inline in general.
  7648. if (*IsInline && II && II->getName().startswith("__atomic") &&
  7649. S.getSourceManager().isInSystemHeader(Loc)) {
  7650. // Mark all prior declarations of the namespace as inline.
  7651. for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
  7652. NS = NS->getPreviousDecl())
  7653. NS->setInline(*IsInline);
  7654. // Patch up the lookup table for the containing namespace. This isn't really
  7655. // correct, but it's good enough for this particular case.
  7656. for (auto *I : PrevNS->decls())
  7657. if (auto *ND = dyn_cast<NamedDecl>(I))
  7658. PrevNS->getParent()->makeDeclVisibleInContext(ND);
  7659. return;
  7660. }
  7661. if (PrevNS->isInline())
  7662. // The user probably just forgot the 'inline', so suggest that it
  7663. // be added back.
  7664. S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
  7665. << FixItHint::CreateInsertion(KeywordLoc, "inline ");
  7666. else
  7667. S.Diag(Loc, diag::err_inline_namespace_mismatch);
  7668. S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
  7669. *IsInline = PrevNS->isInline();
  7670. }
  7671. /// ActOnStartNamespaceDef - This is called at the start of a namespace
  7672. /// definition.
  7673. Decl *Sema::ActOnStartNamespaceDef(
  7674. Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
  7675. SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
  7676. const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
  7677. SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
  7678. // For anonymous namespace, take the location of the left brace.
  7679. SourceLocation Loc = II ? IdentLoc : LBrace;
  7680. bool IsInline = InlineLoc.isValid();
  7681. bool IsInvalid = false;
  7682. bool IsStd = false;
  7683. bool AddToKnown = false;
  7684. Scope *DeclRegionScope = NamespcScope->getParent();
  7685. NamespaceDecl *PrevNS = nullptr;
  7686. if (II) {
  7687. // C++ [namespace.def]p2:
  7688. // The identifier in an original-namespace-definition shall not
  7689. // have been previously defined in the declarative region in
  7690. // which the original-namespace-definition appears. The
  7691. // identifier in an original-namespace-definition is the name of
  7692. // the namespace. Subsequently in that declarative region, it is
  7693. // treated as an original-namespace-name.
  7694. //
  7695. // Since namespace names are unique in their scope, and we don't
  7696. // look through using directives, just look for any ordinary names
  7697. // as if by qualified name lookup.
  7698. LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
  7699. ForExternalRedeclaration);
  7700. LookupQualifiedName(R, CurContext->getRedeclContext());
  7701. NamedDecl *PrevDecl =
  7702. R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
  7703. PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
  7704. if (PrevNS) {
  7705. // This is an extended namespace definition.
  7706. if (IsInline != PrevNS->isInline())
  7707. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
  7708. &IsInline, PrevNS);
  7709. } else if (PrevDecl) {
  7710. // This is an invalid name redefinition.
  7711. Diag(Loc, diag::err_redefinition_different_kind)
  7712. << II;
  7713. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  7714. IsInvalid = true;
  7715. // Continue on to push Namespc as current DeclContext and return it.
  7716. } else if (II->isStr("std") &&
  7717. CurContext->getRedeclContext()->isTranslationUnit()) {
  7718. // This is the first "real" definition of the namespace "std", so update
  7719. // our cache of the "std" namespace to point at this definition.
  7720. PrevNS = getStdNamespace();
  7721. IsStd = true;
  7722. AddToKnown = !IsInline;
  7723. } else {
  7724. // We've seen this namespace for the first time.
  7725. AddToKnown = !IsInline;
  7726. }
  7727. } else {
  7728. // Anonymous namespaces.
  7729. // Determine whether the parent already has an anonymous namespace.
  7730. DeclContext *Parent = CurContext->getRedeclContext();
  7731. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  7732. PrevNS = TU->getAnonymousNamespace();
  7733. } else {
  7734. NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
  7735. PrevNS = ND->getAnonymousNamespace();
  7736. }
  7737. if (PrevNS && IsInline != PrevNS->isInline())
  7738. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
  7739. &IsInline, PrevNS);
  7740. }
  7741. NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
  7742. StartLoc, Loc, II, PrevNS);
  7743. if (IsInvalid)
  7744. Namespc->setInvalidDecl();
  7745. ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
  7746. AddPragmaAttributes(DeclRegionScope, Namespc);
  7747. // FIXME: Should we be merging attributes?
  7748. if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
  7749. PushNamespaceVisibilityAttr(Attr, Loc);
  7750. if (IsStd)
  7751. StdNamespace = Namespc;
  7752. if (AddToKnown)
  7753. KnownNamespaces[Namespc] = false;
  7754. if (II) {
  7755. PushOnScopeChains(Namespc, DeclRegionScope);
  7756. } else {
  7757. // Link the anonymous namespace into its parent.
  7758. DeclContext *Parent = CurContext->getRedeclContext();
  7759. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  7760. TU->setAnonymousNamespace(Namespc);
  7761. } else {
  7762. cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
  7763. }
  7764. CurContext->addDecl(Namespc);
  7765. // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
  7766. // behaves as if it were replaced by
  7767. // namespace unique { /* empty body */ }
  7768. // using namespace unique;
  7769. // namespace unique { namespace-body }
  7770. // where all occurrences of 'unique' in a translation unit are
  7771. // replaced by the same identifier and this identifier differs
  7772. // from all other identifiers in the entire program.
  7773. // We just create the namespace with an empty name and then add an
  7774. // implicit using declaration, just like the standard suggests.
  7775. //
  7776. // CodeGen enforces the "universally unique" aspect by giving all
  7777. // declarations semantically contained within an anonymous
  7778. // namespace internal linkage.
  7779. if (!PrevNS) {
  7780. UD = UsingDirectiveDecl::Create(Context, Parent,
  7781. /* 'using' */ LBrace,
  7782. /* 'namespace' */ SourceLocation(),
  7783. /* qualifier */ NestedNameSpecifierLoc(),
  7784. /* identifier */ SourceLocation(),
  7785. Namespc,
  7786. /* Ancestor */ Parent);
  7787. UD->setImplicit();
  7788. Parent->addDecl(UD);
  7789. }
  7790. }
  7791. ActOnDocumentableDecl(Namespc);
  7792. // Although we could have an invalid decl (i.e. the namespace name is a
  7793. // redefinition), push it as current DeclContext and try to continue parsing.
  7794. // FIXME: We should be able to push Namespc here, so that the each DeclContext
  7795. // for the namespace has the declarations that showed up in that particular
  7796. // namespace definition.
  7797. PushDeclContext(NamespcScope, Namespc);
  7798. return Namespc;
  7799. }
  7800. /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
  7801. /// is a namespace alias, returns the namespace it points to.
  7802. static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
  7803. if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
  7804. return AD->getNamespace();
  7805. return dyn_cast_or_null<NamespaceDecl>(D);
  7806. }
  7807. /// ActOnFinishNamespaceDef - This callback is called after a namespace is
  7808. /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
  7809. void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
  7810. NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
  7811. assert(Namespc && "Invalid parameter, expected NamespaceDecl");
  7812. Namespc->setRBraceLoc(RBrace);
  7813. PopDeclContext();
  7814. if (Namespc->hasAttr<VisibilityAttr>())
  7815. PopPragmaVisibility(true, RBrace);
  7816. }
  7817. CXXRecordDecl *Sema::getStdBadAlloc() const {
  7818. return cast_or_null<CXXRecordDecl>(
  7819. StdBadAlloc.get(Context.getExternalSource()));
  7820. }
  7821. EnumDecl *Sema::getStdAlignValT() const {
  7822. return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
  7823. }
  7824. NamespaceDecl *Sema::getStdNamespace() const {
  7825. return cast_or_null<NamespaceDecl>(
  7826. StdNamespace.get(Context.getExternalSource()));
  7827. }
  7828. NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
  7829. if (!StdExperimentalNamespaceCache) {
  7830. if (auto Std = getStdNamespace()) {
  7831. LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
  7832. SourceLocation(), LookupNamespaceName);
  7833. if (!LookupQualifiedName(Result, Std) ||
  7834. !(StdExperimentalNamespaceCache =
  7835. Result.getAsSingle<NamespaceDecl>()))
  7836. Result.suppressDiagnostics();
  7837. }
  7838. }
  7839. return StdExperimentalNamespaceCache;
  7840. }
  7841. namespace {
  7842. enum UnsupportedSTLSelect {
  7843. USS_InvalidMember,
  7844. USS_MissingMember,
  7845. USS_NonTrivial,
  7846. USS_Other
  7847. };
  7848. struct InvalidSTLDiagnoser {
  7849. Sema &S;
  7850. SourceLocation Loc;
  7851. QualType TyForDiags;
  7852. QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
  7853. const VarDecl *VD = nullptr) {
  7854. {
  7855. auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
  7856. << TyForDiags << ((int)Sel);
  7857. if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
  7858. assert(!Name.empty());
  7859. D << Name;
  7860. }
  7861. }
  7862. if (Sel == USS_InvalidMember) {
  7863. S.Diag(VD->getLocation(), diag::note_var_declared_here)
  7864. << VD << VD->getSourceRange();
  7865. }
  7866. return QualType();
  7867. }
  7868. };
  7869. } // namespace
  7870. QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
  7871. SourceLocation Loc) {
  7872. assert(getLangOpts().CPlusPlus &&
  7873. "Looking for comparison category type outside of C++.");
  7874. // Check if we've already successfully checked the comparison category type
  7875. // before. If so, skip checking it again.
  7876. ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
  7877. if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
  7878. return Info->getType();
  7879. // If lookup failed
  7880. if (!Info) {
  7881. std::string NameForDiags = "std::";
  7882. NameForDiags += ComparisonCategories::getCategoryString(Kind);
  7883. Diag(Loc, diag::err_implied_comparison_category_type_not_found)
  7884. << NameForDiags;
  7885. return QualType();
  7886. }
  7887. assert(Info->Kind == Kind);
  7888. assert(Info->Record);
  7889. // Update the Record decl in case we encountered a forward declaration on our
  7890. // first pass. FIXME: This is a bit of a hack.
  7891. if (Info->Record->hasDefinition())
  7892. Info->Record = Info->Record->getDefinition();
  7893. // Use an elaborated type for diagnostics which has a name containing the
  7894. // prepended 'std' namespace but not any inline namespace names.
  7895. QualType TyForDiags = [&]() {
  7896. auto *NNS =
  7897. NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
  7898. return Context.getElaboratedType(ETK_None, NNS, Info->getType());
  7899. }();
  7900. if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
  7901. return QualType();
  7902. InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
  7903. if (!Info->Record->isTriviallyCopyable())
  7904. return UnsupportedSTLError(USS_NonTrivial);
  7905. for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
  7906. CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
  7907. // Tolerate empty base classes.
  7908. if (Base->isEmpty())
  7909. continue;
  7910. // Reject STL implementations which have at least one non-empty base.
  7911. return UnsupportedSTLError();
  7912. }
  7913. // Check that the STL has implemented the types using a single integer field.
  7914. // This expectation allows better codegen for builtin operators. We require:
  7915. // (1) The class has exactly one field.
  7916. // (2) The field is an integral or enumeration type.
  7917. auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
  7918. if (std::distance(FIt, FEnd) != 1 ||
  7919. !FIt->getType()->isIntegralOrEnumerationType()) {
  7920. return UnsupportedSTLError();
  7921. }
  7922. // Build each of the require values and store them in Info.
  7923. for (ComparisonCategoryResult CCR :
  7924. ComparisonCategories::getPossibleResultsForType(Kind)) {
  7925. StringRef MemName = ComparisonCategories::getResultString(CCR);
  7926. ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
  7927. if (!ValInfo)
  7928. return UnsupportedSTLError(USS_MissingMember, MemName);
  7929. VarDecl *VD = ValInfo->VD;
  7930. assert(VD && "should not be null!");
  7931. // Attempt to diagnose reasons why the STL definition of this type
  7932. // might be foobar, including it failing to be a constant expression.
  7933. // TODO Handle more ways the lookup or result can be invalid.
  7934. if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
  7935. !VD->checkInitIsICE())
  7936. return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
  7937. // Attempt to evaluate the var decl as a constant expression and extract
  7938. // the value of its first field as a ICE. If this fails, the STL
  7939. // implementation is not supported.
  7940. if (!ValInfo->hasValidIntValue())
  7941. return UnsupportedSTLError();
  7942. MarkVariableReferenced(Loc, VD);
  7943. }
  7944. // We've successfully built the required types and expressions. Update
  7945. // the cache and return the newly cached value.
  7946. FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
  7947. return Info->getType();
  7948. }
  7949. /// Retrieve the special "std" namespace, which may require us to
  7950. /// implicitly define the namespace.
  7951. NamespaceDecl *Sema::getOrCreateStdNamespace() {
  7952. if (!StdNamespace) {
  7953. // The "std" namespace has not yet been defined, so build one implicitly.
  7954. StdNamespace = NamespaceDecl::Create(Context,
  7955. Context.getTranslationUnitDecl(),
  7956. /*Inline=*/false,
  7957. SourceLocation(), SourceLocation(),
  7958. &PP.getIdentifierTable().get("std"),
  7959. /*PrevDecl=*/nullptr);
  7960. getStdNamespace()->setImplicit(true);
  7961. }
  7962. return getStdNamespace();
  7963. }
  7964. bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
  7965. assert(getLangOpts().CPlusPlus &&
  7966. "Looking for std::initializer_list outside of C++.");
  7967. // We're looking for implicit instantiations of
  7968. // template <typename E> class std::initializer_list.
  7969. if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
  7970. return false;
  7971. ClassTemplateDecl *Template = nullptr;
  7972. const TemplateArgument *Arguments = nullptr;
  7973. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  7974. ClassTemplateSpecializationDecl *Specialization =
  7975. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  7976. if (!Specialization)
  7977. return false;
  7978. Template = Specialization->getSpecializedTemplate();
  7979. Arguments = Specialization->getTemplateArgs().data();
  7980. } else if (const TemplateSpecializationType *TST =
  7981. Ty->getAs<TemplateSpecializationType>()) {
  7982. Template = dyn_cast_or_null<ClassTemplateDecl>(
  7983. TST->getTemplateName().getAsTemplateDecl());
  7984. Arguments = TST->getArgs();
  7985. }
  7986. if (!Template)
  7987. return false;
  7988. if (!StdInitializerList) {
  7989. // Haven't recognized std::initializer_list yet, maybe this is it.
  7990. CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
  7991. if (TemplateClass->getIdentifier() !=
  7992. &PP.getIdentifierTable().get("initializer_list") ||
  7993. !getStdNamespace()->InEnclosingNamespaceSetOf(
  7994. TemplateClass->getDeclContext()))
  7995. return false;
  7996. // This is a template called std::initializer_list, but is it the right
  7997. // template?
  7998. TemplateParameterList *Params = Template->getTemplateParameters();
  7999. if (Params->getMinRequiredArguments() != 1)
  8000. return false;
  8001. if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
  8002. return false;
  8003. // It's the right template.
  8004. StdInitializerList = Template;
  8005. }
  8006. if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
  8007. return false;
  8008. // This is an instance of std::initializer_list. Find the argument type.
  8009. if (Element)
  8010. *Element = Arguments[0].getAsType();
  8011. return true;
  8012. }
  8013. static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
  8014. NamespaceDecl *Std = S.getStdNamespace();
  8015. if (!Std) {
  8016. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  8017. return nullptr;
  8018. }
  8019. LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
  8020. Loc, Sema::LookupOrdinaryName);
  8021. if (!S.LookupQualifiedName(Result, Std)) {
  8022. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  8023. return nullptr;
  8024. }
  8025. ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
  8026. if (!Template) {
  8027. Result.suppressDiagnostics();
  8028. // We found something weird. Complain about the first thing we found.
  8029. NamedDecl *Found = *Result.begin();
  8030. S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
  8031. return nullptr;
  8032. }
  8033. // We found some template called std::initializer_list. Now verify that it's
  8034. // correct.
  8035. TemplateParameterList *Params = Template->getTemplateParameters();
  8036. if (Params->getMinRequiredArguments() != 1 ||
  8037. !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  8038. S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
  8039. return nullptr;
  8040. }
  8041. return Template;
  8042. }
  8043. QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
  8044. if (!StdInitializerList) {
  8045. StdInitializerList = LookupStdInitializerList(*this, Loc);
  8046. if (!StdInitializerList)
  8047. return QualType();
  8048. }
  8049. TemplateArgumentListInfo Args(Loc, Loc);
  8050. Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
  8051. Context.getTrivialTypeSourceInfo(Element,
  8052. Loc)));
  8053. return Context.getCanonicalType(
  8054. CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
  8055. }
  8056. bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
  8057. // C++ [dcl.init.list]p2:
  8058. // A constructor is an initializer-list constructor if its first parameter
  8059. // is of type std::initializer_list<E> or reference to possibly cv-qualified
  8060. // std::initializer_list<E> for some type E, and either there are no other
  8061. // parameters or else all other parameters have default arguments.
  8062. if (Ctor->getNumParams() < 1 ||
  8063. (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
  8064. return false;
  8065. QualType ArgType = Ctor->getParamDecl(0)->getType();
  8066. if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
  8067. ArgType = RT->getPointeeType().getUnqualifiedType();
  8068. return isStdInitializerList(ArgType, nullptr);
  8069. }
  8070. /// Determine whether a using statement is in a context where it will be
  8071. /// apply in all contexts.
  8072. static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
  8073. switch (CurContext->getDeclKind()) {
  8074. case Decl::TranslationUnit:
  8075. return true;
  8076. case Decl::LinkageSpec:
  8077. return IsUsingDirectiveInToplevelContext(CurContext->getParent());
  8078. default:
  8079. return false;
  8080. }
  8081. }
  8082. namespace {
  8083. // Callback to only accept typo corrections that are namespaces.
  8084. class NamespaceValidatorCCC : public CorrectionCandidateCallback {
  8085. public:
  8086. bool ValidateCandidate(const TypoCorrection &candidate) override {
  8087. if (NamedDecl *ND = candidate.getCorrectionDecl())
  8088. return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
  8089. return false;
  8090. }
  8091. };
  8092. }
  8093. static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
  8094. CXXScopeSpec &SS,
  8095. SourceLocation IdentLoc,
  8096. IdentifierInfo *Ident) {
  8097. R.clear();
  8098. if (TypoCorrection Corrected =
  8099. S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
  8100. llvm::make_unique<NamespaceValidatorCCC>(),
  8101. Sema::CTK_ErrorRecovery)) {
  8102. if (DeclContext *DC = S.computeDeclContext(SS, false)) {
  8103. std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
  8104. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  8105. Ident->getName().equals(CorrectedStr);
  8106. S.diagnoseTypo(Corrected,
  8107. S.PDiag(diag::err_using_directive_member_suggest)
  8108. << Ident << DC << DroppedSpecifier << SS.getRange(),
  8109. S.PDiag(diag::note_namespace_defined_here));
  8110. } else {
  8111. S.diagnoseTypo(Corrected,
  8112. S.PDiag(diag::err_using_directive_suggest) << Ident,
  8113. S.PDiag(diag::note_namespace_defined_here));
  8114. }
  8115. R.addDecl(Corrected.getFoundDecl());
  8116. return true;
  8117. }
  8118. return false;
  8119. }
  8120. Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
  8121. SourceLocation NamespcLoc, CXXScopeSpec &SS,
  8122. SourceLocation IdentLoc,
  8123. IdentifierInfo *NamespcName,
  8124. const ParsedAttributesView &AttrList) {
  8125. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  8126. assert(NamespcName && "Invalid NamespcName.");
  8127. assert(IdentLoc.isValid() && "Invalid NamespceName location.");
  8128. // This can only happen along a recovery path.
  8129. while (S->isTemplateParamScope())
  8130. S = S->getParent();
  8131. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  8132. UsingDirectiveDecl *UDir = nullptr;
  8133. NestedNameSpecifier *Qualifier = nullptr;
  8134. if (SS.isSet())
  8135. Qualifier = SS.getScopeRep();
  8136. // Lookup namespace name.
  8137. LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
  8138. LookupParsedName(R, S, &SS);
  8139. if (R.isAmbiguous())
  8140. return nullptr;
  8141. if (R.empty()) {
  8142. R.clear();
  8143. // Allow "using namespace std;" or "using namespace ::std;" even if
  8144. // "std" hasn't been defined yet, for GCC compatibility.
  8145. if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
  8146. NamespcName->isStr("std")) {
  8147. Diag(IdentLoc, diag::ext_using_undefined_std);
  8148. R.addDecl(getOrCreateStdNamespace());
  8149. R.resolveKind();
  8150. }
  8151. // Otherwise, attempt typo correction.
  8152. else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
  8153. }
  8154. if (!R.empty()) {
  8155. NamedDecl *Named = R.getRepresentativeDecl();
  8156. NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
  8157. assert(NS && "expected namespace decl");
  8158. // The use of a nested name specifier may trigger deprecation warnings.
  8159. DiagnoseUseOfDecl(Named, IdentLoc);
  8160. // C++ [namespace.udir]p1:
  8161. // A using-directive specifies that the names in the nominated
  8162. // namespace can be used in the scope in which the
  8163. // using-directive appears after the using-directive. During
  8164. // unqualified name lookup (3.4.1), the names appear as if they
  8165. // were declared in the nearest enclosing namespace which
  8166. // contains both the using-directive and the nominated
  8167. // namespace. [Note: in this context, "contains" means "contains
  8168. // directly or indirectly". ]
  8169. // Find enclosing context containing both using-directive and
  8170. // nominated namespace.
  8171. DeclContext *CommonAncestor = NS;
  8172. while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
  8173. CommonAncestor = CommonAncestor->getParent();
  8174. UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
  8175. SS.getWithLocInContext(Context),
  8176. IdentLoc, Named, CommonAncestor);
  8177. if (IsUsingDirectiveInToplevelContext(CurContext) &&
  8178. !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
  8179. Diag(IdentLoc, diag::warn_using_directive_in_header);
  8180. }
  8181. PushUsingDirective(S, UDir);
  8182. } else {
  8183. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  8184. }
  8185. if (UDir)
  8186. ProcessDeclAttributeList(S, UDir, AttrList);
  8187. return UDir;
  8188. }
  8189. void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
  8190. // If the scope has an associated entity and the using directive is at
  8191. // namespace or translation unit scope, add the UsingDirectiveDecl into
  8192. // its lookup structure so qualified name lookup can find it.
  8193. DeclContext *Ctx = S->getEntity();
  8194. if (Ctx && !Ctx->isFunctionOrMethod())
  8195. Ctx->addDecl(UDir);
  8196. else
  8197. // Otherwise, it is at block scope. The using-directives will affect lookup
  8198. // only to the end of the scope.
  8199. S->PushUsingDirective(UDir);
  8200. }
  8201. Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
  8202. SourceLocation UsingLoc,
  8203. SourceLocation TypenameLoc, CXXScopeSpec &SS,
  8204. UnqualifiedId &Name,
  8205. SourceLocation EllipsisLoc,
  8206. const ParsedAttributesView &AttrList) {
  8207. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  8208. if (SS.isEmpty()) {
  8209. Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
  8210. return nullptr;
  8211. }
  8212. switch (Name.getKind()) {
  8213. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  8214. case UnqualifiedIdKind::IK_Identifier:
  8215. case UnqualifiedIdKind::IK_OperatorFunctionId:
  8216. case UnqualifiedIdKind::IK_LiteralOperatorId:
  8217. case UnqualifiedIdKind::IK_ConversionFunctionId:
  8218. break;
  8219. case UnqualifiedIdKind::IK_ConstructorName:
  8220. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  8221. // C++11 inheriting constructors.
  8222. Diag(Name.getBeginLoc(),
  8223. getLangOpts().CPlusPlus11
  8224. ? diag::warn_cxx98_compat_using_decl_constructor
  8225. : diag::err_using_decl_constructor)
  8226. << SS.getRange();
  8227. if (getLangOpts().CPlusPlus11) break;
  8228. return nullptr;
  8229. case UnqualifiedIdKind::IK_DestructorName:
  8230. Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
  8231. return nullptr;
  8232. case UnqualifiedIdKind::IK_TemplateId:
  8233. Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
  8234. << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
  8235. return nullptr;
  8236. case UnqualifiedIdKind::IK_DeductionGuideName:
  8237. llvm_unreachable("cannot parse qualified deduction guide name");
  8238. }
  8239. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  8240. DeclarationName TargetName = TargetNameInfo.getName();
  8241. if (!TargetName)
  8242. return nullptr;
  8243. // Warn about access declarations.
  8244. if (UsingLoc.isInvalid()) {
  8245. Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
  8246. ? diag::err_access_decl
  8247. : diag::warn_access_decl_deprecated)
  8248. << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
  8249. }
  8250. if (EllipsisLoc.isInvalid()) {
  8251. if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
  8252. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
  8253. return nullptr;
  8254. } else {
  8255. if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
  8256. !TargetNameInfo.containsUnexpandedParameterPack()) {
  8257. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  8258. << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
  8259. EllipsisLoc = SourceLocation();
  8260. }
  8261. }
  8262. NamedDecl *UD =
  8263. BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
  8264. SS, TargetNameInfo, EllipsisLoc, AttrList,
  8265. /*IsInstantiation*/false);
  8266. if (UD)
  8267. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  8268. return UD;
  8269. }
  8270. /// Determine whether a using declaration considers the given
  8271. /// declarations as "equivalent", e.g., if they are redeclarations of
  8272. /// the same entity or are both typedefs of the same type.
  8273. static bool
  8274. IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
  8275. if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
  8276. return true;
  8277. if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
  8278. if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
  8279. return Context.hasSameType(TD1->getUnderlyingType(),
  8280. TD2->getUnderlyingType());
  8281. return false;
  8282. }
  8283. /// Determines whether to create a using shadow decl for a particular
  8284. /// decl, given the set of decls existing prior to this using lookup.
  8285. bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
  8286. const LookupResult &Previous,
  8287. UsingShadowDecl *&PrevShadow) {
  8288. // Diagnose finding a decl which is not from a base class of the
  8289. // current class. We do this now because there are cases where this
  8290. // function will silently decide not to build a shadow decl, which
  8291. // will pre-empt further diagnostics.
  8292. //
  8293. // We don't need to do this in C++11 because we do the check once on
  8294. // the qualifier.
  8295. //
  8296. // FIXME: diagnose the following if we care enough:
  8297. // struct A { int foo; };
  8298. // struct B : A { using A::foo; };
  8299. // template <class T> struct C : A {};
  8300. // template <class T> struct D : C<T> { using B::foo; } // <---
  8301. // This is invalid (during instantiation) in C++03 because B::foo
  8302. // resolves to the using decl in B, which is not a base class of D<T>.
  8303. // We can't diagnose it immediately because C<T> is an unknown
  8304. // specialization. The UsingShadowDecl in D<T> then points directly
  8305. // to A::foo, which will look well-formed when we instantiate.
  8306. // The right solution is to not collapse the shadow-decl chain.
  8307. if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
  8308. DeclContext *OrigDC = Orig->getDeclContext();
  8309. // Handle enums and anonymous structs.
  8310. if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
  8311. CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
  8312. while (OrigRec->isAnonymousStructOrUnion())
  8313. OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
  8314. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
  8315. if (OrigDC == CurContext) {
  8316. Diag(Using->getLocation(),
  8317. diag::err_using_decl_nested_name_specifier_is_current_class)
  8318. << Using->getQualifierLoc().getSourceRange();
  8319. Diag(Orig->getLocation(), diag::note_using_decl_target);
  8320. Using->setInvalidDecl();
  8321. return true;
  8322. }
  8323. Diag(Using->getQualifierLoc().getBeginLoc(),
  8324. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  8325. << Using->getQualifier()
  8326. << cast<CXXRecordDecl>(CurContext)
  8327. << Using->getQualifierLoc().getSourceRange();
  8328. Diag(Orig->getLocation(), diag::note_using_decl_target);
  8329. Using->setInvalidDecl();
  8330. return true;
  8331. }
  8332. }
  8333. if (Previous.empty()) return false;
  8334. NamedDecl *Target = Orig;
  8335. if (isa<UsingShadowDecl>(Target))
  8336. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  8337. // If the target happens to be one of the previous declarations, we
  8338. // don't have a conflict.
  8339. //
  8340. // FIXME: but we might be increasing its access, in which case we
  8341. // should redeclare it.
  8342. NamedDecl *NonTag = nullptr, *Tag = nullptr;
  8343. bool FoundEquivalentDecl = false;
  8344. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  8345. I != E; ++I) {
  8346. NamedDecl *D = (*I)->getUnderlyingDecl();
  8347. // We can have UsingDecls in our Previous results because we use the same
  8348. // LookupResult for checking whether the UsingDecl itself is a valid
  8349. // redeclaration.
  8350. if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
  8351. continue;
  8352. if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  8353. // C++ [class.mem]p19:
  8354. // If T is the name of a class, then [every named member other than
  8355. // a non-static data member] shall have a name different from T
  8356. if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
  8357. !isa<IndirectFieldDecl>(Target) &&
  8358. !isa<UnresolvedUsingValueDecl>(Target) &&
  8359. DiagnoseClassNameShadow(
  8360. CurContext,
  8361. DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
  8362. return true;
  8363. }
  8364. if (IsEquivalentForUsingDecl(Context, D, Target)) {
  8365. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
  8366. PrevShadow = Shadow;
  8367. FoundEquivalentDecl = true;
  8368. } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
  8369. // We don't conflict with an existing using shadow decl of an equivalent
  8370. // declaration, but we're not a redeclaration of it.
  8371. FoundEquivalentDecl = true;
  8372. }
  8373. if (isVisible(D))
  8374. (isa<TagDecl>(D) ? Tag : NonTag) = D;
  8375. }
  8376. if (FoundEquivalentDecl)
  8377. return false;
  8378. if (FunctionDecl *FD = Target->getAsFunction()) {
  8379. NamedDecl *OldDecl = nullptr;
  8380. switch (CheckOverload(nullptr, FD, Previous, OldDecl,
  8381. /*IsForUsingDecl*/ true)) {
  8382. case Ovl_Overload:
  8383. return false;
  8384. case Ovl_NonFunction:
  8385. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8386. break;
  8387. // We found a decl with the exact signature.
  8388. case Ovl_Match:
  8389. // If we're in a record, we want to hide the target, so we
  8390. // return true (without a diagnostic) to tell the caller not to
  8391. // build a shadow decl.
  8392. if (CurContext->isRecord())
  8393. return true;
  8394. // If we're not in a record, this is an error.
  8395. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8396. break;
  8397. }
  8398. Diag(Target->getLocation(), diag::note_using_decl_target);
  8399. Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
  8400. Using->setInvalidDecl();
  8401. return true;
  8402. }
  8403. // Target is not a function.
  8404. if (isa<TagDecl>(Target)) {
  8405. // No conflict between a tag and a non-tag.
  8406. if (!Tag) return false;
  8407. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8408. Diag(Target->getLocation(), diag::note_using_decl_target);
  8409. Diag(Tag->getLocation(), diag::note_using_decl_conflict);
  8410. Using->setInvalidDecl();
  8411. return true;
  8412. }
  8413. // No conflict between a tag and a non-tag.
  8414. if (!NonTag) return false;
  8415. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  8416. Diag(Target->getLocation(), diag::note_using_decl_target);
  8417. Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
  8418. Using->setInvalidDecl();
  8419. return true;
  8420. }
  8421. /// Determine whether a direct base class is a virtual base class.
  8422. static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
  8423. if (!Derived->getNumVBases())
  8424. return false;
  8425. for (auto &B : Derived->bases())
  8426. if (B.getType()->getAsCXXRecordDecl() == Base)
  8427. return B.isVirtual();
  8428. llvm_unreachable("not a direct base class");
  8429. }
  8430. /// Builds a shadow declaration corresponding to a 'using' declaration.
  8431. UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
  8432. UsingDecl *UD,
  8433. NamedDecl *Orig,
  8434. UsingShadowDecl *PrevDecl) {
  8435. // If we resolved to another shadow declaration, just coalesce them.
  8436. NamedDecl *Target = Orig;
  8437. if (isa<UsingShadowDecl>(Target)) {
  8438. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  8439. assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
  8440. }
  8441. NamedDecl *NonTemplateTarget = Target;
  8442. if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
  8443. NonTemplateTarget = TargetTD->getTemplatedDecl();
  8444. UsingShadowDecl *Shadow;
  8445. if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
  8446. bool IsVirtualBase =
  8447. isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
  8448. UD->getQualifier()->getAsRecordDecl());
  8449. Shadow = ConstructorUsingShadowDecl::Create(
  8450. Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
  8451. } else {
  8452. Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
  8453. Target);
  8454. }
  8455. UD->addShadowDecl(Shadow);
  8456. Shadow->setAccess(UD->getAccess());
  8457. if (Orig->isInvalidDecl() || UD->isInvalidDecl())
  8458. Shadow->setInvalidDecl();
  8459. Shadow->setPreviousDecl(PrevDecl);
  8460. if (S)
  8461. PushOnScopeChains(Shadow, S);
  8462. else
  8463. CurContext->addDecl(Shadow);
  8464. return Shadow;
  8465. }
  8466. /// Hides a using shadow declaration. This is required by the current
  8467. /// using-decl implementation when a resolvable using declaration in a
  8468. /// class is followed by a declaration which would hide or override
  8469. /// one or more of the using decl's targets; for example:
  8470. ///
  8471. /// struct Base { void foo(int); };
  8472. /// struct Derived : Base {
  8473. /// using Base::foo;
  8474. /// void foo(int);
  8475. /// };
  8476. ///
  8477. /// The governing language is C++03 [namespace.udecl]p12:
  8478. ///
  8479. /// When a using-declaration brings names from a base class into a
  8480. /// derived class scope, member functions in the derived class
  8481. /// override and/or hide member functions with the same name and
  8482. /// parameter types in a base class (rather than conflicting).
  8483. ///
  8484. /// There are two ways to implement this:
  8485. /// (1) optimistically create shadow decls when they're not hidden
  8486. /// by existing declarations, or
  8487. /// (2) don't create any shadow decls (or at least don't make them
  8488. /// visible) until we've fully parsed/instantiated the class.
  8489. /// The problem with (1) is that we might have to retroactively remove
  8490. /// a shadow decl, which requires several O(n) operations because the
  8491. /// decl structures are (very reasonably) not designed for removal.
  8492. /// (2) avoids this but is very fiddly and phase-dependent.
  8493. void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
  8494. if (Shadow->getDeclName().getNameKind() ==
  8495. DeclarationName::CXXConversionFunctionName)
  8496. cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
  8497. // Remove it from the DeclContext...
  8498. Shadow->getDeclContext()->removeDecl(Shadow);
  8499. // ...and the scope, if applicable...
  8500. if (S) {
  8501. S->RemoveDecl(Shadow);
  8502. IdResolver.RemoveDecl(Shadow);
  8503. }
  8504. // ...and the using decl.
  8505. Shadow->getUsingDecl()->removeShadowDecl(Shadow);
  8506. // TODO: complain somehow if Shadow was used. It shouldn't
  8507. // be possible for this to happen, because...?
  8508. }
  8509. /// Find the base specifier for a base class with the given type.
  8510. static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
  8511. QualType DesiredBase,
  8512. bool &AnyDependentBases) {
  8513. // Check whether the named type is a direct base class.
  8514. CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
  8515. for (auto &Base : Derived->bases()) {
  8516. CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
  8517. if (CanonicalDesiredBase == BaseType)
  8518. return &Base;
  8519. if (BaseType->isDependentType())
  8520. AnyDependentBases = true;
  8521. }
  8522. return nullptr;
  8523. }
  8524. namespace {
  8525. class UsingValidatorCCC : public CorrectionCandidateCallback {
  8526. public:
  8527. UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
  8528. NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
  8529. : HasTypenameKeyword(HasTypenameKeyword),
  8530. IsInstantiation(IsInstantiation), OldNNS(NNS),
  8531. RequireMemberOf(RequireMemberOf) {}
  8532. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  8533. NamedDecl *ND = Candidate.getCorrectionDecl();
  8534. // Keywords are not valid here.
  8535. if (!ND || isa<NamespaceDecl>(ND))
  8536. return false;
  8537. // Completely unqualified names are invalid for a 'using' declaration.
  8538. if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
  8539. return false;
  8540. // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
  8541. // reject.
  8542. if (RequireMemberOf) {
  8543. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  8544. if (FoundRecord && FoundRecord->isInjectedClassName()) {
  8545. // No-one ever wants a using-declaration to name an injected-class-name
  8546. // of a base class, unless they're declaring an inheriting constructor.
  8547. ASTContext &Ctx = ND->getASTContext();
  8548. if (!Ctx.getLangOpts().CPlusPlus11)
  8549. return false;
  8550. QualType FoundType = Ctx.getRecordType(FoundRecord);
  8551. // Check that the injected-class-name is named as a member of its own
  8552. // type; we don't want to suggest 'using Derived::Base;', since that
  8553. // means something else.
  8554. NestedNameSpecifier *Specifier =
  8555. Candidate.WillReplaceSpecifier()
  8556. ? Candidate.getCorrectionSpecifier()
  8557. : OldNNS;
  8558. if (!Specifier->getAsType() ||
  8559. !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
  8560. return false;
  8561. // Check that this inheriting constructor declaration actually names a
  8562. // direct base class of the current class.
  8563. bool AnyDependentBases = false;
  8564. if (!findDirectBaseWithType(RequireMemberOf,
  8565. Ctx.getRecordType(FoundRecord),
  8566. AnyDependentBases) &&
  8567. !AnyDependentBases)
  8568. return false;
  8569. } else {
  8570. auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
  8571. if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
  8572. return false;
  8573. // FIXME: Check that the base class member is accessible?
  8574. }
  8575. } else {
  8576. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  8577. if (FoundRecord && FoundRecord->isInjectedClassName())
  8578. return false;
  8579. }
  8580. if (isa<TypeDecl>(ND))
  8581. return HasTypenameKeyword || !IsInstantiation;
  8582. return !HasTypenameKeyword;
  8583. }
  8584. private:
  8585. bool HasTypenameKeyword;
  8586. bool IsInstantiation;
  8587. NestedNameSpecifier *OldNNS;
  8588. CXXRecordDecl *RequireMemberOf;
  8589. };
  8590. } // end anonymous namespace
  8591. /// Builds a using declaration.
  8592. ///
  8593. /// \param IsInstantiation - Whether this call arises from an
  8594. /// instantiation of an unresolved using declaration. We treat
  8595. /// the lookup differently for these declarations.
  8596. NamedDecl *Sema::BuildUsingDeclaration(
  8597. Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
  8598. bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
  8599. DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
  8600. const ParsedAttributesView &AttrList, bool IsInstantiation) {
  8601. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  8602. SourceLocation IdentLoc = NameInfo.getLoc();
  8603. assert(IdentLoc.isValid() && "Invalid TargetName location.");
  8604. // FIXME: We ignore attributes for now.
  8605. // For an inheriting constructor declaration, the name of the using
  8606. // declaration is the name of a constructor in this class, not in the
  8607. // base class.
  8608. DeclarationNameInfo UsingName = NameInfo;
  8609. if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
  8610. if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
  8611. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  8612. Context.getCanonicalType(Context.getRecordType(RD))));
  8613. // Do the redeclaration lookup in the current scope.
  8614. LookupResult Previous(*this, UsingName, LookupUsingDeclName,
  8615. ForVisibleRedeclaration);
  8616. Previous.setHideTags(false);
  8617. if (S) {
  8618. LookupName(Previous, S);
  8619. // It is really dumb that we have to do this.
  8620. LookupResult::Filter F = Previous.makeFilter();
  8621. while (F.hasNext()) {
  8622. NamedDecl *D = F.next();
  8623. if (!isDeclInScope(D, CurContext, S))
  8624. F.erase();
  8625. // If we found a local extern declaration that's not ordinarily visible,
  8626. // and this declaration is being added to a non-block scope, ignore it.
  8627. // We're only checking for scope conflicts here, not also for violations
  8628. // of the linkage rules.
  8629. else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
  8630. !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
  8631. F.erase();
  8632. }
  8633. F.done();
  8634. } else {
  8635. assert(IsInstantiation && "no scope in non-instantiation");
  8636. if (CurContext->isRecord())
  8637. LookupQualifiedName(Previous, CurContext);
  8638. else {
  8639. // No redeclaration check is needed here; in non-member contexts we
  8640. // diagnosed all possible conflicts with other using-declarations when
  8641. // building the template:
  8642. //
  8643. // For a dependent non-type using declaration, the only valid case is
  8644. // if we instantiate to a single enumerator. We check for conflicts
  8645. // between shadow declarations we introduce, and we check in the template
  8646. // definition for conflicts between a non-type using declaration and any
  8647. // other declaration, which together covers all cases.
  8648. //
  8649. // A dependent typename using declaration will never successfully
  8650. // instantiate, since it will always name a class member, so we reject
  8651. // that in the template definition.
  8652. }
  8653. }
  8654. // Check for invalid redeclarations.
  8655. if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
  8656. SS, IdentLoc, Previous))
  8657. return nullptr;
  8658. // Check for bad qualifiers.
  8659. if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
  8660. IdentLoc))
  8661. return nullptr;
  8662. DeclContext *LookupContext = computeDeclContext(SS);
  8663. NamedDecl *D;
  8664. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  8665. if (!LookupContext || EllipsisLoc.isValid()) {
  8666. if (HasTypenameKeyword) {
  8667. // FIXME: not all declaration name kinds are legal here
  8668. D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
  8669. UsingLoc, TypenameLoc,
  8670. QualifierLoc,
  8671. IdentLoc, NameInfo.getName(),
  8672. EllipsisLoc);
  8673. } else {
  8674. D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
  8675. QualifierLoc, NameInfo, EllipsisLoc);
  8676. }
  8677. D->setAccess(AS);
  8678. CurContext->addDecl(D);
  8679. return D;
  8680. }
  8681. auto Build = [&](bool Invalid) {
  8682. UsingDecl *UD =
  8683. UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
  8684. UsingName, HasTypenameKeyword);
  8685. UD->setAccess(AS);
  8686. CurContext->addDecl(UD);
  8687. UD->setInvalidDecl(Invalid);
  8688. return UD;
  8689. };
  8690. auto BuildInvalid = [&]{ return Build(true); };
  8691. auto BuildValid = [&]{ return Build(false); };
  8692. if (RequireCompleteDeclContext(SS, LookupContext))
  8693. return BuildInvalid();
  8694. // Look up the target name.
  8695. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  8696. // Unlike most lookups, we don't always want to hide tag
  8697. // declarations: tag names are visible through the using declaration
  8698. // even if hidden by ordinary names, *except* in a dependent context
  8699. // where it's important for the sanity of two-phase lookup.
  8700. if (!IsInstantiation)
  8701. R.setHideTags(false);
  8702. // For the purposes of this lookup, we have a base object type
  8703. // equal to that of the current context.
  8704. if (CurContext->isRecord()) {
  8705. R.setBaseObjectType(
  8706. Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
  8707. }
  8708. LookupQualifiedName(R, LookupContext);
  8709. // Try to correct typos if possible. If constructor name lookup finds no
  8710. // results, that means the named class has no explicit constructors, and we
  8711. // suppressed declaring implicit ones (probably because it's dependent or
  8712. // invalid).
  8713. if (R.empty() &&
  8714. NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
  8715. // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
  8716. // it will believe that glibc provides a ::gets in cases where it does not,
  8717. // and will try to pull it into namespace std with a using-declaration.
  8718. // Just ignore the using-declaration in that case.
  8719. auto *II = NameInfo.getName().getAsIdentifierInfo();
  8720. if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
  8721. CurContext->isStdNamespace() &&
  8722. isa<TranslationUnitDecl>(LookupContext) &&
  8723. getSourceManager().isInSystemHeader(UsingLoc))
  8724. return nullptr;
  8725. if (TypoCorrection Corrected = CorrectTypo(
  8726. R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  8727. llvm::make_unique<UsingValidatorCCC>(
  8728. HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
  8729. dyn_cast<CXXRecordDecl>(CurContext)),
  8730. CTK_ErrorRecovery)) {
  8731. // We reject candidates where DroppedSpecifier == true, hence the
  8732. // literal '0' below.
  8733. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  8734. << NameInfo.getName() << LookupContext << 0
  8735. << SS.getRange());
  8736. // If we picked a correction with no attached Decl we can't do anything
  8737. // useful with it, bail out.
  8738. NamedDecl *ND = Corrected.getCorrectionDecl();
  8739. if (!ND)
  8740. return BuildInvalid();
  8741. // If we corrected to an inheriting constructor, handle it as one.
  8742. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  8743. if (RD && RD->isInjectedClassName()) {
  8744. // The parent of the injected class name is the class itself.
  8745. RD = cast<CXXRecordDecl>(RD->getParent());
  8746. // Fix up the information we'll use to build the using declaration.
  8747. if (Corrected.WillReplaceSpecifier()) {
  8748. NestedNameSpecifierLocBuilder Builder;
  8749. Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  8750. QualifierLoc.getSourceRange());
  8751. QualifierLoc = Builder.getWithLocInContext(Context);
  8752. }
  8753. // In this case, the name we introduce is the name of a derived class
  8754. // constructor.
  8755. auto *CurClass = cast<CXXRecordDecl>(CurContext);
  8756. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  8757. Context.getCanonicalType(Context.getRecordType(CurClass))));
  8758. UsingName.setNamedTypeInfo(nullptr);
  8759. for (auto *Ctor : LookupConstructors(RD))
  8760. R.addDecl(Ctor);
  8761. R.resolveKind();
  8762. } else {
  8763. // FIXME: Pick up all the declarations if we found an overloaded
  8764. // function.
  8765. UsingName.setName(ND->getDeclName());
  8766. R.addDecl(ND);
  8767. }
  8768. } else {
  8769. Diag(IdentLoc, diag::err_no_member)
  8770. << NameInfo.getName() << LookupContext << SS.getRange();
  8771. return BuildInvalid();
  8772. }
  8773. }
  8774. if (R.isAmbiguous())
  8775. return BuildInvalid();
  8776. if (HasTypenameKeyword) {
  8777. // If we asked for a typename and got a non-type decl, error out.
  8778. if (!R.getAsSingle<TypeDecl>()) {
  8779. Diag(IdentLoc, diag::err_using_typename_non_type);
  8780. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  8781. Diag((*I)->getUnderlyingDecl()->getLocation(),
  8782. diag::note_using_decl_target);
  8783. return BuildInvalid();
  8784. }
  8785. } else {
  8786. // If we asked for a non-typename and we got a type, error out,
  8787. // but only if this is an instantiation of an unresolved using
  8788. // decl. Otherwise just silently find the type name.
  8789. if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
  8790. Diag(IdentLoc, diag::err_using_dependent_value_is_type);
  8791. Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
  8792. return BuildInvalid();
  8793. }
  8794. }
  8795. // C++14 [namespace.udecl]p6:
  8796. // A using-declaration shall not name a namespace.
  8797. if (R.getAsSingle<NamespaceDecl>()) {
  8798. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
  8799. << SS.getRange();
  8800. return BuildInvalid();
  8801. }
  8802. // C++14 [namespace.udecl]p7:
  8803. // A using-declaration shall not name a scoped enumerator.
  8804. if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
  8805. if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
  8806. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
  8807. << SS.getRange();
  8808. return BuildInvalid();
  8809. }
  8810. }
  8811. UsingDecl *UD = BuildValid();
  8812. // Some additional rules apply to inheriting constructors.
  8813. if (UsingName.getName().getNameKind() ==
  8814. DeclarationName::CXXConstructorName) {
  8815. // Suppress access diagnostics; the access check is instead performed at the
  8816. // point of use for an inheriting constructor.
  8817. R.suppressDiagnostics();
  8818. if (CheckInheritingConstructorUsingDecl(UD))
  8819. return UD;
  8820. }
  8821. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  8822. UsingShadowDecl *PrevDecl = nullptr;
  8823. if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
  8824. BuildUsingShadowDecl(S, UD, *I, PrevDecl);
  8825. }
  8826. return UD;
  8827. }
  8828. NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
  8829. ArrayRef<NamedDecl *> Expansions) {
  8830. assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
  8831. isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
  8832. isa<UsingPackDecl>(InstantiatedFrom));
  8833. auto *UPD =
  8834. UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
  8835. UPD->setAccess(InstantiatedFrom->getAccess());
  8836. CurContext->addDecl(UPD);
  8837. return UPD;
  8838. }
  8839. /// Additional checks for a using declaration referring to a constructor name.
  8840. bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
  8841. assert(!UD->hasTypename() && "expecting a constructor name");
  8842. const Type *SourceType = UD->getQualifier()->getAsType();
  8843. assert(SourceType &&
  8844. "Using decl naming constructor doesn't have type in scope spec.");
  8845. CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
  8846. // Check whether the named type is a direct base class.
  8847. bool AnyDependentBases = false;
  8848. auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
  8849. AnyDependentBases);
  8850. if (!Base && !AnyDependentBases) {
  8851. Diag(UD->getUsingLoc(),
  8852. diag::err_using_decl_constructor_not_in_direct_base)
  8853. << UD->getNameInfo().getSourceRange()
  8854. << QualType(SourceType, 0) << TargetClass;
  8855. UD->setInvalidDecl();
  8856. return true;
  8857. }
  8858. if (Base)
  8859. Base->setInheritConstructors();
  8860. return false;
  8861. }
  8862. /// Checks that the given using declaration is not an invalid
  8863. /// redeclaration. Note that this is checking only for the using decl
  8864. /// itself, not for any ill-formedness among the UsingShadowDecls.
  8865. bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
  8866. bool HasTypenameKeyword,
  8867. const CXXScopeSpec &SS,
  8868. SourceLocation NameLoc,
  8869. const LookupResult &Prev) {
  8870. NestedNameSpecifier *Qual = SS.getScopeRep();
  8871. // C++03 [namespace.udecl]p8:
  8872. // C++0x [namespace.udecl]p10:
  8873. // A using-declaration is a declaration and can therefore be used
  8874. // repeatedly where (and only where) multiple declarations are
  8875. // allowed.
  8876. //
  8877. // That's in non-member contexts.
  8878. if (!CurContext->getRedeclContext()->isRecord()) {
  8879. // A dependent qualifier outside a class can only ever resolve to an
  8880. // enumeration type. Therefore it conflicts with any other non-type
  8881. // declaration in the same scope.
  8882. // FIXME: How should we check for dependent type-type conflicts at block
  8883. // scope?
  8884. if (Qual->isDependent() && !HasTypenameKeyword) {
  8885. for (auto *D : Prev) {
  8886. if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
  8887. bool OldCouldBeEnumerator =
  8888. isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
  8889. Diag(NameLoc,
  8890. OldCouldBeEnumerator ? diag::err_redefinition
  8891. : diag::err_redefinition_different_kind)
  8892. << Prev.getLookupName();
  8893. Diag(D->getLocation(), diag::note_previous_definition);
  8894. return true;
  8895. }
  8896. }
  8897. }
  8898. return false;
  8899. }
  8900. for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
  8901. NamedDecl *D = *I;
  8902. bool DTypename;
  8903. NestedNameSpecifier *DQual;
  8904. if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
  8905. DTypename = UD->hasTypename();
  8906. DQual = UD->getQualifier();
  8907. } else if (UnresolvedUsingValueDecl *UD
  8908. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  8909. DTypename = false;
  8910. DQual = UD->getQualifier();
  8911. } else if (UnresolvedUsingTypenameDecl *UD
  8912. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  8913. DTypename = true;
  8914. DQual = UD->getQualifier();
  8915. } else continue;
  8916. // using decls differ if one says 'typename' and the other doesn't.
  8917. // FIXME: non-dependent using decls?
  8918. if (HasTypenameKeyword != DTypename) continue;
  8919. // using decls differ if they name different scopes (but note that
  8920. // template instantiation can cause this check to trigger when it
  8921. // didn't before instantiation).
  8922. if (Context.getCanonicalNestedNameSpecifier(Qual) !=
  8923. Context.getCanonicalNestedNameSpecifier(DQual))
  8924. continue;
  8925. Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
  8926. Diag(D->getLocation(), diag::note_using_decl) << 1;
  8927. return true;
  8928. }
  8929. return false;
  8930. }
  8931. /// Checks that the given nested-name qualifier used in a using decl
  8932. /// in the current context is appropriately related to the current
  8933. /// scope. If an error is found, diagnoses it and returns true.
  8934. bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
  8935. bool HasTypename,
  8936. const CXXScopeSpec &SS,
  8937. const DeclarationNameInfo &NameInfo,
  8938. SourceLocation NameLoc) {
  8939. DeclContext *NamedContext = computeDeclContext(SS);
  8940. if (!CurContext->isRecord()) {
  8941. // C++03 [namespace.udecl]p3:
  8942. // C++0x [namespace.udecl]p8:
  8943. // A using-declaration for a class member shall be a member-declaration.
  8944. // If we weren't able to compute a valid scope, it might validly be a
  8945. // dependent class scope or a dependent enumeration unscoped scope. If
  8946. // we have a 'typename' keyword, the scope must resolve to a class type.
  8947. if ((HasTypename && !NamedContext) ||
  8948. (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
  8949. auto *RD = NamedContext
  8950. ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
  8951. : nullptr;
  8952. if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
  8953. RD = nullptr;
  8954. Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
  8955. << SS.getRange();
  8956. // If we have a complete, non-dependent source type, try to suggest a
  8957. // way to get the same effect.
  8958. if (!RD)
  8959. return true;
  8960. // Find what this using-declaration was referring to.
  8961. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  8962. R.setHideTags(false);
  8963. R.suppressDiagnostics();
  8964. LookupQualifiedName(R, RD);
  8965. if (R.getAsSingle<TypeDecl>()) {
  8966. if (getLangOpts().CPlusPlus11) {
  8967. // Convert 'using X::Y;' to 'using Y = X::Y;'.
  8968. Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
  8969. << 0 // alias declaration
  8970. << FixItHint::CreateInsertion(SS.getBeginLoc(),
  8971. NameInfo.getName().getAsString() +
  8972. " = ");
  8973. } else {
  8974. // Convert 'using X::Y;' to 'typedef X::Y Y;'.
  8975. SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
  8976. Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
  8977. << 1 // typedef declaration
  8978. << FixItHint::CreateReplacement(UsingLoc, "typedef")
  8979. << FixItHint::CreateInsertion(
  8980. InsertLoc, " " + NameInfo.getName().getAsString());
  8981. }
  8982. } else if (R.getAsSingle<VarDecl>()) {
  8983. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  8984. // repeating the type of the static data member here.
  8985. FixItHint FixIt;
  8986. if (getLangOpts().CPlusPlus11) {
  8987. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  8988. FixIt = FixItHint::CreateReplacement(
  8989. UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
  8990. }
  8991. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  8992. << 2 // reference declaration
  8993. << FixIt;
  8994. } else if (R.getAsSingle<EnumConstantDecl>()) {
  8995. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  8996. // repeating the type of the enumeration here, and we can't do so if
  8997. // the type is anonymous.
  8998. FixItHint FixIt;
  8999. if (getLangOpts().CPlusPlus11) {
  9000. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  9001. FixIt = FixItHint::CreateReplacement(
  9002. UsingLoc,
  9003. "constexpr auto " + NameInfo.getName().getAsString() + " = ");
  9004. }
  9005. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  9006. << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
  9007. << FixIt;
  9008. }
  9009. return true;
  9010. }
  9011. // Otherwise, this might be valid.
  9012. return false;
  9013. }
  9014. // The current scope is a record.
  9015. // If the named context is dependent, we can't decide much.
  9016. if (!NamedContext) {
  9017. // FIXME: in C++0x, we can diagnose if we can prove that the
  9018. // nested-name-specifier does not refer to a base class, which is
  9019. // still possible in some cases.
  9020. // Otherwise we have to conservatively report that things might be
  9021. // okay.
  9022. return false;
  9023. }
  9024. if (!NamedContext->isRecord()) {
  9025. // Ideally this would point at the last name in the specifier,
  9026. // but we don't have that level of source info.
  9027. Diag(SS.getRange().getBegin(),
  9028. diag::err_using_decl_nested_name_specifier_is_not_class)
  9029. << SS.getScopeRep() << SS.getRange();
  9030. return true;
  9031. }
  9032. if (!NamedContext->isDependentContext() &&
  9033. RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
  9034. return true;
  9035. if (getLangOpts().CPlusPlus11) {
  9036. // C++11 [namespace.udecl]p3:
  9037. // In a using-declaration used as a member-declaration, the
  9038. // nested-name-specifier shall name a base class of the class
  9039. // being defined.
  9040. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
  9041. cast<CXXRecordDecl>(NamedContext))) {
  9042. if (CurContext == NamedContext) {
  9043. Diag(NameLoc,
  9044. diag::err_using_decl_nested_name_specifier_is_current_class)
  9045. << SS.getRange();
  9046. return true;
  9047. }
  9048. if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
  9049. Diag(SS.getRange().getBegin(),
  9050. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  9051. << SS.getScopeRep()
  9052. << cast<CXXRecordDecl>(CurContext)
  9053. << SS.getRange();
  9054. }
  9055. return true;
  9056. }
  9057. return false;
  9058. }
  9059. // C++03 [namespace.udecl]p4:
  9060. // A using-declaration used as a member-declaration shall refer
  9061. // to a member of a base class of the class being defined [etc.].
  9062. // Salient point: SS doesn't have to name a base class as long as
  9063. // lookup only finds members from base classes. Therefore we can
  9064. // diagnose here only if we can prove that that can't happen,
  9065. // i.e. if the class hierarchies provably don't intersect.
  9066. // TODO: it would be nice if "definitely valid" results were cached
  9067. // in the UsingDecl and UsingShadowDecl so that these checks didn't
  9068. // need to be repeated.
  9069. llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
  9070. auto Collect = [&Bases](const CXXRecordDecl *Base) {
  9071. Bases.insert(Base);
  9072. return true;
  9073. };
  9074. // Collect all bases. Return false if we find a dependent base.
  9075. if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
  9076. return false;
  9077. // Returns true if the base is dependent or is one of the accumulated base
  9078. // classes.
  9079. auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
  9080. return !Bases.count(Base);
  9081. };
  9082. // Return false if the class has a dependent base or if it or one
  9083. // of its bases is present in the base set of the current context.
  9084. if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
  9085. !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
  9086. return false;
  9087. Diag(SS.getRange().getBegin(),
  9088. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  9089. << SS.getScopeRep()
  9090. << cast<CXXRecordDecl>(CurContext)
  9091. << SS.getRange();
  9092. return true;
  9093. }
  9094. Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
  9095. MultiTemplateParamsArg TemplateParamLists,
  9096. SourceLocation UsingLoc, UnqualifiedId &Name,
  9097. const ParsedAttributesView &AttrList,
  9098. TypeResult Type, Decl *DeclFromDeclSpec) {
  9099. // Skip up to the relevant declaration scope.
  9100. while (S->isTemplateParamScope())
  9101. S = S->getParent();
  9102. assert((S->getFlags() & Scope::DeclScope) &&
  9103. "got alias-declaration outside of declaration scope");
  9104. if (Type.isInvalid())
  9105. return nullptr;
  9106. bool Invalid = false;
  9107. DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
  9108. TypeSourceInfo *TInfo = nullptr;
  9109. GetTypeFromParser(Type.get(), &TInfo);
  9110. if (DiagnoseClassNameShadow(CurContext, NameInfo))
  9111. return nullptr;
  9112. if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
  9113. UPPC_DeclarationType)) {
  9114. Invalid = true;
  9115. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  9116. TInfo->getTypeLoc().getBeginLoc());
  9117. }
  9118. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  9119. TemplateParamLists.size()
  9120. ? forRedeclarationInCurContext()
  9121. : ForVisibleRedeclaration);
  9122. LookupName(Previous, S);
  9123. // Warn about shadowing the name of a template parameter.
  9124. if (Previous.isSingleResult() &&
  9125. Previous.getFoundDecl()->isTemplateParameter()) {
  9126. DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
  9127. Previous.clear();
  9128. }
  9129. assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
  9130. "name in alias declaration must be an identifier");
  9131. TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
  9132. Name.StartLocation,
  9133. Name.Identifier, TInfo);
  9134. NewTD->setAccess(AS);
  9135. if (Invalid)
  9136. NewTD->setInvalidDecl();
  9137. ProcessDeclAttributeList(S, NewTD, AttrList);
  9138. AddPragmaAttributes(S, NewTD);
  9139. CheckTypedefForVariablyModifiedType(S, NewTD);
  9140. Invalid |= NewTD->isInvalidDecl();
  9141. bool Redeclaration = false;
  9142. NamedDecl *NewND;
  9143. if (TemplateParamLists.size()) {
  9144. TypeAliasTemplateDecl *OldDecl = nullptr;
  9145. TemplateParameterList *OldTemplateParams = nullptr;
  9146. if (TemplateParamLists.size() != 1) {
  9147. Diag(UsingLoc, diag::err_alias_template_extra_headers)
  9148. << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
  9149. TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
  9150. }
  9151. TemplateParameterList *TemplateParams = TemplateParamLists[0];
  9152. // Check that we can declare a template here.
  9153. if (CheckTemplateDeclScope(S, TemplateParams))
  9154. return nullptr;
  9155. // Only consider previous declarations in the same scope.
  9156. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
  9157. /*ExplicitInstantiationOrSpecialization*/false);
  9158. if (!Previous.empty()) {
  9159. Redeclaration = true;
  9160. OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
  9161. if (!OldDecl && !Invalid) {
  9162. Diag(UsingLoc, diag::err_redefinition_different_kind)
  9163. << Name.Identifier;
  9164. NamedDecl *OldD = Previous.getRepresentativeDecl();
  9165. if (OldD->getLocation().isValid())
  9166. Diag(OldD->getLocation(), diag::note_previous_definition);
  9167. Invalid = true;
  9168. }
  9169. if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
  9170. if (TemplateParameterListsAreEqual(TemplateParams,
  9171. OldDecl->getTemplateParameters(),
  9172. /*Complain=*/true,
  9173. TPL_TemplateMatch))
  9174. OldTemplateParams =
  9175. OldDecl->getMostRecentDecl()->getTemplateParameters();
  9176. else
  9177. Invalid = true;
  9178. TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
  9179. if (!Invalid &&
  9180. !Context.hasSameType(OldTD->getUnderlyingType(),
  9181. NewTD->getUnderlyingType())) {
  9182. // FIXME: The C++0x standard does not clearly say this is ill-formed,
  9183. // but we can't reasonably accept it.
  9184. Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
  9185. << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
  9186. if (OldTD->getLocation().isValid())
  9187. Diag(OldTD->getLocation(), diag::note_previous_definition);
  9188. Invalid = true;
  9189. }
  9190. }
  9191. }
  9192. // Merge any previous default template arguments into our parameters,
  9193. // and check the parameter list.
  9194. if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
  9195. TPC_TypeAliasTemplate))
  9196. return nullptr;
  9197. TypeAliasTemplateDecl *NewDecl =
  9198. TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
  9199. Name.Identifier, TemplateParams,
  9200. NewTD);
  9201. NewTD->setDescribedAliasTemplate(NewDecl);
  9202. NewDecl->setAccess(AS);
  9203. if (Invalid)
  9204. NewDecl->setInvalidDecl();
  9205. else if (OldDecl) {
  9206. NewDecl->setPreviousDecl(OldDecl);
  9207. CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
  9208. }
  9209. NewND = NewDecl;
  9210. } else {
  9211. if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
  9212. setTagNameForLinkagePurposes(TD, NewTD);
  9213. handleTagNumbering(TD, S);
  9214. }
  9215. ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
  9216. NewND = NewTD;
  9217. }
  9218. PushOnScopeChains(NewND, S);
  9219. ActOnDocumentableDecl(NewND);
  9220. return NewND;
  9221. }
  9222. Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
  9223. SourceLocation AliasLoc,
  9224. IdentifierInfo *Alias, CXXScopeSpec &SS,
  9225. SourceLocation IdentLoc,
  9226. IdentifierInfo *Ident) {
  9227. // Lookup the namespace name.
  9228. LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
  9229. LookupParsedName(R, S, &SS);
  9230. if (R.isAmbiguous())
  9231. return nullptr;
  9232. if (R.empty()) {
  9233. if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
  9234. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  9235. return nullptr;
  9236. }
  9237. }
  9238. assert(!R.isAmbiguous() && !R.empty());
  9239. NamedDecl *ND = R.getRepresentativeDecl();
  9240. // Check if we have a previous declaration with the same name.
  9241. LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
  9242. ForVisibleRedeclaration);
  9243. LookupName(PrevR, S);
  9244. // Check we're not shadowing a template parameter.
  9245. if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
  9246. DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
  9247. PrevR.clear();
  9248. }
  9249. // Filter out any other lookup result from an enclosing scope.
  9250. FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
  9251. /*AllowInlineNamespace*/false);
  9252. // Find the previous declaration and check that we can redeclare it.
  9253. NamespaceAliasDecl *Prev = nullptr;
  9254. if (PrevR.isSingleResult()) {
  9255. NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
  9256. if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
  9257. // We already have an alias with the same name that points to the same
  9258. // namespace; check that it matches.
  9259. if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
  9260. Prev = AD;
  9261. } else if (isVisible(PrevDecl)) {
  9262. Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
  9263. << Alias;
  9264. Diag(AD->getLocation(), diag::note_previous_namespace_alias)
  9265. << AD->getNamespace();
  9266. return nullptr;
  9267. }
  9268. } else if (isVisible(PrevDecl)) {
  9269. unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
  9270. ? diag::err_redefinition
  9271. : diag::err_redefinition_different_kind;
  9272. Diag(AliasLoc, DiagID) << Alias;
  9273. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  9274. return nullptr;
  9275. }
  9276. }
  9277. // The use of a nested name specifier may trigger deprecation warnings.
  9278. DiagnoseUseOfDecl(ND, IdentLoc);
  9279. NamespaceAliasDecl *AliasDecl =
  9280. NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
  9281. Alias, SS.getWithLocInContext(Context),
  9282. IdentLoc, ND);
  9283. if (Prev)
  9284. AliasDecl->setPreviousDecl(Prev);
  9285. PushOnScopeChains(AliasDecl, S);
  9286. return AliasDecl;
  9287. }
  9288. namespace {
  9289. struct SpecialMemberExceptionSpecInfo
  9290. : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
  9291. SourceLocation Loc;
  9292. Sema::ImplicitExceptionSpecification ExceptSpec;
  9293. SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
  9294. Sema::CXXSpecialMember CSM,
  9295. Sema::InheritedConstructorInfo *ICI,
  9296. SourceLocation Loc)
  9297. : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
  9298. bool visitBase(CXXBaseSpecifier *Base);
  9299. bool visitField(FieldDecl *FD);
  9300. void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  9301. unsigned Quals);
  9302. void visitSubobjectCall(Subobject Subobj,
  9303. Sema::SpecialMemberOverloadResult SMOR);
  9304. };
  9305. }
  9306. bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
  9307. auto *RT = Base->getType()->getAs<RecordType>();
  9308. if (!RT)
  9309. return false;
  9310. auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
  9311. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  9312. if (auto *BaseCtor = SMOR.getMethod()) {
  9313. visitSubobjectCall(Base, BaseCtor);
  9314. return false;
  9315. }
  9316. visitClassSubobject(BaseClass, Base, 0);
  9317. return false;
  9318. }
  9319. bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
  9320. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
  9321. Expr *E = FD->getInClassInitializer();
  9322. if (!E)
  9323. // FIXME: It's a little wasteful to build and throw away a
  9324. // CXXDefaultInitExpr here.
  9325. // FIXME: We should have a single context note pointing at Loc, and
  9326. // this location should be MD->getLocation() instead, since that's
  9327. // the location where we actually use the default init expression.
  9328. E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
  9329. if (E)
  9330. ExceptSpec.CalledExpr(E);
  9331. } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
  9332. ->getAs<RecordType>()) {
  9333. visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
  9334. FD->getType().getCVRQualifiers());
  9335. }
  9336. return false;
  9337. }
  9338. void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
  9339. Subobject Subobj,
  9340. unsigned Quals) {
  9341. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  9342. bool IsMutable = Field && Field->isMutable();
  9343. visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
  9344. }
  9345. void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
  9346. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
  9347. // Note, if lookup fails, it doesn't matter what exception specification we
  9348. // choose because the special member will be deleted.
  9349. if (CXXMethodDecl *MD = SMOR.getMethod())
  9350. ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
  9351. }
  9352. namespace {
  9353. /// RAII object to register a special member as being currently declared.
  9354. struct ComputingExceptionSpec {
  9355. Sema &S;
  9356. ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
  9357. : S(S) {
  9358. Sema::CodeSynthesisContext Ctx;
  9359. Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
  9360. Ctx.PointOfInstantiation = Loc;
  9361. Ctx.Entity = MD;
  9362. S.pushCodeSynthesisContext(Ctx);
  9363. }
  9364. ~ComputingExceptionSpec() {
  9365. S.popCodeSynthesisContext();
  9366. }
  9367. };
  9368. }
  9369. static Sema::ImplicitExceptionSpecification
  9370. ComputeDefaultedSpecialMemberExceptionSpec(
  9371. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  9372. Sema::InheritedConstructorInfo *ICI) {
  9373. ComputingExceptionSpec CES(S, MD, Loc);
  9374. CXXRecordDecl *ClassDecl = MD->getParent();
  9375. // C++ [except.spec]p14:
  9376. // An implicitly declared special member function (Clause 12) shall have an
  9377. // exception-specification. [...]
  9378. SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
  9379. if (ClassDecl->isInvalidDecl())
  9380. return Info.ExceptSpec;
  9381. // FIXME: If this diagnostic fires, we're probably missing a check for
  9382. // attempting to resolve an exception specification before it's known
  9383. // at a higher level.
  9384. if (S.RequireCompleteType(MD->getLocation(),
  9385. S.Context.getRecordType(ClassDecl),
  9386. diag::err_exception_spec_incomplete_type))
  9387. return Info.ExceptSpec;
  9388. // C++1z [except.spec]p7:
  9389. // [Look for exceptions thrown by] a constructor selected [...] to
  9390. // initialize a potentially constructed subobject,
  9391. // C++1z [except.spec]p8:
  9392. // The exception specification for an implicitly-declared destructor, or a
  9393. // destructor without a noexcept-specifier, is potentially-throwing if and
  9394. // only if any of the destructors for any of its potentially constructed
  9395. // subojects is potentially throwing.
  9396. // FIXME: We respect the first rule but ignore the "potentially constructed"
  9397. // in the second rule to resolve a core issue (no number yet) that would have
  9398. // us reject:
  9399. // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
  9400. // struct B : A {};
  9401. // struct C : B { void f(); };
  9402. // ... due to giving B::~B() a non-throwing exception specification.
  9403. Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
  9404. : Info.VisitAllBases);
  9405. return Info.ExceptSpec;
  9406. }
  9407. namespace {
  9408. /// RAII object to register a special member as being currently declared.
  9409. struct DeclaringSpecialMember {
  9410. Sema &S;
  9411. Sema::SpecialMemberDecl D;
  9412. Sema::ContextRAII SavedContext;
  9413. bool WasAlreadyBeingDeclared;
  9414. DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
  9415. : S(S), D(RD, CSM), SavedContext(S, RD) {
  9416. WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
  9417. if (WasAlreadyBeingDeclared)
  9418. // This almost never happens, but if it does, ensure that our cache
  9419. // doesn't contain a stale result.
  9420. S.SpecialMemberCache.clear();
  9421. else {
  9422. // Register a note to be produced if we encounter an error while
  9423. // declaring the special member.
  9424. Sema::CodeSynthesisContext Ctx;
  9425. Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
  9426. // FIXME: We don't have a location to use here. Using the class's
  9427. // location maintains the fiction that we declare all special members
  9428. // with the class, but (1) it's not clear that lying about that helps our
  9429. // users understand what's going on, and (2) there may be outer contexts
  9430. // on the stack (some of which are relevant) and printing them exposes
  9431. // our lies.
  9432. Ctx.PointOfInstantiation = RD->getLocation();
  9433. Ctx.Entity = RD;
  9434. Ctx.SpecialMember = CSM;
  9435. S.pushCodeSynthesisContext(Ctx);
  9436. }
  9437. }
  9438. ~DeclaringSpecialMember() {
  9439. if (!WasAlreadyBeingDeclared) {
  9440. S.SpecialMembersBeingDeclared.erase(D);
  9441. S.popCodeSynthesisContext();
  9442. }
  9443. }
  9444. /// Are we already trying to declare this special member?
  9445. bool isAlreadyBeingDeclared() const {
  9446. return WasAlreadyBeingDeclared;
  9447. }
  9448. };
  9449. }
  9450. void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
  9451. // Look up any existing declarations, but don't trigger declaration of all
  9452. // implicit special members with this name.
  9453. DeclarationName Name = FD->getDeclName();
  9454. LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
  9455. ForExternalRedeclaration);
  9456. for (auto *D : FD->getParent()->lookup(Name))
  9457. if (auto *Acceptable = R.getAcceptableDecl(D))
  9458. R.addDecl(Acceptable);
  9459. R.resolveKind();
  9460. R.suppressDiagnostics();
  9461. CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
  9462. }
  9463. CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
  9464. CXXRecordDecl *ClassDecl) {
  9465. // C++ [class.ctor]p5:
  9466. // A default constructor for a class X is a constructor of class X
  9467. // that can be called without an argument. If there is no
  9468. // user-declared constructor for class X, a default constructor is
  9469. // implicitly declared. An implicitly-declared default constructor
  9470. // is an inline public member of its class.
  9471. assert(ClassDecl->needsImplicitDefaultConstructor() &&
  9472. "Should not build implicit default constructor!");
  9473. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
  9474. if (DSM.isAlreadyBeingDeclared())
  9475. return nullptr;
  9476. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  9477. CXXDefaultConstructor,
  9478. false);
  9479. // Create the actual constructor declaration.
  9480. CanQualType ClassType
  9481. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  9482. SourceLocation ClassLoc = ClassDecl->getLocation();
  9483. DeclarationName Name
  9484. = Context.DeclarationNames.getCXXConstructorName(ClassType);
  9485. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9486. CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
  9487. Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
  9488. /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
  9489. /*isImplicitlyDeclared=*/true, Constexpr);
  9490. DefaultCon->setAccess(AS_public);
  9491. DefaultCon->setDefaulted();
  9492. if (getLangOpts().CUDA) {
  9493. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
  9494. DefaultCon,
  9495. /* ConstRHS */ false,
  9496. /* Diagnose */ false);
  9497. }
  9498. // Build an exception specification pointing back at this constructor.
  9499. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
  9500. DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  9501. // We don't need to use SpecialMemberIsTrivial here; triviality for default
  9502. // constructors is easy to compute.
  9503. DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
  9504. // Note that we have declared this constructor.
  9505. ++ASTContext::NumImplicitDefaultConstructorsDeclared;
  9506. Scope *S = getScopeForContext(ClassDecl);
  9507. CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
  9508. if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
  9509. SetDeclDeleted(DefaultCon, ClassLoc);
  9510. if (S)
  9511. PushOnScopeChains(DefaultCon, S, false);
  9512. ClassDecl->addDecl(DefaultCon);
  9513. return DefaultCon;
  9514. }
  9515. void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
  9516. CXXConstructorDecl *Constructor) {
  9517. assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  9518. !Constructor->doesThisDeclarationHaveABody() &&
  9519. !Constructor->isDeleted()) &&
  9520. "DefineImplicitDefaultConstructor - call it for implicit default ctor");
  9521. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  9522. return;
  9523. CXXRecordDecl *ClassDecl = Constructor->getParent();
  9524. assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
  9525. SynthesizedFunctionScope Scope(*this, Constructor);
  9526. // The exception specification is needed because we are defining the
  9527. // function.
  9528. ResolveExceptionSpec(CurrentLocation,
  9529. Constructor->getType()->castAs<FunctionProtoType>());
  9530. MarkVTableUsed(CurrentLocation, ClassDecl);
  9531. // Add a context note for diagnostics produced after this point.
  9532. Scope.addContextNote(CurrentLocation);
  9533. if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
  9534. Constructor->setInvalidDecl();
  9535. return;
  9536. }
  9537. SourceLocation Loc = Constructor->getEndLoc().isValid()
  9538. ? Constructor->getEndLoc()
  9539. : Constructor->getLocation();
  9540. Constructor->setBody(new (Context) CompoundStmt(Loc));
  9541. Constructor->markUsed(Context);
  9542. if (ASTMutationListener *L = getASTMutationListener()) {
  9543. L->CompletedImplicitDefinition(Constructor);
  9544. }
  9545. DiagnoseUninitializedFields(*this, Constructor);
  9546. }
  9547. void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
  9548. // Perform any delayed checks on exception specifications.
  9549. CheckDelayedMemberExceptionSpecs();
  9550. }
  9551. /// Find or create the fake constructor we synthesize to model constructing an
  9552. /// object of a derived class via a constructor of a base class.
  9553. CXXConstructorDecl *
  9554. Sema::findInheritingConstructor(SourceLocation Loc,
  9555. CXXConstructorDecl *BaseCtor,
  9556. ConstructorUsingShadowDecl *Shadow) {
  9557. CXXRecordDecl *Derived = Shadow->getParent();
  9558. SourceLocation UsingLoc = Shadow->getLocation();
  9559. // FIXME: Add a new kind of DeclarationName for an inherited constructor.
  9560. // For now we use the name of the base class constructor as a member of the
  9561. // derived class to indicate a (fake) inherited constructor name.
  9562. DeclarationName Name = BaseCtor->getDeclName();
  9563. // Check to see if we already have a fake constructor for this inherited
  9564. // constructor call.
  9565. for (NamedDecl *Ctor : Derived->lookup(Name))
  9566. if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
  9567. ->getInheritedConstructor()
  9568. .getConstructor(),
  9569. BaseCtor))
  9570. return cast<CXXConstructorDecl>(Ctor);
  9571. DeclarationNameInfo NameInfo(Name, UsingLoc);
  9572. TypeSourceInfo *TInfo =
  9573. Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
  9574. FunctionProtoTypeLoc ProtoLoc =
  9575. TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
  9576. // Check the inherited constructor is valid and find the list of base classes
  9577. // from which it was inherited.
  9578. InheritedConstructorInfo ICI(*this, Loc, Shadow);
  9579. bool Constexpr =
  9580. BaseCtor->isConstexpr() &&
  9581. defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
  9582. false, BaseCtor, &ICI);
  9583. CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
  9584. Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
  9585. BaseCtor->isExplicit(), /*Inline=*/true,
  9586. /*ImplicitlyDeclared=*/true, Constexpr,
  9587. InheritedConstructor(Shadow, BaseCtor));
  9588. if (Shadow->isInvalidDecl())
  9589. DerivedCtor->setInvalidDecl();
  9590. // Build an unevaluated exception specification for this fake constructor.
  9591. const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
  9592. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9593. EPI.ExceptionSpec.Type = EST_Unevaluated;
  9594. EPI.ExceptionSpec.SourceDecl = DerivedCtor;
  9595. DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
  9596. FPT->getParamTypes(), EPI));
  9597. // Build the parameter declarations.
  9598. SmallVector<ParmVarDecl *, 16> ParamDecls;
  9599. for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
  9600. TypeSourceInfo *TInfo =
  9601. Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
  9602. ParmVarDecl *PD = ParmVarDecl::Create(
  9603. Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
  9604. FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
  9605. PD->setScopeInfo(0, I);
  9606. PD->setImplicit();
  9607. // Ensure attributes are propagated onto parameters (this matters for
  9608. // format, pass_object_size, ...).
  9609. mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
  9610. ParamDecls.push_back(PD);
  9611. ProtoLoc.setParam(I, PD);
  9612. }
  9613. // Set up the new constructor.
  9614. assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
  9615. DerivedCtor->setAccess(BaseCtor->getAccess());
  9616. DerivedCtor->setParams(ParamDecls);
  9617. Derived->addDecl(DerivedCtor);
  9618. if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
  9619. SetDeclDeleted(DerivedCtor, UsingLoc);
  9620. return DerivedCtor;
  9621. }
  9622. void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
  9623. InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
  9624. Ctor->getInheritedConstructor().getShadowDecl());
  9625. ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
  9626. /*Diagnose*/true);
  9627. }
  9628. void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
  9629. CXXConstructorDecl *Constructor) {
  9630. CXXRecordDecl *ClassDecl = Constructor->getParent();
  9631. assert(Constructor->getInheritedConstructor() &&
  9632. !Constructor->doesThisDeclarationHaveABody() &&
  9633. !Constructor->isDeleted());
  9634. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  9635. return;
  9636. // Initializations are performed "as if by a defaulted default constructor",
  9637. // so enter the appropriate scope.
  9638. SynthesizedFunctionScope Scope(*this, Constructor);
  9639. // The exception specification is needed because we are defining the
  9640. // function.
  9641. ResolveExceptionSpec(CurrentLocation,
  9642. Constructor->getType()->castAs<FunctionProtoType>());
  9643. MarkVTableUsed(CurrentLocation, ClassDecl);
  9644. // Add a context note for diagnostics produced after this point.
  9645. Scope.addContextNote(CurrentLocation);
  9646. ConstructorUsingShadowDecl *Shadow =
  9647. Constructor->getInheritedConstructor().getShadowDecl();
  9648. CXXConstructorDecl *InheritedCtor =
  9649. Constructor->getInheritedConstructor().getConstructor();
  9650. // [class.inhctor.init]p1:
  9651. // initialization proceeds as if a defaulted default constructor is used to
  9652. // initialize the D object and each base class subobject from which the
  9653. // constructor was inherited
  9654. InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
  9655. CXXRecordDecl *RD = Shadow->getParent();
  9656. SourceLocation InitLoc = Shadow->getLocation();
  9657. // Build explicit initializers for all base classes from which the
  9658. // constructor was inherited.
  9659. SmallVector<CXXCtorInitializer*, 8> Inits;
  9660. for (bool VBase : {false, true}) {
  9661. for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
  9662. if (B.isVirtual() != VBase)
  9663. continue;
  9664. auto *BaseRD = B.getType()->getAsCXXRecordDecl();
  9665. if (!BaseRD)
  9666. continue;
  9667. auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
  9668. if (!BaseCtor.first)
  9669. continue;
  9670. MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
  9671. ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
  9672. InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
  9673. auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
  9674. Inits.push_back(new (Context) CXXCtorInitializer(
  9675. Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
  9676. SourceLocation()));
  9677. }
  9678. }
  9679. // We now proceed as if for a defaulted default constructor, with the relevant
  9680. // initializers replaced.
  9681. if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
  9682. Constructor->setInvalidDecl();
  9683. return;
  9684. }
  9685. Constructor->setBody(new (Context) CompoundStmt(InitLoc));
  9686. Constructor->markUsed(Context);
  9687. if (ASTMutationListener *L = getASTMutationListener()) {
  9688. L->CompletedImplicitDefinition(Constructor);
  9689. }
  9690. DiagnoseUninitializedFields(*this, Constructor);
  9691. }
  9692. CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
  9693. // C++ [class.dtor]p2:
  9694. // If a class has no user-declared destructor, a destructor is
  9695. // declared implicitly. An implicitly-declared destructor is an
  9696. // inline public member of its class.
  9697. assert(ClassDecl->needsImplicitDestructor());
  9698. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
  9699. if (DSM.isAlreadyBeingDeclared())
  9700. return nullptr;
  9701. // Create the actual destructor declaration.
  9702. CanQualType ClassType
  9703. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  9704. SourceLocation ClassLoc = ClassDecl->getLocation();
  9705. DeclarationName Name
  9706. = Context.DeclarationNames.getCXXDestructorName(ClassType);
  9707. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9708. CXXDestructorDecl *Destructor
  9709. = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
  9710. QualType(), nullptr, /*isInline=*/true,
  9711. /*isImplicitlyDeclared=*/true);
  9712. Destructor->setAccess(AS_public);
  9713. Destructor->setDefaulted();
  9714. if (getLangOpts().CUDA) {
  9715. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
  9716. Destructor,
  9717. /* ConstRHS */ false,
  9718. /* Diagnose */ false);
  9719. }
  9720. // Build an exception specification pointing back at this destructor.
  9721. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
  9722. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  9723. // We don't need to use SpecialMemberIsTrivial here; triviality for
  9724. // destructors is easy to compute.
  9725. Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
  9726. Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
  9727. ClassDecl->hasTrivialDestructorForCall());
  9728. // Note that we have declared this destructor.
  9729. ++ASTContext::NumImplicitDestructorsDeclared;
  9730. Scope *S = getScopeForContext(ClassDecl);
  9731. CheckImplicitSpecialMemberDeclaration(S, Destructor);
  9732. // We can't check whether an implicit destructor is deleted before we complete
  9733. // the definition of the class, because its validity depends on the alignment
  9734. // of the class. We'll check this from ActOnFields once the class is complete.
  9735. if (ClassDecl->isCompleteDefinition() &&
  9736. ShouldDeleteSpecialMember(Destructor, CXXDestructor))
  9737. SetDeclDeleted(Destructor, ClassLoc);
  9738. // Introduce this destructor into its scope.
  9739. if (S)
  9740. PushOnScopeChains(Destructor, S, false);
  9741. ClassDecl->addDecl(Destructor);
  9742. return Destructor;
  9743. }
  9744. void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
  9745. CXXDestructorDecl *Destructor) {
  9746. assert((Destructor->isDefaulted() &&
  9747. !Destructor->doesThisDeclarationHaveABody() &&
  9748. !Destructor->isDeleted()) &&
  9749. "DefineImplicitDestructor - call it for implicit default dtor");
  9750. if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
  9751. return;
  9752. CXXRecordDecl *ClassDecl = Destructor->getParent();
  9753. assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
  9754. SynthesizedFunctionScope Scope(*this, Destructor);
  9755. // The exception specification is needed because we are defining the
  9756. // function.
  9757. ResolveExceptionSpec(CurrentLocation,
  9758. Destructor->getType()->castAs<FunctionProtoType>());
  9759. MarkVTableUsed(CurrentLocation, ClassDecl);
  9760. // Add a context note for diagnostics produced after this point.
  9761. Scope.addContextNote(CurrentLocation);
  9762. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  9763. Destructor->getParent());
  9764. if (CheckDestructor(Destructor)) {
  9765. Destructor->setInvalidDecl();
  9766. return;
  9767. }
  9768. SourceLocation Loc = Destructor->getEndLoc().isValid()
  9769. ? Destructor->getEndLoc()
  9770. : Destructor->getLocation();
  9771. Destructor->setBody(new (Context) CompoundStmt(Loc));
  9772. Destructor->markUsed(Context);
  9773. if (ASTMutationListener *L = getASTMutationListener()) {
  9774. L->CompletedImplicitDefinition(Destructor);
  9775. }
  9776. }
  9777. /// Perform any semantic analysis which needs to be delayed until all
  9778. /// pending class member declarations have been parsed.
  9779. void Sema::ActOnFinishCXXMemberDecls() {
  9780. // If the context is an invalid C++ class, just suppress these checks.
  9781. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
  9782. if (Record->isInvalidDecl()) {
  9783. DelayedOverridingExceptionSpecChecks.clear();
  9784. DelayedEquivalentExceptionSpecChecks.clear();
  9785. DelayedDefaultedMemberExceptionSpecs.clear();
  9786. return;
  9787. }
  9788. checkForMultipleExportedDefaultConstructors(*this, Record);
  9789. }
  9790. }
  9791. void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
  9792. referenceDLLExportedClassMethods();
  9793. }
  9794. void Sema::referenceDLLExportedClassMethods() {
  9795. if (!DelayedDllExportClasses.empty()) {
  9796. // Calling ReferenceDllExportedMembers might cause the current function to
  9797. // be called again, so use a local copy of DelayedDllExportClasses.
  9798. SmallVector<CXXRecordDecl *, 4> WorkList;
  9799. std::swap(DelayedDllExportClasses, WorkList);
  9800. for (CXXRecordDecl *Class : WorkList)
  9801. ReferenceDllExportedMembers(*this, Class);
  9802. }
  9803. }
  9804. void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
  9805. assert(getLangOpts().CPlusPlus11 &&
  9806. "adjusting dtor exception specs was introduced in c++11");
  9807. if (Destructor->isDependentContext())
  9808. return;
  9809. // C++11 [class.dtor]p3:
  9810. // A declaration of a destructor that does not have an exception-
  9811. // specification is implicitly considered to have the same exception-
  9812. // specification as an implicit declaration.
  9813. const FunctionProtoType *DtorType = Destructor->getType()->
  9814. getAs<FunctionProtoType>();
  9815. if (DtorType->hasExceptionSpec())
  9816. return;
  9817. // Replace the destructor's type, building off the existing one. Fortunately,
  9818. // the only thing of interest in the destructor type is its extended info.
  9819. // The return and arguments are fixed.
  9820. FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
  9821. EPI.ExceptionSpec.Type = EST_Unevaluated;
  9822. EPI.ExceptionSpec.SourceDecl = Destructor;
  9823. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  9824. // FIXME: If the destructor has a body that could throw, and the newly created
  9825. // spec doesn't allow exceptions, we should emit a warning, because this
  9826. // change in behavior can break conforming C++03 programs at runtime.
  9827. // However, we don't have a body or an exception specification yet, so it
  9828. // needs to be done somewhere else.
  9829. }
  9830. namespace {
  9831. /// An abstract base class for all helper classes used in building the
  9832. // copy/move operators. These classes serve as factory functions and help us
  9833. // avoid using the same Expr* in the AST twice.
  9834. class ExprBuilder {
  9835. ExprBuilder(const ExprBuilder&) = delete;
  9836. ExprBuilder &operator=(const ExprBuilder&) = delete;
  9837. protected:
  9838. static Expr *assertNotNull(Expr *E) {
  9839. assert(E && "Expression construction must not fail.");
  9840. return E;
  9841. }
  9842. public:
  9843. ExprBuilder() {}
  9844. virtual ~ExprBuilder() {}
  9845. virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
  9846. };
  9847. class RefBuilder: public ExprBuilder {
  9848. VarDecl *Var;
  9849. QualType VarType;
  9850. public:
  9851. Expr *build(Sema &S, SourceLocation Loc) const override {
  9852. return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
  9853. }
  9854. RefBuilder(VarDecl *Var, QualType VarType)
  9855. : Var(Var), VarType(VarType) {}
  9856. };
  9857. class ThisBuilder: public ExprBuilder {
  9858. public:
  9859. Expr *build(Sema &S, SourceLocation Loc) const override {
  9860. return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
  9861. }
  9862. };
  9863. class CastBuilder: public ExprBuilder {
  9864. const ExprBuilder &Builder;
  9865. QualType Type;
  9866. ExprValueKind Kind;
  9867. const CXXCastPath &Path;
  9868. public:
  9869. Expr *build(Sema &S, SourceLocation Loc) const override {
  9870. return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
  9871. CK_UncheckedDerivedToBase, Kind,
  9872. &Path).get());
  9873. }
  9874. CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
  9875. const CXXCastPath &Path)
  9876. : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
  9877. };
  9878. class DerefBuilder: public ExprBuilder {
  9879. const ExprBuilder &Builder;
  9880. public:
  9881. Expr *build(Sema &S, SourceLocation Loc) const override {
  9882. return assertNotNull(
  9883. S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
  9884. }
  9885. DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  9886. };
  9887. class MemberBuilder: public ExprBuilder {
  9888. const ExprBuilder &Builder;
  9889. QualType Type;
  9890. CXXScopeSpec SS;
  9891. bool IsArrow;
  9892. LookupResult &MemberLookup;
  9893. public:
  9894. Expr *build(Sema &S, SourceLocation Loc) const override {
  9895. return assertNotNull(S.BuildMemberReferenceExpr(
  9896. Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
  9897. nullptr, MemberLookup, nullptr, nullptr).get());
  9898. }
  9899. MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
  9900. LookupResult &MemberLookup)
  9901. : Builder(Builder), Type(Type), IsArrow(IsArrow),
  9902. MemberLookup(MemberLookup) {}
  9903. };
  9904. class MoveCastBuilder: public ExprBuilder {
  9905. const ExprBuilder &Builder;
  9906. public:
  9907. Expr *build(Sema &S, SourceLocation Loc) const override {
  9908. return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
  9909. }
  9910. MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  9911. };
  9912. class LvalueConvBuilder: public ExprBuilder {
  9913. const ExprBuilder &Builder;
  9914. public:
  9915. Expr *build(Sema &S, SourceLocation Loc) const override {
  9916. return assertNotNull(
  9917. S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
  9918. }
  9919. LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  9920. };
  9921. class SubscriptBuilder: public ExprBuilder {
  9922. const ExprBuilder &Base;
  9923. const ExprBuilder &Index;
  9924. public:
  9925. Expr *build(Sema &S, SourceLocation Loc) const override {
  9926. return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
  9927. Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
  9928. }
  9929. SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
  9930. : Base(Base), Index(Index) {}
  9931. };
  9932. } // end anonymous namespace
  9933. /// When generating a defaulted copy or move assignment operator, if a field
  9934. /// should be copied with __builtin_memcpy rather than via explicit assignments,
  9935. /// do so. This optimization only applies for arrays of scalars, and for arrays
  9936. /// of class type where the selected copy/move-assignment operator is trivial.
  9937. static StmtResult
  9938. buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
  9939. const ExprBuilder &ToB, const ExprBuilder &FromB) {
  9940. // Compute the size of the memory buffer to be copied.
  9941. QualType SizeType = S.Context.getSizeType();
  9942. llvm::APInt Size(S.Context.getTypeSize(SizeType),
  9943. S.Context.getTypeSizeInChars(T).getQuantity());
  9944. // Take the address of the field references for "from" and "to". We
  9945. // directly construct UnaryOperators here because semantic analysis
  9946. // does not permit us to take the address of an xvalue.
  9947. Expr *From = FromB.build(S, Loc);
  9948. From = new (S.Context) UnaryOperator(From, UO_AddrOf,
  9949. S.Context.getPointerType(From->getType()),
  9950. VK_RValue, OK_Ordinary, Loc, false);
  9951. Expr *To = ToB.build(S, Loc);
  9952. To = new (S.Context) UnaryOperator(To, UO_AddrOf,
  9953. S.Context.getPointerType(To->getType()),
  9954. VK_RValue, OK_Ordinary, Loc, false);
  9955. const Type *E = T->getBaseElementTypeUnsafe();
  9956. bool NeedsCollectableMemCpy =
  9957. E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
  9958. // Create a reference to the __builtin_objc_memmove_collectable function
  9959. StringRef MemCpyName = NeedsCollectableMemCpy ?
  9960. "__builtin_objc_memmove_collectable" :
  9961. "__builtin_memcpy";
  9962. LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
  9963. Sema::LookupOrdinaryName);
  9964. S.LookupName(R, S.TUScope, true);
  9965. FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
  9966. if (!MemCpy)
  9967. // Something went horribly wrong earlier, and we will have complained
  9968. // about it.
  9969. return StmtError();
  9970. ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
  9971. VK_RValue, Loc, nullptr);
  9972. assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
  9973. Expr *CallArgs[] = {
  9974. To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
  9975. };
  9976. ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
  9977. Loc, CallArgs, Loc);
  9978. assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
  9979. return Call.getAs<Stmt>();
  9980. }
  9981. /// Builds a statement that copies/moves the given entity from \p From to
  9982. /// \c To.
  9983. ///
  9984. /// This routine is used to copy/move the members of a class with an
  9985. /// implicitly-declared copy/move assignment operator. When the entities being
  9986. /// copied are arrays, this routine builds for loops to copy them.
  9987. ///
  9988. /// \param S The Sema object used for type-checking.
  9989. ///
  9990. /// \param Loc The location where the implicit copy/move is being generated.
  9991. ///
  9992. /// \param T The type of the expressions being copied/moved. Both expressions
  9993. /// must have this type.
  9994. ///
  9995. /// \param To The expression we are copying/moving to.
  9996. ///
  9997. /// \param From The expression we are copying/moving from.
  9998. ///
  9999. /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
  10000. /// Otherwise, it's a non-static member subobject.
  10001. ///
  10002. /// \param Copying Whether we're copying or moving.
  10003. ///
  10004. /// \param Depth Internal parameter recording the depth of the recursion.
  10005. ///
  10006. /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
  10007. /// if a memcpy should be used instead.
  10008. static StmtResult
  10009. buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
  10010. const ExprBuilder &To, const ExprBuilder &From,
  10011. bool CopyingBaseSubobject, bool Copying,
  10012. unsigned Depth = 0) {
  10013. // C++11 [class.copy]p28:
  10014. // Each subobject is assigned in the manner appropriate to its type:
  10015. //
  10016. // - if the subobject is of class type, as if by a call to operator= with
  10017. // the subobject as the object expression and the corresponding
  10018. // subobject of x as a single function argument (as if by explicit
  10019. // qualification; that is, ignoring any possible virtual overriding
  10020. // functions in more derived classes);
  10021. //
  10022. // C++03 [class.copy]p13:
  10023. // - if the subobject is of class type, the copy assignment operator for
  10024. // the class is used (as if by explicit qualification; that is,
  10025. // ignoring any possible virtual overriding functions in more derived
  10026. // classes);
  10027. if (const RecordType *RecordTy = T->getAs<RecordType>()) {
  10028. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  10029. // Look for operator=.
  10030. DeclarationName Name
  10031. = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10032. LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
  10033. S.LookupQualifiedName(OpLookup, ClassDecl, false);
  10034. // Prior to C++11, filter out any result that isn't a copy/move-assignment
  10035. // operator.
  10036. if (!S.getLangOpts().CPlusPlus11) {
  10037. LookupResult::Filter F = OpLookup.makeFilter();
  10038. while (F.hasNext()) {
  10039. NamedDecl *D = F.next();
  10040. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  10041. if (Method->isCopyAssignmentOperator() ||
  10042. (!Copying && Method->isMoveAssignmentOperator()))
  10043. continue;
  10044. F.erase();
  10045. }
  10046. F.done();
  10047. }
  10048. // Suppress the protected check (C++ [class.protected]) for each of the
  10049. // assignment operators we found. This strange dance is required when
  10050. // we're assigning via a base classes's copy-assignment operator. To
  10051. // ensure that we're getting the right base class subobject (without
  10052. // ambiguities), we need to cast "this" to that subobject type; to
  10053. // ensure that we don't go through the virtual call mechanism, we need
  10054. // to qualify the operator= name with the base class (see below). However,
  10055. // this means that if the base class has a protected copy assignment
  10056. // operator, the protected member access check will fail. So, we
  10057. // rewrite "protected" access to "public" access in this case, since we
  10058. // know by construction that we're calling from a derived class.
  10059. if (CopyingBaseSubobject) {
  10060. for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
  10061. L != LEnd; ++L) {
  10062. if (L.getAccess() == AS_protected)
  10063. L.setAccess(AS_public);
  10064. }
  10065. }
  10066. // Create the nested-name-specifier that will be used to qualify the
  10067. // reference to operator=; this is required to suppress the virtual
  10068. // call mechanism.
  10069. CXXScopeSpec SS;
  10070. const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
  10071. SS.MakeTrivial(S.Context,
  10072. NestedNameSpecifier::Create(S.Context, nullptr, false,
  10073. CanonicalT),
  10074. Loc);
  10075. // Create the reference to operator=.
  10076. ExprResult OpEqualRef
  10077. = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
  10078. SS, /*TemplateKWLoc=*/SourceLocation(),
  10079. /*FirstQualifierInScope=*/nullptr,
  10080. OpLookup,
  10081. /*TemplateArgs=*/nullptr, /*S*/nullptr,
  10082. /*SuppressQualifierCheck=*/true);
  10083. if (OpEqualRef.isInvalid())
  10084. return StmtError();
  10085. // Build the call to the assignment operator.
  10086. Expr *FromInst = From.build(S, Loc);
  10087. ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
  10088. OpEqualRef.getAs<Expr>(),
  10089. Loc, FromInst, Loc);
  10090. if (Call.isInvalid())
  10091. return StmtError();
  10092. // If we built a call to a trivial 'operator=' while copying an array,
  10093. // bail out. We'll replace the whole shebang with a memcpy.
  10094. CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
  10095. if (CE && CE->getMethodDecl()->isTrivial() && Depth)
  10096. return StmtResult((Stmt*)nullptr);
  10097. // Convert to an expression-statement, and clean up any produced
  10098. // temporaries.
  10099. return S.ActOnExprStmt(Call);
  10100. }
  10101. // - if the subobject is of scalar type, the built-in assignment
  10102. // operator is used.
  10103. const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
  10104. if (!ArrayTy) {
  10105. ExprResult Assignment = S.CreateBuiltinBinOp(
  10106. Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
  10107. if (Assignment.isInvalid())
  10108. return StmtError();
  10109. return S.ActOnExprStmt(Assignment);
  10110. }
  10111. // - if the subobject is an array, each element is assigned, in the
  10112. // manner appropriate to the element type;
  10113. // Construct a loop over the array bounds, e.g.,
  10114. //
  10115. // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
  10116. //
  10117. // that will copy each of the array elements.
  10118. QualType SizeType = S.Context.getSizeType();
  10119. // Create the iteration variable.
  10120. IdentifierInfo *IterationVarName = nullptr;
  10121. {
  10122. SmallString<8> Str;
  10123. llvm::raw_svector_ostream OS(Str);
  10124. OS << "__i" << Depth;
  10125. IterationVarName = &S.Context.Idents.get(OS.str());
  10126. }
  10127. VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  10128. IterationVarName, SizeType,
  10129. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  10130. SC_None);
  10131. // Initialize the iteration variable to zero.
  10132. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  10133. IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  10134. // Creates a reference to the iteration variable.
  10135. RefBuilder IterationVarRef(IterationVar, SizeType);
  10136. LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
  10137. // Create the DeclStmt that holds the iteration variable.
  10138. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
  10139. // Subscript the "from" and "to" expressions with the iteration variable.
  10140. SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
  10141. MoveCastBuilder FromIndexMove(FromIndexCopy);
  10142. const ExprBuilder *FromIndex;
  10143. if (Copying)
  10144. FromIndex = &FromIndexCopy;
  10145. else
  10146. FromIndex = &FromIndexMove;
  10147. SubscriptBuilder ToIndex(To, IterationVarRefRVal);
  10148. // Build the copy/move for an individual element of the array.
  10149. StmtResult Copy =
  10150. buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
  10151. ToIndex, *FromIndex, CopyingBaseSubobject,
  10152. Copying, Depth + 1);
  10153. // Bail out if copying fails or if we determined that we should use memcpy.
  10154. if (Copy.isInvalid() || !Copy.get())
  10155. return Copy;
  10156. // Create the comparison against the array bound.
  10157. llvm::APInt Upper
  10158. = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
  10159. Expr *Comparison
  10160. = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
  10161. IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
  10162. BO_NE, S.Context.BoolTy,
  10163. VK_RValue, OK_Ordinary, Loc, FPOptions());
  10164. // Create the pre-increment of the iteration variable. We can determine
  10165. // whether the increment will overflow based on the value of the array
  10166. // bound.
  10167. Expr *Increment = new (S.Context)
  10168. UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
  10169. VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
  10170. // Construct the loop that copies all elements of this array.
  10171. return S.ActOnForStmt(
  10172. Loc, Loc, InitStmt,
  10173. S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
  10174. S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
  10175. }
  10176. static StmtResult
  10177. buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
  10178. const ExprBuilder &To, const ExprBuilder &From,
  10179. bool CopyingBaseSubobject, bool Copying) {
  10180. // Maybe we should use a memcpy?
  10181. if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
  10182. T.isTriviallyCopyableType(S.Context))
  10183. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  10184. StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
  10185. CopyingBaseSubobject,
  10186. Copying, 0));
  10187. // If we ended up picking a trivial assignment operator for an array of a
  10188. // non-trivially-copyable class type, just emit a memcpy.
  10189. if (!Result.isInvalid() && !Result.get())
  10190. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  10191. return Result;
  10192. }
  10193. CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
  10194. // Note: The following rules are largely analoguous to the copy
  10195. // constructor rules. Note that virtual bases are not taken into account
  10196. // for determining the argument type of the operator. Note also that
  10197. // operators taking an object instead of a reference are allowed.
  10198. assert(ClassDecl->needsImplicitCopyAssignment());
  10199. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
  10200. if (DSM.isAlreadyBeingDeclared())
  10201. return nullptr;
  10202. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  10203. QualType RetType = Context.getLValueReferenceType(ArgType);
  10204. bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
  10205. if (Const)
  10206. ArgType = ArgType.withConst();
  10207. ArgType = Context.getLValueReferenceType(ArgType);
  10208. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10209. CXXCopyAssignment,
  10210. Const);
  10211. // An implicitly-declared copy assignment operator is an inline public
  10212. // member of its class.
  10213. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10214. SourceLocation ClassLoc = ClassDecl->getLocation();
  10215. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10216. CXXMethodDecl *CopyAssignment =
  10217. CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  10218. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  10219. /*isInline=*/true, Constexpr, SourceLocation());
  10220. CopyAssignment->setAccess(AS_public);
  10221. CopyAssignment->setDefaulted();
  10222. CopyAssignment->setImplicit();
  10223. if (getLangOpts().CUDA) {
  10224. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
  10225. CopyAssignment,
  10226. /* ConstRHS */ Const,
  10227. /* Diagnose */ false);
  10228. }
  10229. // Build an exception specification pointing back at this member.
  10230. FunctionProtoType::ExtProtoInfo EPI =
  10231. getImplicitMethodEPI(*this, CopyAssignment);
  10232. CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
  10233. // Add the parameter to the operator.
  10234. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
  10235. ClassLoc, ClassLoc,
  10236. /*Id=*/nullptr, ArgType,
  10237. /*TInfo=*/nullptr, SC_None,
  10238. nullptr);
  10239. CopyAssignment->setParams(FromParam);
  10240. CopyAssignment->setTrivial(
  10241. ClassDecl->needsOverloadResolutionForCopyAssignment()
  10242. ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
  10243. : ClassDecl->hasTrivialCopyAssignment());
  10244. // Note that we have added this copy-assignment operator.
  10245. ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
  10246. Scope *S = getScopeForContext(ClassDecl);
  10247. CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
  10248. if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
  10249. SetDeclDeleted(CopyAssignment, ClassLoc);
  10250. if (S)
  10251. PushOnScopeChains(CopyAssignment, S, false);
  10252. ClassDecl->addDecl(CopyAssignment);
  10253. return CopyAssignment;
  10254. }
  10255. /// Diagnose an implicit copy operation for a class which is odr-used, but
  10256. /// which is deprecated because the class has a user-declared copy constructor,
  10257. /// copy assignment operator, or destructor.
  10258. static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
  10259. assert(CopyOp->isImplicit());
  10260. CXXRecordDecl *RD = CopyOp->getParent();
  10261. CXXMethodDecl *UserDeclaredOperation = nullptr;
  10262. // In Microsoft mode, assignment operations don't affect constructors and
  10263. // vice versa.
  10264. if (RD->hasUserDeclaredDestructor()) {
  10265. UserDeclaredOperation = RD->getDestructor();
  10266. } else if (!isa<CXXConstructorDecl>(CopyOp) &&
  10267. RD->hasUserDeclaredCopyConstructor() &&
  10268. !S.getLangOpts().MSVCCompat) {
  10269. // Find any user-declared copy constructor.
  10270. for (auto *I : RD->ctors()) {
  10271. if (I->isCopyConstructor()) {
  10272. UserDeclaredOperation = I;
  10273. break;
  10274. }
  10275. }
  10276. assert(UserDeclaredOperation);
  10277. } else if (isa<CXXConstructorDecl>(CopyOp) &&
  10278. RD->hasUserDeclaredCopyAssignment() &&
  10279. !S.getLangOpts().MSVCCompat) {
  10280. // Find any user-declared move assignment operator.
  10281. for (auto *I : RD->methods()) {
  10282. if (I->isCopyAssignmentOperator()) {
  10283. UserDeclaredOperation = I;
  10284. break;
  10285. }
  10286. }
  10287. assert(UserDeclaredOperation);
  10288. }
  10289. if (UserDeclaredOperation) {
  10290. S.Diag(UserDeclaredOperation->getLocation(),
  10291. diag::warn_deprecated_copy_operation)
  10292. << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
  10293. << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
  10294. }
  10295. }
  10296. void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
  10297. CXXMethodDecl *CopyAssignOperator) {
  10298. assert((CopyAssignOperator->isDefaulted() &&
  10299. CopyAssignOperator->isOverloadedOperator() &&
  10300. CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
  10301. !CopyAssignOperator->doesThisDeclarationHaveABody() &&
  10302. !CopyAssignOperator->isDeleted()) &&
  10303. "DefineImplicitCopyAssignment called for wrong function");
  10304. if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
  10305. return;
  10306. CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
  10307. if (ClassDecl->isInvalidDecl()) {
  10308. CopyAssignOperator->setInvalidDecl();
  10309. return;
  10310. }
  10311. SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
  10312. // The exception specification is needed because we are defining the
  10313. // function.
  10314. ResolveExceptionSpec(CurrentLocation,
  10315. CopyAssignOperator->getType()->castAs<FunctionProtoType>());
  10316. // Add a context note for diagnostics produced after this point.
  10317. Scope.addContextNote(CurrentLocation);
  10318. // C++11 [class.copy]p18:
  10319. // The [definition of an implicitly declared copy assignment operator] is
  10320. // deprecated if the class has a user-declared copy constructor or a
  10321. // user-declared destructor.
  10322. if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
  10323. diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
  10324. // C++0x [class.copy]p30:
  10325. // The implicitly-defined or explicitly-defaulted copy assignment operator
  10326. // for a non-union class X performs memberwise copy assignment of its
  10327. // subobjects. The direct base classes of X are assigned first, in the
  10328. // order of their declaration in the base-specifier-list, and then the
  10329. // immediate non-static data members of X are assigned, in the order in
  10330. // which they were declared in the class definition.
  10331. // The statements that form the synthesized function body.
  10332. SmallVector<Stmt*, 8> Statements;
  10333. // The parameter for the "other" object, which we are copying from.
  10334. ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
  10335. Qualifiers OtherQuals = Other->getType().getQualifiers();
  10336. QualType OtherRefType = Other->getType();
  10337. if (const LValueReferenceType *OtherRef
  10338. = OtherRefType->getAs<LValueReferenceType>()) {
  10339. OtherRefType = OtherRef->getPointeeType();
  10340. OtherQuals = OtherRefType.getQualifiers();
  10341. }
  10342. // Our location for everything implicitly-generated.
  10343. SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
  10344. ? CopyAssignOperator->getEndLoc()
  10345. : CopyAssignOperator->getLocation();
  10346. // Builds a DeclRefExpr for the "other" object.
  10347. RefBuilder OtherRef(Other, OtherRefType);
  10348. // Builds the "this" pointer.
  10349. ThisBuilder This;
  10350. // Assign base classes.
  10351. bool Invalid = false;
  10352. for (auto &Base : ClassDecl->bases()) {
  10353. // Form the assignment:
  10354. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
  10355. QualType BaseType = Base.getType().getUnqualifiedType();
  10356. if (!BaseType->isRecordType()) {
  10357. Invalid = true;
  10358. continue;
  10359. }
  10360. CXXCastPath BasePath;
  10361. BasePath.push_back(&Base);
  10362. // Construct the "from" expression, which is an implicit cast to the
  10363. // appropriately-qualified base type.
  10364. CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
  10365. VK_LValue, BasePath);
  10366. // Dereference "this".
  10367. DerefBuilder DerefThis(This);
  10368. CastBuilder To(DerefThis,
  10369. Context.getCVRQualifiedType(
  10370. BaseType, CopyAssignOperator->getTypeQualifiers()),
  10371. VK_LValue, BasePath);
  10372. // Build the copy.
  10373. StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
  10374. To, From,
  10375. /*CopyingBaseSubobject=*/true,
  10376. /*Copying=*/true);
  10377. if (Copy.isInvalid()) {
  10378. CopyAssignOperator->setInvalidDecl();
  10379. return;
  10380. }
  10381. // Success! Record the copy.
  10382. Statements.push_back(Copy.getAs<Expr>());
  10383. }
  10384. // Assign non-static members.
  10385. for (auto *Field : ClassDecl->fields()) {
  10386. // FIXME: We should form some kind of AST representation for the implied
  10387. // memcpy in a union copy operation.
  10388. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  10389. continue;
  10390. if (Field->isInvalidDecl()) {
  10391. Invalid = true;
  10392. continue;
  10393. }
  10394. // Check for members of reference type; we can't copy those.
  10395. if (Field->getType()->isReferenceType()) {
  10396. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10397. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  10398. Diag(Field->getLocation(), diag::note_declared_at);
  10399. Invalid = true;
  10400. continue;
  10401. }
  10402. // Check for members of const-qualified, non-class type.
  10403. QualType BaseType = Context.getBaseElementType(Field->getType());
  10404. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  10405. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10406. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  10407. Diag(Field->getLocation(), diag::note_declared_at);
  10408. Invalid = true;
  10409. continue;
  10410. }
  10411. // Suppress assigning zero-width bitfields.
  10412. if (Field->isZeroLengthBitField(Context))
  10413. continue;
  10414. QualType FieldType = Field->getType().getNonReferenceType();
  10415. if (FieldType->isIncompleteArrayType()) {
  10416. assert(ClassDecl->hasFlexibleArrayMember() &&
  10417. "Incomplete array type is not valid");
  10418. continue;
  10419. }
  10420. // Build references to the field in the object we're copying from and to.
  10421. CXXScopeSpec SS; // Intentionally empty
  10422. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  10423. LookupMemberName);
  10424. MemberLookup.addDecl(Field);
  10425. MemberLookup.resolveKind();
  10426. MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
  10427. MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
  10428. // Build the copy of this field.
  10429. StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
  10430. To, From,
  10431. /*CopyingBaseSubobject=*/false,
  10432. /*Copying=*/true);
  10433. if (Copy.isInvalid()) {
  10434. CopyAssignOperator->setInvalidDecl();
  10435. return;
  10436. }
  10437. // Success! Record the copy.
  10438. Statements.push_back(Copy.getAs<Stmt>());
  10439. }
  10440. if (!Invalid) {
  10441. // Add a "return *this;"
  10442. ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  10443. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  10444. if (Return.isInvalid())
  10445. Invalid = true;
  10446. else
  10447. Statements.push_back(Return.getAs<Stmt>());
  10448. }
  10449. if (Invalid) {
  10450. CopyAssignOperator->setInvalidDecl();
  10451. return;
  10452. }
  10453. StmtResult Body;
  10454. {
  10455. CompoundScopeRAII CompoundScope(*this);
  10456. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  10457. /*isStmtExpr=*/false);
  10458. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  10459. }
  10460. CopyAssignOperator->setBody(Body.getAs<Stmt>());
  10461. CopyAssignOperator->markUsed(Context);
  10462. if (ASTMutationListener *L = getASTMutationListener()) {
  10463. L->CompletedImplicitDefinition(CopyAssignOperator);
  10464. }
  10465. }
  10466. CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
  10467. assert(ClassDecl->needsImplicitMoveAssignment());
  10468. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
  10469. if (DSM.isAlreadyBeingDeclared())
  10470. return nullptr;
  10471. // Note: The following rules are largely analoguous to the move
  10472. // constructor rules.
  10473. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  10474. QualType RetType = Context.getLValueReferenceType(ArgType);
  10475. ArgType = Context.getRValueReferenceType(ArgType);
  10476. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10477. CXXMoveAssignment,
  10478. false);
  10479. // An implicitly-declared move assignment operator is an inline public
  10480. // member of its class.
  10481. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10482. SourceLocation ClassLoc = ClassDecl->getLocation();
  10483. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10484. CXXMethodDecl *MoveAssignment =
  10485. CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  10486. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  10487. /*isInline=*/true, Constexpr, SourceLocation());
  10488. MoveAssignment->setAccess(AS_public);
  10489. MoveAssignment->setDefaulted();
  10490. MoveAssignment->setImplicit();
  10491. if (getLangOpts().CUDA) {
  10492. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
  10493. MoveAssignment,
  10494. /* ConstRHS */ false,
  10495. /* Diagnose */ false);
  10496. }
  10497. // Build an exception specification pointing back at this member.
  10498. FunctionProtoType::ExtProtoInfo EPI =
  10499. getImplicitMethodEPI(*this, MoveAssignment);
  10500. MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
  10501. // Add the parameter to the operator.
  10502. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
  10503. ClassLoc, ClassLoc,
  10504. /*Id=*/nullptr, ArgType,
  10505. /*TInfo=*/nullptr, SC_None,
  10506. nullptr);
  10507. MoveAssignment->setParams(FromParam);
  10508. MoveAssignment->setTrivial(
  10509. ClassDecl->needsOverloadResolutionForMoveAssignment()
  10510. ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
  10511. : ClassDecl->hasTrivialMoveAssignment());
  10512. // Note that we have added this copy-assignment operator.
  10513. ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
  10514. Scope *S = getScopeForContext(ClassDecl);
  10515. CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
  10516. if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
  10517. ClassDecl->setImplicitMoveAssignmentIsDeleted();
  10518. SetDeclDeleted(MoveAssignment, ClassLoc);
  10519. }
  10520. if (S)
  10521. PushOnScopeChains(MoveAssignment, S, false);
  10522. ClassDecl->addDecl(MoveAssignment);
  10523. return MoveAssignment;
  10524. }
  10525. /// Check if we're implicitly defining a move assignment operator for a class
  10526. /// with virtual bases. Such a move assignment might move-assign the virtual
  10527. /// base multiple times.
  10528. static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
  10529. SourceLocation CurrentLocation) {
  10530. assert(!Class->isDependentContext() && "should not define dependent move");
  10531. // Only a virtual base could get implicitly move-assigned multiple times.
  10532. // Only a non-trivial move assignment can observe this. We only want to
  10533. // diagnose if we implicitly define an assignment operator that assigns
  10534. // two base classes, both of which move-assign the same virtual base.
  10535. if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
  10536. Class->getNumBases() < 2)
  10537. return;
  10538. llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
  10539. typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
  10540. VBaseMap VBases;
  10541. for (auto &BI : Class->bases()) {
  10542. Worklist.push_back(&BI);
  10543. while (!Worklist.empty()) {
  10544. CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
  10545. CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
  10546. // If the base has no non-trivial move assignment operators,
  10547. // we don't care about moves from it.
  10548. if (!Base->hasNonTrivialMoveAssignment())
  10549. continue;
  10550. // If there's nothing virtual here, skip it.
  10551. if (!BaseSpec->isVirtual() && !Base->getNumVBases())
  10552. continue;
  10553. // If we're not actually going to call a move assignment for this base,
  10554. // or the selected move assignment is trivial, skip it.
  10555. Sema::SpecialMemberOverloadResult SMOR =
  10556. S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
  10557. /*ConstArg*/false, /*VolatileArg*/false,
  10558. /*RValueThis*/true, /*ConstThis*/false,
  10559. /*VolatileThis*/false);
  10560. if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
  10561. !SMOR.getMethod()->isMoveAssignmentOperator())
  10562. continue;
  10563. if (BaseSpec->isVirtual()) {
  10564. // We're going to move-assign this virtual base, and its move
  10565. // assignment operator is not trivial. If this can happen for
  10566. // multiple distinct direct bases of Class, diagnose it. (If it
  10567. // only happens in one base, we'll diagnose it when synthesizing
  10568. // that base class's move assignment operator.)
  10569. CXXBaseSpecifier *&Existing =
  10570. VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
  10571. .first->second;
  10572. if (Existing && Existing != &BI) {
  10573. S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
  10574. << Class << Base;
  10575. S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
  10576. << (Base->getCanonicalDecl() ==
  10577. Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10578. << Base << Existing->getType() << Existing->getSourceRange();
  10579. S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
  10580. << (Base->getCanonicalDecl() ==
  10581. BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10582. << Base << BI.getType() << BaseSpec->getSourceRange();
  10583. // Only diagnose each vbase once.
  10584. Existing = nullptr;
  10585. }
  10586. } else {
  10587. // Only walk over bases that have defaulted move assignment operators.
  10588. // We assume that any user-provided move assignment operator handles
  10589. // the multiple-moves-of-vbase case itself somehow.
  10590. if (!SMOR.getMethod()->isDefaulted())
  10591. continue;
  10592. // We're going to move the base classes of Base. Add them to the list.
  10593. for (auto &BI : Base->bases())
  10594. Worklist.push_back(&BI);
  10595. }
  10596. }
  10597. }
  10598. }
  10599. void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
  10600. CXXMethodDecl *MoveAssignOperator) {
  10601. assert((MoveAssignOperator->isDefaulted() &&
  10602. MoveAssignOperator->isOverloadedOperator() &&
  10603. MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
  10604. !MoveAssignOperator->doesThisDeclarationHaveABody() &&
  10605. !MoveAssignOperator->isDeleted()) &&
  10606. "DefineImplicitMoveAssignment called for wrong function");
  10607. if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
  10608. return;
  10609. CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
  10610. if (ClassDecl->isInvalidDecl()) {
  10611. MoveAssignOperator->setInvalidDecl();
  10612. return;
  10613. }
  10614. // C++0x [class.copy]p28:
  10615. // The implicitly-defined or move assignment operator for a non-union class
  10616. // X performs memberwise move assignment of its subobjects. The direct base
  10617. // classes of X are assigned first, in the order of their declaration in the
  10618. // base-specifier-list, and then the immediate non-static data members of X
  10619. // are assigned, in the order in which they were declared in the class
  10620. // definition.
  10621. // Issue a warning if our implicit move assignment operator will move
  10622. // from a virtual base more than once.
  10623. checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
  10624. SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
  10625. // The exception specification is needed because we are defining the
  10626. // function.
  10627. ResolveExceptionSpec(CurrentLocation,
  10628. MoveAssignOperator->getType()->castAs<FunctionProtoType>());
  10629. // Add a context note for diagnostics produced after this point.
  10630. Scope.addContextNote(CurrentLocation);
  10631. // The statements that form the synthesized function body.
  10632. SmallVector<Stmt*, 8> Statements;
  10633. // The parameter for the "other" object, which we are move from.
  10634. ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
  10635. QualType OtherRefType = Other->getType()->
  10636. getAs<RValueReferenceType>()->getPointeeType();
  10637. assert(!OtherRefType.getQualifiers() &&
  10638. "Bad argument type of defaulted move assignment");
  10639. // Our location for everything implicitly-generated.
  10640. SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
  10641. ? MoveAssignOperator->getEndLoc()
  10642. : MoveAssignOperator->getLocation();
  10643. // Builds a reference to the "other" object.
  10644. RefBuilder OtherRef(Other, OtherRefType);
  10645. // Cast to rvalue.
  10646. MoveCastBuilder MoveOther(OtherRef);
  10647. // Builds the "this" pointer.
  10648. ThisBuilder This;
  10649. // Assign base classes.
  10650. bool Invalid = false;
  10651. for (auto &Base : ClassDecl->bases()) {
  10652. // C++11 [class.copy]p28:
  10653. // It is unspecified whether subobjects representing virtual base classes
  10654. // are assigned more than once by the implicitly-defined copy assignment
  10655. // operator.
  10656. // FIXME: Do not assign to a vbase that will be assigned by some other base
  10657. // class. For a move-assignment, this can result in the vbase being moved
  10658. // multiple times.
  10659. // Form the assignment:
  10660. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
  10661. QualType BaseType = Base.getType().getUnqualifiedType();
  10662. if (!BaseType->isRecordType()) {
  10663. Invalid = true;
  10664. continue;
  10665. }
  10666. CXXCastPath BasePath;
  10667. BasePath.push_back(&Base);
  10668. // Construct the "from" expression, which is an implicit cast to the
  10669. // appropriately-qualified base type.
  10670. CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
  10671. // Dereference "this".
  10672. DerefBuilder DerefThis(This);
  10673. // Implicitly cast "this" to the appropriately-qualified base type.
  10674. CastBuilder To(DerefThis,
  10675. Context.getCVRQualifiedType(
  10676. BaseType, MoveAssignOperator->getTypeQualifiers()),
  10677. VK_LValue, BasePath);
  10678. // Build the move.
  10679. StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
  10680. To, From,
  10681. /*CopyingBaseSubobject=*/true,
  10682. /*Copying=*/false);
  10683. if (Move.isInvalid()) {
  10684. MoveAssignOperator->setInvalidDecl();
  10685. return;
  10686. }
  10687. // Success! Record the move.
  10688. Statements.push_back(Move.getAs<Expr>());
  10689. }
  10690. // Assign non-static members.
  10691. for (auto *Field : ClassDecl->fields()) {
  10692. // FIXME: We should form some kind of AST representation for the implied
  10693. // memcpy in a union copy operation.
  10694. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  10695. continue;
  10696. if (Field->isInvalidDecl()) {
  10697. Invalid = true;
  10698. continue;
  10699. }
  10700. // Check for members of reference type; we can't move those.
  10701. if (Field->getType()->isReferenceType()) {
  10702. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10703. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  10704. Diag(Field->getLocation(), diag::note_declared_at);
  10705. Invalid = true;
  10706. continue;
  10707. }
  10708. // Check for members of const-qualified, non-class type.
  10709. QualType BaseType = Context.getBaseElementType(Field->getType());
  10710. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  10711. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10712. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  10713. Diag(Field->getLocation(), diag::note_declared_at);
  10714. Invalid = true;
  10715. continue;
  10716. }
  10717. // Suppress assigning zero-width bitfields.
  10718. if (Field->isZeroLengthBitField(Context))
  10719. continue;
  10720. QualType FieldType = Field->getType().getNonReferenceType();
  10721. if (FieldType->isIncompleteArrayType()) {
  10722. assert(ClassDecl->hasFlexibleArrayMember() &&
  10723. "Incomplete array type is not valid");
  10724. continue;
  10725. }
  10726. // Build references to the field in the object we're copying from and to.
  10727. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  10728. LookupMemberName);
  10729. MemberLookup.addDecl(Field);
  10730. MemberLookup.resolveKind();
  10731. MemberBuilder From(MoveOther, OtherRefType,
  10732. /*IsArrow=*/false, MemberLookup);
  10733. MemberBuilder To(This, getCurrentThisType(),
  10734. /*IsArrow=*/true, MemberLookup);
  10735. assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
  10736. "Member reference with rvalue base must be rvalue except for reference "
  10737. "members, which aren't allowed for move assignment.");
  10738. // Build the move of this field.
  10739. StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
  10740. To, From,
  10741. /*CopyingBaseSubobject=*/false,
  10742. /*Copying=*/false);
  10743. if (Move.isInvalid()) {
  10744. MoveAssignOperator->setInvalidDecl();
  10745. return;
  10746. }
  10747. // Success! Record the copy.
  10748. Statements.push_back(Move.getAs<Stmt>());
  10749. }
  10750. if (!Invalid) {
  10751. // Add a "return *this;"
  10752. ExprResult ThisObj =
  10753. CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  10754. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  10755. if (Return.isInvalid())
  10756. Invalid = true;
  10757. else
  10758. Statements.push_back(Return.getAs<Stmt>());
  10759. }
  10760. if (Invalid) {
  10761. MoveAssignOperator->setInvalidDecl();
  10762. return;
  10763. }
  10764. StmtResult Body;
  10765. {
  10766. CompoundScopeRAII CompoundScope(*this);
  10767. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  10768. /*isStmtExpr=*/false);
  10769. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  10770. }
  10771. MoveAssignOperator->setBody(Body.getAs<Stmt>());
  10772. MoveAssignOperator->markUsed(Context);
  10773. if (ASTMutationListener *L = getASTMutationListener()) {
  10774. L->CompletedImplicitDefinition(MoveAssignOperator);
  10775. }
  10776. }
  10777. CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
  10778. CXXRecordDecl *ClassDecl) {
  10779. // C++ [class.copy]p4:
  10780. // If the class definition does not explicitly declare a copy
  10781. // constructor, one is declared implicitly.
  10782. assert(ClassDecl->needsImplicitCopyConstructor());
  10783. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
  10784. if (DSM.isAlreadyBeingDeclared())
  10785. return nullptr;
  10786. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  10787. QualType ArgType = ClassType;
  10788. bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
  10789. if (Const)
  10790. ArgType = ArgType.withConst();
  10791. ArgType = Context.getLValueReferenceType(ArgType);
  10792. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10793. CXXCopyConstructor,
  10794. Const);
  10795. DeclarationName Name
  10796. = Context.DeclarationNames.getCXXConstructorName(
  10797. Context.getCanonicalType(ClassType));
  10798. SourceLocation ClassLoc = ClassDecl->getLocation();
  10799. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10800. // An implicitly-declared copy constructor is an inline public
  10801. // member of its class.
  10802. CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
  10803. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  10804. /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  10805. Constexpr);
  10806. CopyConstructor->setAccess(AS_public);
  10807. CopyConstructor->setDefaulted();
  10808. if (getLangOpts().CUDA) {
  10809. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
  10810. CopyConstructor,
  10811. /* ConstRHS */ Const,
  10812. /* Diagnose */ false);
  10813. }
  10814. // Build an exception specification pointing back at this member.
  10815. FunctionProtoType::ExtProtoInfo EPI =
  10816. getImplicitMethodEPI(*this, CopyConstructor);
  10817. CopyConstructor->setType(
  10818. Context.getFunctionType(Context.VoidTy, ArgType, EPI));
  10819. // Add the parameter to the constructor.
  10820. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
  10821. ClassLoc, ClassLoc,
  10822. /*IdentifierInfo=*/nullptr,
  10823. ArgType, /*TInfo=*/nullptr,
  10824. SC_None, nullptr);
  10825. CopyConstructor->setParams(FromParam);
  10826. CopyConstructor->setTrivial(
  10827. ClassDecl->needsOverloadResolutionForCopyConstructor()
  10828. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
  10829. : ClassDecl->hasTrivialCopyConstructor());
  10830. CopyConstructor->setTrivialForCall(
  10831. ClassDecl->hasAttr<TrivialABIAttr>() ||
  10832. (ClassDecl->needsOverloadResolutionForCopyConstructor()
  10833. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
  10834. TAH_ConsiderTrivialABI)
  10835. : ClassDecl->hasTrivialCopyConstructorForCall()));
  10836. // Note that we have declared this constructor.
  10837. ++ASTContext::NumImplicitCopyConstructorsDeclared;
  10838. Scope *S = getScopeForContext(ClassDecl);
  10839. CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
  10840. if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
  10841. ClassDecl->setImplicitCopyConstructorIsDeleted();
  10842. SetDeclDeleted(CopyConstructor, ClassLoc);
  10843. }
  10844. if (S)
  10845. PushOnScopeChains(CopyConstructor, S, false);
  10846. ClassDecl->addDecl(CopyConstructor);
  10847. return CopyConstructor;
  10848. }
  10849. void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
  10850. CXXConstructorDecl *CopyConstructor) {
  10851. assert((CopyConstructor->isDefaulted() &&
  10852. CopyConstructor->isCopyConstructor() &&
  10853. !CopyConstructor->doesThisDeclarationHaveABody() &&
  10854. !CopyConstructor->isDeleted()) &&
  10855. "DefineImplicitCopyConstructor - call it for implicit copy ctor");
  10856. if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
  10857. return;
  10858. CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
  10859. assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
  10860. SynthesizedFunctionScope Scope(*this, CopyConstructor);
  10861. // The exception specification is needed because we are defining the
  10862. // function.
  10863. ResolveExceptionSpec(CurrentLocation,
  10864. CopyConstructor->getType()->castAs<FunctionProtoType>());
  10865. MarkVTableUsed(CurrentLocation, ClassDecl);
  10866. // Add a context note for diagnostics produced after this point.
  10867. Scope.addContextNote(CurrentLocation);
  10868. // C++11 [class.copy]p7:
  10869. // The [definition of an implicitly declared copy constructor] is
  10870. // deprecated if the class has a user-declared copy assignment operator
  10871. // or a user-declared destructor.
  10872. if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
  10873. diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
  10874. if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
  10875. CopyConstructor->setInvalidDecl();
  10876. } else {
  10877. SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
  10878. ? CopyConstructor->getEndLoc()
  10879. : CopyConstructor->getLocation();
  10880. Sema::CompoundScopeRAII CompoundScope(*this);
  10881. CopyConstructor->setBody(
  10882. ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
  10883. CopyConstructor->markUsed(Context);
  10884. }
  10885. if (ASTMutationListener *L = getASTMutationListener()) {
  10886. L->CompletedImplicitDefinition(CopyConstructor);
  10887. }
  10888. }
  10889. CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
  10890. CXXRecordDecl *ClassDecl) {
  10891. assert(ClassDecl->needsImplicitMoveConstructor());
  10892. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
  10893. if (DSM.isAlreadyBeingDeclared())
  10894. return nullptr;
  10895. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  10896. QualType ArgType = Context.getRValueReferenceType(ClassType);
  10897. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10898. CXXMoveConstructor,
  10899. false);
  10900. DeclarationName Name
  10901. = Context.DeclarationNames.getCXXConstructorName(
  10902. Context.getCanonicalType(ClassType));
  10903. SourceLocation ClassLoc = ClassDecl->getLocation();
  10904. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10905. // C++11 [class.copy]p11:
  10906. // An implicitly-declared copy/move constructor is an inline public
  10907. // member of its class.
  10908. CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
  10909. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  10910. /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  10911. Constexpr);
  10912. MoveConstructor->setAccess(AS_public);
  10913. MoveConstructor->setDefaulted();
  10914. if (getLangOpts().CUDA) {
  10915. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
  10916. MoveConstructor,
  10917. /* ConstRHS */ false,
  10918. /* Diagnose */ false);
  10919. }
  10920. // Build an exception specification pointing back at this member.
  10921. FunctionProtoType::ExtProtoInfo EPI =
  10922. getImplicitMethodEPI(*this, MoveConstructor);
  10923. MoveConstructor->setType(
  10924. Context.getFunctionType(Context.VoidTy, ArgType, EPI));
  10925. // Add the parameter to the constructor.
  10926. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
  10927. ClassLoc, ClassLoc,
  10928. /*IdentifierInfo=*/nullptr,
  10929. ArgType, /*TInfo=*/nullptr,
  10930. SC_None, nullptr);
  10931. MoveConstructor->setParams(FromParam);
  10932. MoveConstructor->setTrivial(
  10933. ClassDecl->needsOverloadResolutionForMoveConstructor()
  10934. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
  10935. : ClassDecl->hasTrivialMoveConstructor());
  10936. MoveConstructor->setTrivialForCall(
  10937. ClassDecl->hasAttr<TrivialABIAttr>() ||
  10938. (ClassDecl->needsOverloadResolutionForMoveConstructor()
  10939. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
  10940. TAH_ConsiderTrivialABI)
  10941. : ClassDecl->hasTrivialMoveConstructorForCall()));
  10942. // Note that we have declared this constructor.
  10943. ++ASTContext::NumImplicitMoveConstructorsDeclared;
  10944. Scope *S = getScopeForContext(ClassDecl);
  10945. CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
  10946. if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
  10947. ClassDecl->setImplicitMoveConstructorIsDeleted();
  10948. SetDeclDeleted(MoveConstructor, ClassLoc);
  10949. }
  10950. if (S)
  10951. PushOnScopeChains(MoveConstructor, S, false);
  10952. ClassDecl->addDecl(MoveConstructor);
  10953. return MoveConstructor;
  10954. }
  10955. void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
  10956. CXXConstructorDecl *MoveConstructor) {
  10957. assert((MoveConstructor->isDefaulted() &&
  10958. MoveConstructor->isMoveConstructor() &&
  10959. !MoveConstructor->doesThisDeclarationHaveABody() &&
  10960. !MoveConstructor->isDeleted()) &&
  10961. "DefineImplicitMoveConstructor - call it for implicit move ctor");
  10962. if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
  10963. return;
  10964. CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
  10965. assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
  10966. SynthesizedFunctionScope Scope(*this, MoveConstructor);
  10967. // The exception specification is needed because we are defining the
  10968. // function.
  10969. ResolveExceptionSpec(CurrentLocation,
  10970. MoveConstructor->getType()->castAs<FunctionProtoType>());
  10971. MarkVTableUsed(CurrentLocation, ClassDecl);
  10972. // Add a context note for diagnostics produced after this point.
  10973. Scope.addContextNote(CurrentLocation);
  10974. if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
  10975. MoveConstructor->setInvalidDecl();
  10976. } else {
  10977. SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
  10978. ? MoveConstructor->getEndLoc()
  10979. : MoveConstructor->getLocation();
  10980. Sema::CompoundScopeRAII CompoundScope(*this);
  10981. MoveConstructor->setBody(ActOnCompoundStmt(
  10982. Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
  10983. MoveConstructor->markUsed(Context);
  10984. }
  10985. if (ASTMutationListener *L = getASTMutationListener()) {
  10986. L->CompletedImplicitDefinition(MoveConstructor);
  10987. }
  10988. }
  10989. bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
  10990. return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
  10991. }
  10992. void Sema::DefineImplicitLambdaToFunctionPointerConversion(
  10993. SourceLocation CurrentLocation,
  10994. CXXConversionDecl *Conv) {
  10995. SynthesizedFunctionScope Scope(*this, Conv);
  10996. assert(!Conv->getReturnType()->isUndeducedType());
  10997. CXXRecordDecl *Lambda = Conv->getParent();
  10998. FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
  10999. FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
  11000. if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
  11001. CallOp = InstantiateFunctionDeclaration(
  11002. CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  11003. if (!CallOp)
  11004. return;
  11005. Invoker = InstantiateFunctionDeclaration(
  11006. Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  11007. if (!Invoker)
  11008. return;
  11009. }
  11010. if (CallOp->isInvalidDecl())
  11011. return;
  11012. // Mark the call operator referenced (and add to pending instantiations
  11013. // if necessary).
  11014. // For both the conversion and static-invoker template specializations
  11015. // we construct their body's in this function, so no need to add them
  11016. // to the PendingInstantiations.
  11017. MarkFunctionReferenced(CurrentLocation, CallOp);
  11018. // Fill in the __invoke function with a dummy implementation. IR generation
  11019. // will fill in the actual details. Update its type in case it contained
  11020. // an 'auto'.
  11021. Invoker->markUsed(Context);
  11022. Invoker->setReferenced();
  11023. Invoker->setType(Conv->getReturnType()->getPointeeType());
  11024. Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
  11025. // Construct the body of the conversion function { return __invoke; }.
  11026. Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
  11027. VK_LValue, Conv->getLocation()).get();
  11028. assert(FunctionRef && "Can't refer to __invoke function?");
  11029. Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
  11030. Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
  11031. Conv->getLocation()));
  11032. Conv->markUsed(Context);
  11033. Conv->setReferenced();
  11034. if (ASTMutationListener *L = getASTMutationListener()) {
  11035. L->CompletedImplicitDefinition(Conv);
  11036. L->CompletedImplicitDefinition(Invoker);
  11037. }
  11038. }
  11039. void Sema::DefineImplicitLambdaToBlockPointerConversion(
  11040. SourceLocation CurrentLocation,
  11041. CXXConversionDecl *Conv)
  11042. {
  11043. assert(!Conv->getParent()->isGenericLambda());
  11044. SynthesizedFunctionScope Scope(*this, Conv);
  11045. // Copy-initialize the lambda object as needed to capture it.
  11046. Expr *This = ActOnCXXThis(CurrentLocation).get();
  11047. Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
  11048. ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
  11049. Conv->getLocation(),
  11050. Conv, DerefThis);
  11051. // If we're not under ARC, make sure we still get the _Block_copy/autorelease
  11052. // behavior. Note that only the general conversion function does this
  11053. // (since it's unusable otherwise); in the case where we inline the
  11054. // block literal, it has block literal lifetime semantics.
  11055. if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
  11056. BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
  11057. CK_CopyAndAutoreleaseBlockObject,
  11058. BuildBlock.get(), nullptr, VK_RValue);
  11059. if (BuildBlock.isInvalid()) {
  11060. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  11061. Conv->setInvalidDecl();
  11062. return;
  11063. }
  11064. // Create the return statement that returns the block from the conversion
  11065. // function.
  11066. StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
  11067. if (Return.isInvalid()) {
  11068. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  11069. Conv->setInvalidDecl();
  11070. return;
  11071. }
  11072. // Set the body of the conversion function.
  11073. Stmt *ReturnS = Return.get();
  11074. Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
  11075. Conv->getLocation()));
  11076. Conv->markUsed(Context);
  11077. // We're done; notify the mutation listener, if any.
  11078. if (ASTMutationListener *L = getASTMutationListener()) {
  11079. L->CompletedImplicitDefinition(Conv);
  11080. }
  11081. }
  11082. /// Determine whether the given list arguments contains exactly one
  11083. /// "real" (non-default) argument.
  11084. static bool hasOneRealArgument(MultiExprArg Args) {
  11085. switch (Args.size()) {
  11086. case 0:
  11087. return false;
  11088. default:
  11089. if (!Args[1]->isDefaultArgument())
  11090. return false;
  11091. LLVM_FALLTHROUGH;
  11092. case 1:
  11093. return !Args[0]->isDefaultArgument();
  11094. }
  11095. return false;
  11096. }
  11097. ExprResult
  11098. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11099. NamedDecl *FoundDecl,
  11100. CXXConstructorDecl *Constructor,
  11101. MultiExprArg ExprArgs,
  11102. bool HadMultipleCandidates,
  11103. bool IsListInitialization,
  11104. bool IsStdInitListInitialization,
  11105. bool RequiresZeroInit,
  11106. unsigned ConstructKind,
  11107. SourceRange ParenRange) {
  11108. bool Elidable = false;
  11109. // C++0x [class.copy]p34:
  11110. // When certain criteria are met, an implementation is allowed to
  11111. // omit the copy/move construction of a class object, even if the
  11112. // copy/move constructor and/or destructor for the object have
  11113. // side effects. [...]
  11114. // - when a temporary class object that has not been bound to a
  11115. // reference (12.2) would be copied/moved to a class object
  11116. // with the same cv-unqualified type, the copy/move operation
  11117. // can be omitted by constructing the temporary object
  11118. // directly into the target of the omitted copy/move
  11119. if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
  11120. Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
  11121. Expr *SubExpr = ExprArgs[0];
  11122. Elidable = SubExpr->isTemporaryObject(
  11123. Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  11124. }
  11125. return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
  11126. FoundDecl, Constructor,
  11127. Elidable, ExprArgs, HadMultipleCandidates,
  11128. IsListInitialization,
  11129. IsStdInitListInitialization, RequiresZeroInit,
  11130. ConstructKind, ParenRange);
  11131. }
  11132. ExprResult
  11133. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11134. NamedDecl *FoundDecl,
  11135. CXXConstructorDecl *Constructor,
  11136. bool Elidable,
  11137. MultiExprArg ExprArgs,
  11138. bool HadMultipleCandidates,
  11139. bool IsListInitialization,
  11140. bool IsStdInitListInitialization,
  11141. bool RequiresZeroInit,
  11142. unsigned ConstructKind,
  11143. SourceRange ParenRange) {
  11144. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
  11145. Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
  11146. if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
  11147. return ExprError();
  11148. }
  11149. return BuildCXXConstructExpr(
  11150. ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
  11151. HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
  11152. RequiresZeroInit, ConstructKind, ParenRange);
  11153. }
  11154. /// BuildCXXConstructExpr - Creates a complete call to a constructor,
  11155. /// including handling of its default argument expressions.
  11156. ExprResult
  11157. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  11158. CXXConstructorDecl *Constructor,
  11159. bool Elidable,
  11160. MultiExprArg ExprArgs,
  11161. bool HadMultipleCandidates,
  11162. bool IsListInitialization,
  11163. bool IsStdInitListInitialization,
  11164. bool RequiresZeroInit,
  11165. unsigned ConstructKind,
  11166. SourceRange ParenRange) {
  11167. assert(declaresSameEntity(
  11168. Constructor->getParent(),
  11169. DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
  11170. "given constructor for wrong type");
  11171. MarkFunctionReferenced(ConstructLoc, Constructor);
  11172. if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
  11173. return ExprError();
  11174. return CXXConstructExpr::Create(
  11175. Context, DeclInitType, ConstructLoc, Constructor, Elidable,
  11176. ExprArgs, HadMultipleCandidates, IsListInitialization,
  11177. IsStdInitListInitialization, RequiresZeroInit,
  11178. static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
  11179. ParenRange);
  11180. }
  11181. ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
  11182. assert(Field->hasInClassInitializer());
  11183. // If we already have the in-class initializer nothing needs to be done.
  11184. if (Field->getInClassInitializer())
  11185. return CXXDefaultInitExpr::Create(Context, Loc, Field);
  11186. // If we might have already tried and failed to instantiate, don't try again.
  11187. if (Field->isInvalidDecl())
  11188. return ExprError();
  11189. // Maybe we haven't instantiated the in-class initializer. Go check the
  11190. // pattern FieldDecl to see if it has one.
  11191. CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
  11192. if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
  11193. CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
  11194. DeclContext::lookup_result Lookup =
  11195. ClassPattern->lookup(Field->getDeclName());
  11196. // Lookup can return at most two results: the pattern for the field, or the
  11197. // injected class name of the parent record. No other member can have the
  11198. // same name as the field.
  11199. // In modules mode, lookup can return multiple results (coming from
  11200. // different modules).
  11201. assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
  11202. "more than two lookup results for field name");
  11203. FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
  11204. if (!Pattern) {
  11205. assert(isa<CXXRecordDecl>(Lookup[0]) &&
  11206. "cannot have other non-field member with same name");
  11207. for (auto L : Lookup)
  11208. if (isa<FieldDecl>(L)) {
  11209. Pattern = cast<FieldDecl>(L);
  11210. break;
  11211. }
  11212. assert(Pattern && "We must have set the Pattern!");
  11213. }
  11214. if (!Pattern->hasInClassInitializer() ||
  11215. InstantiateInClassInitializer(Loc, Field, Pattern,
  11216. getTemplateInstantiationArgs(Field))) {
  11217. // Don't diagnose this again.
  11218. Field->setInvalidDecl();
  11219. return ExprError();
  11220. }
  11221. return CXXDefaultInitExpr::Create(Context, Loc, Field);
  11222. }
  11223. // DR1351:
  11224. // If the brace-or-equal-initializer of a non-static data member
  11225. // invokes a defaulted default constructor of its class or of an
  11226. // enclosing class in a potentially evaluated subexpression, the
  11227. // program is ill-formed.
  11228. //
  11229. // This resolution is unworkable: the exception specification of the
  11230. // default constructor can be needed in an unevaluated context, in
  11231. // particular, in the operand of a noexcept-expression, and we can be
  11232. // unable to compute an exception specification for an enclosed class.
  11233. //
  11234. // Any attempt to resolve the exception specification of a defaulted default
  11235. // constructor before the initializer is lexically complete will ultimately
  11236. // come here at which point we can diagnose it.
  11237. RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
  11238. Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
  11239. << OutermostClass << Field;
  11240. Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
  11241. // Recover by marking the field invalid, unless we're in a SFINAE context.
  11242. if (!isSFINAEContext())
  11243. Field->setInvalidDecl();
  11244. return ExprError();
  11245. }
  11246. void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
  11247. if (VD->isInvalidDecl()) return;
  11248. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
  11249. if (ClassDecl->isInvalidDecl()) return;
  11250. if (ClassDecl->hasIrrelevantDestructor()) return;
  11251. if (ClassDecl->isDependentContext()) return;
  11252. if (VD->isNoDestroy(getASTContext()))
  11253. return;
  11254. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  11255. MarkFunctionReferenced(VD->getLocation(), Destructor);
  11256. CheckDestructorAccess(VD->getLocation(), Destructor,
  11257. PDiag(diag::err_access_dtor_var)
  11258. << VD->getDeclName()
  11259. << VD->getType());
  11260. DiagnoseUseOfDecl(Destructor, VD->getLocation());
  11261. if (Destructor->isTrivial()) return;
  11262. if (!VD->hasGlobalStorage()) return;
  11263. // Emit warning for non-trivial dtor in global scope (a real global,
  11264. // class-static, function-static).
  11265. Diag(VD->getLocation(), diag::warn_exit_time_destructor);
  11266. // TODO: this should be re-enabled for static locals by !CXAAtExit
  11267. if (!VD->isStaticLocal())
  11268. Diag(VD->getLocation(), diag::warn_global_destructor);
  11269. }
  11270. /// Given a constructor and the set of arguments provided for the
  11271. /// constructor, convert the arguments and add any required default arguments
  11272. /// to form a proper call to this constructor.
  11273. ///
  11274. /// \returns true if an error occurred, false otherwise.
  11275. bool
  11276. Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
  11277. MultiExprArg ArgsPtr,
  11278. SourceLocation Loc,
  11279. SmallVectorImpl<Expr*> &ConvertedArgs,
  11280. bool AllowExplicit,
  11281. bool IsListInitialization) {
  11282. // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
  11283. unsigned NumArgs = ArgsPtr.size();
  11284. Expr **Args = ArgsPtr.data();
  11285. const FunctionProtoType *Proto
  11286. = Constructor->getType()->getAs<FunctionProtoType>();
  11287. assert(Proto && "Constructor without a prototype?");
  11288. unsigned NumParams = Proto->getNumParams();
  11289. // If too few arguments are available, we'll fill in the rest with defaults.
  11290. if (NumArgs < NumParams)
  11291. ConvertedArgs.reserve(NumParams);
  11292. else
  11293. ConvertedArgs.reserve(NumArgs);
  11294. VariadicCallType CallType =
  11295. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  11296. SmallVector<Expr *, 8> AllArgs;
  11297. bool Invalid = GatherArgumentsForCall(Loc, Constructor,
  11298. Proto, 0,
  11299. llvm::makeArrayRef(Args, NumArgs),
  11300. AllArgs,
  11301. CallType, AllowExplicit,
  11302. IsListInitialization);
  11303. ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
  11304. DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
  11305. CheckConstructorCall(Constructor,
  11306. llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
  11307. Proto, Loc);
  11308. return Invalid;
  11309. }
  11310. static inline bool
  11311. CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
  11312. const FunctionDecl *FnDecl) {
  11313. const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
  11314. if (isa<NamespaceDecl>(DC)) {
  11315. return SemaRef.Diag(FnDecl->getLocation(),
  11316. diag::err_operator_new_delete_declared_in_namespace)
  11317. << FnDecl->getDeclName();
  11318. }
  11319. if (isa<TranslationUnitDecl>(DC) &&
  11320. FnDecl->getStorageClass() == SC_Static) {
  11321. return SemaRef.Diag(FnDecl->getLocation(),
  11322. diag::err_operator_new_delete_declared_static)
  11323. << FnDecl->getDeclName();
  11324. }
  11325. return false;
  11326. }
  11327. static QualType
  11328. RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
  11329. QualType QTy = PtrTy->getPointeeType();
  11330. QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
  11331. return SemaRef.Context.getPointerType(QTy);
  11332. }
  11333. static inline bool
  11334. CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
  11335. CanQualType ExpectedResultType,
  11336. CanQualType ExpectedFirstParamType,
  11337. unsigned DependentParamTypeDiag,
  11338. unsigned InvalidParamTypeDiag) {
  11339. QualType ResultType =
  11340. FnDecl->getType()->getAs<FunctionType>()->getReturnType();
  11341. // Check that the result type is not dependent.
  11342. if (ResultType->isDependentType())
  11343. return SemaRef.Diag(FnDecl->getLocation(),
  11344. diag::err_operator_new_delete_dependent_result_type)
  11345. << FnDecl->getDeclName() << ExpectedResultType;
  11346. // OpenCL C++: the operator is valid on any address space.
  11347. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  11348. if (auto *PtrTy = ResultType->getAs<PointerType>()) {
  11349. ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  11350. }
  11351. }
  11352. // Check that the result type is what we expect.
  11353. if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
  11354. return SemaRef.Diag(FnDecl->getLocation(),
  11355. diag::err_operator_new_delete_invalid_result_type)
  11356. << FnDecl->getDeclName() << ExpectedResultType;
  11357. // A function template must have at least 2 parameters.
  11358. if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
  11359. return SemaRef.Diag(FnDecl->getLocation(),
  11360. diag::err_operator_new_delete_template_too_few_parameters)
  11361. << FnDecl->getDeclName();
  11362. // The function decl must have at least 1 parameter.
  11363. if (FnDecl->getNumParams() == 0)
  11364. return SemaRef.Diag(FnDecl->getLocation(),
  11365. diag::err_operator_new_delete_too_few_parameters)
  11366. << FnDecl->getDeclName();
  11367. // Check the first parameter type is not dependent.
  11368. QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
  11369. if (FirstParamType->isDependentType())
  11370. return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
  11371. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11372. // Check that the first parameter type is what we expect.
  11373. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  11374. // OpenCL C++: the operator is valid on any address space.
  11375. if (auto *PtrTy =
  11376. FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
  11377. FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  11378. }
  11379. }
  11380. if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
  11381. ExpectedFirstParamType)
  11382. return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
  11383. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11384. return false;
  11385. }
  11386. static bool
  11387. CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
  11388. // C++ [basic.stc.dynamic.allocation]p1:
  11389. // A program is ill-formed if an allocation function is declared in a
  11390. // namespace scope other than global scope or declared static in global
  11391. // scope.
  11392. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11393. return true;
  11394. CanQualType SizeTy =
  11395. SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
  11396. // C++ [basic.stc.dynamic.allocation]p1:
  11397. // The return type shall be void*. The first parameter shall have type
  11398. // std::size_t.
  11399. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
  11400. SizeTy,
  11401. diag::err_operator_new_dependent_param_type,
  11402. diag::err_operator_new_param_type))
  11403. return true;
  11404. // C++ [basic.stc.dynamic.allocation]p1:
  11405. // The first parameter shall not have an associated default argument.
  11406. if (FnDecl->getParamDecl(0)->hasDefaultArg())
  11407. return SemaRef.Diag(FnDecl->getLocation(),
  11408. diag::err_operator_new_default_arg)
  11409. << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
  11410. return false;
  11411. }
  11412. static bool
  11413. CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
  11414. // C++ [basic.stc.dynamic.deallocation]p1:
  11415. // A program is ill-formed if deallocation functions are declared in a
  11416. // namespace scope other than global scope or declared static in global
  11417. // scope.
  11418. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11419. return true;
  11420. auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
  11421. // C++ P0722:
  11422. // Within a class C, the first parameter of a destroying operator delete
  11423. // shall be of type C *. The first parameter of any other deallocation
  11424. // function shall be of type void *.
  11425. CanQualType ExpectedFirstParamType =
  11426. MD && MD->isDestroyingOperatorDelete()
  11427. ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
  11428. SemaRef.Context.getRecordType(MD->getParent())))
  11429. : SemaRef.Context.VoidPtrTy;
  11430. // C++ [basic.stc.dynamic.deallocation]p2:
  11431. // Each deallocation function shall return void
  11432. if (CheckOperatorNewDeleteTypes(
  11433. SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
  11434. diag::err_operator_delete_dependent_param_type,
  11435. diag::err_operator_delete_param_type))
  11436. return true;
  11437. // C++ P0722:
  11438. // A destroying operator delete shall be a usual deallocation function.
  11439. if (MD && !MD->getParent()->isDependentContext() &&
  11440. MD->isDestroyingOperatorDelete() &&
  11441. !SemaRef.isUsualDeallocationFunction(MD)) {
  11442. SemaRef.Diag(MD->getLocation(),
  11443. diag::err_destroying_operator_delete_not_usual);
  11444. return true;
  11445. }
  11446. return false;
  11447. }
  11448. /// CheckOverloadedOperatorDeclaration - Check whether the declaration
  11449. /// of this overloaded operator is well-formed. If so, returns false;
  11450. /// otherwise, emits appropriate diagnostics and returns true.
  11451. bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
  11452. assert(FnDecl && FnDecl->isOverloadedOperator() &&
  11453. "Expected an overloaded operator declaration");
  11454. OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
  11455. // C++ [over.oper]p5:
  11456. // The allocation and deallocation functions, operator new,
  11457. // operator new[], operator delete and operator delete[], are
  11458. // described completely in 3.7.3. The attributes and restrictions
  11459. // found in the rest of this subclause do not apply to them unless
  11460. // explicitly stated in 3.7.3.
  11461. if (Op == OO_Delete || Op == OO_Array_Delete)
  11462. return CheckOperatorDeleteDeclaration(*this, FnDecl);
  11463. if (Op == OO_New || Op == OO_Array_New)
  11464. return CheckOperatorNewDeclaration(*this, FnDecl);
  11465. // C++ [over.oper]p6:
  11466. // An operator function shall either be a non-static member
  11467. // function or be a non-member function and have at least one
  11468. // parameter whose type is a class, a reference to a class, an
  11469. // enumeration, or a reference to an enumeration.
  11470. if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
  11471. if (MethodDecl->isStatic())
  11472. return Diag(FnDecl->getLocation(),
  11473. diag::err_operator_overload_static) << FnDecl->getDeclName();
  11474. } else {
  11475. bool ClassOrEnumParam = false;
  11476. for (auto Param : FnDecl->parameters()) {
  11477. QualType ParamType = Param->getType().getNonReferenceType();
  11478. if (ParamType->isDependentType() || ParamType->isRecordType() ||
  11479. ParamType->isEnumeralType()) {
  11480. ClassOrEnumParam = true;
  11481. break;
  11482. }
  11483. }
  11484. if (!ClassOrEnumParam)
  11485. return Diag(FnDecl->getLocation(),
  11486. diag::err_operator_overload_needs_class_or_enum)
  11487. << FnDecl->getDeclName();
  11488. }
  11489. // C++ [over.oper]p8:
  11490. // An operator function cannot have default arguments (8.3.6),
  11491. // except where explicitly stated below.
  11492. //
  11493. // Only the function-call operator allows default arguments
  11494. // (C++ [over.call]p1).
  11495. if (Op != OO_Call) {
  11496. for (auto Param : FnDecl->parameters()) {
  11497. if (Param->hasDefaultArg())
  11498. return Diag(Param->getLocation(),
  11499. diag::err_operator_overload_default_arg)
  11500. << FnDecl->getDeclName() << Param->getDefaultArgRange();
  11501. }
  11502. }
  11503. static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
  11504. { false, false, false }
  11505. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  11506. , { Unary, Binary, MemberOnly }
  11507. #include "clang/Basic/OperatorKinds.def"
  11508. };
  11509. bool CanBeUnaryOperator = OperatorUses[Op][0];
  11510. bool CanBeBinaryOperator = OperatorUses[Op][1];
  11511. bool MustBeMemberOperator = OperatorUses[Op][2];
  11512. // C++ [over.oper]p8:
  11513. // [...] Operator functions cannot have more or fewer parameters
  11514. // than the number required for the corresponding operator, as
  11515. // described in the rest of this subclause.
  11516. unsigned NumParams = FnDecl->getNumParams()
  11517. + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
  11518. if (Op != OO_Call &&
  11519. ((NumParams == 1 && !CanBeUnaryOperator) ||
  11520. (NumParams == 2 && !CanBeBinaryOperator) ||
  11521. (NumParams < 1) || (NumParams > 2))) {
  11522. // We have the wrong number of parameters.
  11523. unsigned ErrorKind;
  11524. if (CanBeUnaryOperator && CanBeBinaryOperator) {
  11525. ErrorKind = 2; // 2 -> unary or binary.
  11526. } else if (CanBeUnaryOperator) {
  11527. ErrorKind = 0; // 0 -> unary
  11528. } else {
  11529. assert(CanBeBinaryOperator &&
  11530. "All non-call overloaded operators are unary or binary!");
  11531. ErrorKind = 1; // 1 -> binary
  11532. }
  11533. return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
  11534. << FnDecl->getDeclName() << NumParams << ErrorKind;
  11535. }
  11536. // Overloaded operators other than operator() cannot be variadic.
  11537. if (Op != OO_Call &&
  11538. FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
  11539. return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
  11540. << FnDecl->getDeclName();
  11541. }
  11542. // Some operators must be non-static member functions.
  11543. if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
  11544. return Diag(FnDecl->getLocation(),
  11545. diag::err_operator_overload_must_be_member)
  11546. << FnDecl->getDeclName();
  11547. }
  11548. // C++ [over.inc]p1:
  11549. // The user-defined function called operator++ implements the
  11550. // prefix and postfix ++ operator. If this function is a member
  11551. // function with no parameters, or a non-member function with one
  11552. // parameter of class or enumeration type, it defines the prefix
  11553. // increment operator ++ for objects of that type. If the function
  11554. // is a member function with one parameter (which shall be of type
  11555. // int) or a non-member function with two parameters (the second
  11556. // of which shall be of type int), it defines the postfix
  11557. // increment operator ++ for objects of that type.
  11558. if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
  11559. ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
  11560. QualType ParamType = LastParam->getType();
  11561. if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
  11562. !ParamType->isDependentType())
  11563. return Diag(LastParam->getLocation(),
  11564. diag::err_operator_overload_post_incdec_must_be_int)
  11565. << LastParam->getType() << (Op == OO_MinusMinus);
  11566. }
  11567. return false;
  11568. }
  11569. static bool
  11570. checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
  11571. FunctionTemplateDecl *TpDecl) {
  11572. TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
  11573. // Must have one or two template parameters.
  11574. if (TemplateParams->size() == 1) {
  11575. NonTypeTemplateParmDecl *PmDecl =
  11576. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
  11577. // The template parameter must be a char parameter pack.
  11578. if (PmDecl && PmDecl->isTemplateParameterPack() &&
  11579. SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
  11580. return false;
  11581. } else if (TemplateParams->size() == 2) {
  11582. TemplateTypeParmDecl *PmType =
  11583. dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
  11584. NonTypeTemplateParmDecl *PmArgs =
  11585. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
  11586. // The second template parameter must be a parameter pack with the
  11587. // first template parameter as its type.
  11588. if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
  11589. PmArgs->isTemplateParameterPack()) {
  11590. const TemplateTypeParmType *TArgs =
  11591. PmArgs->getType()->getAs<TemplateTypeParmType>();
  11592. if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
  11593. TArgs->getIndex() == PmType->getIndex()) {
  11594. if (!SemaRef.inTemplateInstantiation())
  11595. SemaRef.Diag(TpDecl->getLocation(),
  11596. diag::ext_string_literal_operator_template);
  11597. return false;
  11598. }
  11599. }
  11600. }
  11601. SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
  11602. diag::err_literal_operator_template)
  11603. << TpDecl->getTemplateParameters()->getSourceRange();
  11604. return true;
  11605. }
  11606. /// CheckLiteralOperatorDeclaration - Check whether the declaration
  11607. /// of this literal operator function is well-formed. If so, returns
  11608. /// false; otherwise, emits appropriate diagnostics and returns true.
  11609. bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
  11610. if (isa<CXXMethodDecl>(FnDecl)) {
  11611. Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
  11612. << FnDecl->getDeclName();
  11613. return true;
  11614. }
  11615. if (FnDecl->isExternC()) {
  11616. Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
  11617. if (const LinkageSpecDecl *LSD =
  11618. FnDecl->getDeclContext()->getExternCContext())
  11619. Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
  11620. return true;
  11621. }
  11622. // This might be the definition of a literal operator template.
  11623. FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
  11624. // This might be a specialization of a literal operator template.
  11625. if (!TpDecl)
  11626. TpDecl = FnDecl->getPrimaryTemplate();
  11627. // template <char...> type operator "" name() and
  11628. // template <class T, T...> type operator "" name() are the only valid
  11629. // template signatures, and the only valid signatures with no parameters.
  11630. if (TpDecl) {
  11631. if (FnDecl->param_size() != 0) {
  11632. Diag(FnDecl->getLocation(),
  11633. diag::err_literal_operator_template_with_params);
  11634. return true;
  11635. }
  11636. if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
  11637. return true;
  11638. } else if (FnDecl->param_size() == 1) {
  11639. const ParmVarDecl *Param = FnDecl->getParamDecl(0);
  11640. QualType ParamType = Param->getType().getUnqualifiedType();
  11641. // Only unsigned long long int, long double, any character type, and const
  11642. // char * are allowed as the only parameters.
  11643. if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
  11644. ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
  11645. Context.hasSameType(ParamType, Context.CharTy) ||
  11646. Context.hasSameType(ParamType, Context.WideCharTy) ||
  11647. Context.hasSameType(ParamType, Context.Char8Ty) ||
  11648. Context.hasSameType(ParamType, Context.Char16Ty) ||
  11649. Context.hasSameType(ParamType, Context.Char32Ty)) {
  11650. } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
  11651. QualType InnerType = Ptr->getPointeeType();
  11652. // Pointer parameter must be a const char *.
  11653. if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
  11654. Context.CharTy) &&
  11655. InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
  11656. Diag(Param->getSourceRange().getBegin(),
  11657. diag::err_literal_operator_param)
  11658. << ParamType << "'const char *'" << Param->getSourceRange();
  11659. return true;
  11660. }
  11661. } else if (ParamType->isRealFloatingType()) {
  11662. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  11663. << ParamType << Context.LongDoubleTy << Param->getSourceRange();
  11664. return true;
  11665. } else if (ParamType->isIntegerType()) {
  11666. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  11667. << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
  11668. return true;
  11669. } else {
  11670. Diag(Param->getSourceRange().getBegin(),
  11671. diag::err_literal_operator_invalid_param)
  11672. << ParamType << Param->getSourceRange();
  11673. return true;
  11674. }
  11675. } else if (FnDecl->param_size() == 2) {
  11676. FunctionDecl::param_iterator Param = FnDecl->param_begin();
  11677. // First, verify that the first parameter is correct.
  11678. QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
  11679. // Two parameter function must have a pointer to const as a
  11680. // first parameter; let's strip those qualifiers.
  11681. const PointerType *PT = FirstParamType->getAs<PointerType>();
  11682. if (!PT) {
  11683. Diag((*Param)->getSourceRange().getBegin(),
  11684. diag::err_literal_operator_param)
  11685. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11686. return true;
  11687. }
  11688. QualType PointeeType = PT->getPointeeType();
  11689. // First parameter must be const
  11690. if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
  11691. Diag((*Param)->getSourceRange().getBegin(),
  11692. diag::err_literal_operator_param)
  11693. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11694. return true;
  11695. }
  11696. QualType InnerType = PointeeType.getUnqualifiedType();
  11697. // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
  11698. // const char32_t* are allowed as the first parameter to a two-parameter
  11699. // function
  11700. if (!(Context.hasSameType(InnerType, Context.CharTy) ||
  11701. Context.hasSameType(InnerType, Context.WideCharTy) ||
  11702. Context.hasSameType(InnerType, Context.Char8Ty) ||
  11703. Context.hasSameType(InnerType, Context.Char16Ty) ||
  11704. Context.hasSameType(InnerType, Context.Char32Ty))) {
  11705. Diag((*Param)->getSourceRange().getBegin(),
  11706. diag::err_literal_operator_param)
  11707. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11708. return true;
  11709. }
  11710. // Move on to the second and final parameter.
  11711. ++Param;
  11712. // The second parameter must be a std::size_t.
  11713. QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
  11714. if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
  11715. Diag((*Param)->getSourceRange().getBegin(),
  11716. diag::err_literal_operator_param)
  11717. << SecondParamType << Context.getSizeType()
  11718. << (*Param)->getSourceRange();
  11719. return true;
  11720. }
  11721. } else {
  11722. Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
  11723. return true;
  11724. }
  11725. // Parameters are good.
  11726. // A parameter-declaration-clause containing a default argument is not
  11727. // equivalent to any of the permitted forms.
  11728. for (auto Param : FnDecl->parameters()) {
  11729. if (Param->hasDefaultArg()) {
  11730. Diag(Param->getDefaultArgRange().getBegin(),
  11731. diag::err_literal_operator_default_argument)
  11732. << Param->getDefaultArgRange();
  11733. break;
  11734. }
  11735. }
  11736. StringRef LiteralName
  11737. = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
  11738. if (LiteralName[0] != '_' &&
  11739. !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
  11740. // C++11 [usrlit.suffix]p1:
  11741. // Literal suffix identifiers that do not start with an underscore
  11742. // are reserved for future standardization.
  11743. Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
  11744. << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
  11745. }
  11746. return false;
  11747. }
  11748. /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
  11749. /// linkage specification, including the language and (if present)
  11750. /// the '{'. ExternLoc is the location of the 'extern', Lang is the
  11751. /// language string literal. LBraceLoc, if valid, provides the location of
  11752. /// the '{' brace. Otherwise, this linkage specification does not
  11753. /// have any braces.
  11754. Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
  11755. Expr *LangStr,
  11756. SourceLocation LBraceLoc) {
  11757. StringLiteral *Lit = cast<StringLiteral>(LangStr);
  11758. if (!Lit->isAscii()) {
  11759. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
  11760. << LangStr->getSourceRange();
  11761. return nullptr;
  11762. }
  11763. StringRef Lang = Lit->getString();
  11764. LinkageSpecDecl::LanguageIDs Language;
  11765. if (Lang == "C")
  11766. Language = LinkageSpecDecl::lang_c;
  11767. else if (Lang == "C++")
  11768. Language = LinkageSpecDecl::lang_cxx;
  11769. else {
  11770. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
  11771. << LangStr->getSourceRange();
  11772. return nullptr;
  11773. }
  11774. // FIXME: Add all the various semantics of linkage specifications
  11775. LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
  11776. LangStr->getExprLoc(), Language,
  11777. LBraceLoc.isValid());
  11778. CurContext->addDecl(D);
  11779. PushDeclContext(S, D);
  11780. return D;
  11781. }
  11782. /// ActOnFinishLinkageSpecification - Complete the definition of
  11783. /// the C++ linkage specification LinkageSpec. If RBraceLoc is
  11784. /// valid, it's the position of the closing '}' brace in a linkage
  11785. /// specification that uses braces.
  11786. Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
  11787. Decl *LinkageSpec,
  11788. SourceLocation RBraceLoc) {
  11789. if (RBraceLoc.isValid()) {
  11790. LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
  11791. LSDecl->setRBraceLoc(RBraceLoc);
  11792. }
  11793. PopDeclContext();
  11794. return LinkageSpec;
  11795. }
  11796. Decl *Sema::ActOnEmptyDeclaration(Scope *S,
  11797. const ParsedAttributesView &AttrList,
  11798. SourceLocation SemiLoc) {
  11799. Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
  11800. // Attribute declarations appertain to empty declaration so we handle
  11801. // them here.
  11802. ProcessDeclAttributeList(S, ED, AttrList);
  11803. CurContext->addDecl(ED);
  11804. return ED;
  11805. }
  11806. /// Perform semantic analysis for the variable declaration that
  11807. /// occurs within a C++ catch clause, returning the newly-created
  11808. /// variable.
  11809. VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
  11810. TypeSourceInfo *TInfo,
  11811. SourceLocation StartLoc,
  11812. SourceLocation Loc,
  11813. IdentifierInfo *Name) {
  11814. bool Invalid = false;
  11815. QualType ExDeclType = TInfo->getType();
  11816. // Arrays and functions decay.
  11817. if (ExDeclType->isArrayType())
  11818. ExDeclType = Context.getArrayDecayedType(ExDeclType);
  11819. else if (ExDeclType->isFunctionType())
  11820. ExDeclType = Context.getPointerType(ExDeclType);
  11821. // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
  11822. // The exception-declaration shall not denote a pointer or reference to an
  11823. // incomplete type, other than [cv] void*.
  11824. // N2844 forbids rvalue references.
  11825. if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
  11826. Diag(Loc, diag::err_catch_rvalue_ref);
  11827. Invalid = true;
  11828. }
  11829. if (ExDeclType->isVariablyModifiedType()) {
  11830. Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
  11831. Invalid = true;
  11832. }
  11833. QualType BaseType = ExDeclType;
  11834. int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
  11835. unsigned DK = diag::err_catch_incomplete;
  11836. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  11837. BaseType = Ptr->getPointeeType();
  11838. Mode = 1;
  11839. DK = diag::err_catch_incomplete_ptr;
  11840. } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
  11841. // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
  11842. BaseType = Ref->getPointeeType();
  11843. Mode = 2;
  11844. DK = diag::err_catch_incomplete_ref;
  11845. }
  11846. if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
  11847. !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
  11848. Invalid = true;
  11849. if (!Invalid && !ExDeclType->isDependentType() &&
  11850. RequireNonAbstractType(Loc, ExDeclType,
  11851. diag::err_abstract_type_in_decl,
  11852. AbstractVariableType))
  11853. Invalid = true;
  11854. // Only the non-fragile NeXT runtime currently supports C++ catches
  11855. // of ObjC types, and no runtime supports catching ObjC types by value.
  11856. if (!Invalid && getLangOpts().ObjC) {
  11857. QualType T = ExDeclType;
  11858. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  11859. T = RT->getPointeeType();
  11860. if (T->isObjCObjectType()) {
  11861. Diag(Loc, diag::err_objc_object_catch);
  11862. Invalid = true;
  11863. } else if (T->isObjCObjectPointerType()) {
  11864. // FIXME: should this be a test for macosx-fragile specifically?
  11865. if (getLangOpts().ObjCRuntime.isFragile())
  11866. Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
  11867. }
  11868. }
  11869. VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
  11870. ExDeclType, TInfo, SC_None);
  11871. ExDecl->setExceptionVariable(true);
  11872. // In ARC, infer 'retaining' for variables of retainable type.
  11873. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
  11874. Invalid = true;
  11875. if (!Invalid && !ExDeclType->isDependentType()) {
  11876. if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
  11877. // Insulate this from anything else we might currently be parsing.
  11878. EnterExpressionEvaluationContext scope(
  11879. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  11880. // C++ [except.handle]p16:
  11881. // The object declared in an exception-declaration or, if the
  11882. // exception-declaration does not specify a name, a temporary (12.2) is
  11883. // copy-initialized (8.5) from the exception object. [...]
  11884. // The object is destroyed when the handler exits, after the destruction
  11885. // of any automatic objects initialized within the handler.
  11886. //
  11887. // We just pretend to initialize the object with itself, then make sure
  11888. // it can be destroyed later.
  11889. QualType initType = Context.getExceptionObjectType(ExDeclType);
  11890. InitializedEntity entity =
  11891. InitializedEntity::InitializeVariable(ExDecl);
  11892. InitializationKind initKind =
  11893. InitializationKind::CreateCopy(Loc, SourceLocation());
  11894. Expr *opaqueValue =
  11895. new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
  11896. InitializationSequence sequence(*this, entity, initKind, opaqueValue);
  11897. ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
  11898. if (result.isInvalid())
  11899. Invalid = true;
  11900. else {
  11901. // If the constructor used was non-trivial, set this as the
  11902. // "initializer".
  11903. CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
  11904. if (!construct->getConstructor()->isTrivial()) {
  11905. Expr *init = MaybeCreateExprWithCleanups(construct);
  11906. ExDecl->setInit(init);
  11907. }
  11908. // And make sure it's destructable.
  11909. FinalizeVarWithDestructor(ExDecl, recordType);
  11910. }
  11911. }
  11912. }
  11913. if (Invalid)
  11914. ExDecl->setInvalidDecl();
  11915. return ExDecl;
  11916. }
  11917. /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
  11918. /// handler.
  11919. Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
  11920. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11921. bool Invalid = D.isInvalidType();
  11922. // Check for unexpanded parameter packs.
  11923. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  11924. UPPC_ExceptionType)) {
  11925. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  11926. D.getIdentifierLoc());
  11927. Invalid = true;
  11928. }
  11929. IdentifierInfo *II = D.getIdentifier();
  11930. if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
  11931. LookupOrdinaryName,
  11932. ForVisibleRedeclaration)) {
  11933. // The scope should be freshly made just for us. There is just no way
  11934. // it contains any previous declaration, except for function parameters in
  11935. // a function-try-block's catch statement.
  11936. assert(!S->isDeclScope(PrevDecl));
  11937. if (isDeclInScope(PrevDecl, CurContext, S)) {
  11938. Diag(D.getIdentifierLoc(), diag::err_redefinition)
  11939. << D.getIdentifier();
  11940. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  11941. Invalid = true;
  11942. } else if (PrevDecl->isTemplateParameter())
  11943. // Maybe we will complain about the shadowed template parameter.
  11944. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11945. }
  11946. if (D.getCXXScopeSpec().isSet() && !Invalid) {
  11947. Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
  11948. << D.getCXXScopeSpec().getRange();
  11949. Invalid = true;
  11950. }
  11951. VarDecl *ExDecl = BuildExceptionDeclaration(
  11952. S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
  11953. if (Invalid)
  11954. ExDecl->setInvalidDecl();
  11955. // Add the exception declaration into this scope.
  11956. if (II)
  11957. PushOnScopeChains(ExDecl, S);
  11958. else
  11959. CurContext->addDecl(ExDecl);
  11960. ProcessDeclAttributes(S, ExDecl, D);
  11961. return ExDecl;
  11962. }
  11963. Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  11964. Expr *AssertExpr,
  11965. Expr *AssertMessageExpr,
  11966. SourceLocation RParenLoc) {
  11967. StringLiteral *AssertMessage =
  11968. AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
  11969. if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
  11970. return nullptr;
  11971. return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
  11972. AssertMessage, RParenLoc, false);
  11973. }
  11974. Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  11975. Expr *AssertExpr,
  11976. StringLiteral *AssertMessage,
  11977. SourceLocation RParenLoc,
  11978. bool Failed) {
  11979. assert(AssertExpr != nullptr && "Expected non-null condition");
  11980. if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
  11981. !Failed) {
  11982. // In a static_assert-declaration, the constant-expression shall be a
  11983. // constant expression that can be contextually converted to bool.
  11984. ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
  11985. if (Converted.isInvalid())
  11986. Failed = true;
  11987. llvm::APSInt Cond;
  11988. if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
  11989. diag::err_static_assert_expression_is_not_constant,
  11990. /*AllowFold=*/false).isInvalid())
  11991. Failed = true;
  11992. if (!Failed && !Cond) {
  11993. SmallString<256> MsgBuffer;
  11994. llvm::raw_svector_ostream Msg(MsgBuffer);
  11995. if (AssertMessage)
  11996. AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
  11997. Expr *InnerCond = nullptr;
  11998. std::string InnerCondDescription;
  11999. std::tie(InnerCond, InnerCondDescription) =
  12000. findFailedBooleanCondition(Converted.get(),
  12001. /*AllowTopLevelCond=*/false);
  12002. if (InnerCond) {
  12003. Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
  12004. << InnerCondDescription << !AssertMessage
  12005. << Msg.str() << InnerCond->getSourceRange();
  12006. } else {
  12007. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  12008. << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
  12009. }
  12010. Failed = true;
  12011. }
  12012. }
  12013. ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
  12014. /*DiscardedValue*/false,
  12015. /*IsConstexpr*/true);
  12016. if (FullAssertExpr.isInvalid())
  12017. Failed = true;
  12018. else
  12019. AssertExpr = FullAssertExpr.get();
  12020. Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
  12021. AssertExpr, AssertMessage, RParenLoc,
  12022. Failed);
  12023. CurContext->addDecl(Decl);
  12024. return Decl;
  12025. }
  12026. /// Perform semantic analysis of the given friend type declaration.
  12027. ///
  12028. /// \returns A friend declaration that.
  12029. FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
  12030. SourceLocation FriendLoc,
  12031. TypeSourceInfo *TSInfo) {
  12032. assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
  12033. QualType T = TSInfo->getType();
  12034. SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
  12035. // C++03 [class.friend]p2:
  12036. // An elaborated-type-specifier shall be used in a friend declaration
  12037. // for a class.*
  12038. //
  12039. // * The class-key of the elaborated-type-specifier is required.
  12040. if (!CodeSynthesisContexts.empty()) {
  12041. // Do not complain about the form of friend template types during any kind
  12042. // of code synthesis. For template instantiation, we will have complained
  12043. // when the template was defined.
  12044. } else {
  12045. if (!T->isElaboratedTypeSpecifier()) {
  12046. // If we evaluated the type to a record type, suggest putting
  12047. // a tag in front.
  12048. if (const RecordType *RT = T->getAs<RecordType>()) {
  12049. RecordDecl *RD = RT->getDecl();
  12050. SmallString<16> InsertionText(" ");
  12051. InsertionText += RD->getKindName();
  12052. Diag(TypeRange.getBegin(),
  12053. getLangOpts().CPlusPlus11 ?
  12054. diag::warn_cxx98_compat_unelaborated_friend_type :
  12055. diag::ext_unelaborated_friend_type)
  12056. << (unsigned) RD->getTagKind()
  12057. << T
  12058. << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
  12059. InsertionText);
  12060. } else {
  12061. Diag(FriendLoc,
  12062. getLangOpts().CPlusPlus11 ?
  12063. diag::warn_cxx98_compat_nonclass_type_friend :
  12064. diag::ext_nonclass_type_friend)
  12065. << T
  12066. << TypeRange;
  12067. }
  12068. } else if (T->getAs<EnumType>()) {
  12069. Diag(FriendLoc,
  12070. getLangOpts().CPlusPlus11 ?
  12071. diag::warn_cxx98_compat_enum_friend :
  12072. diag::ext_enum_friend)
  12073. << T
  12074. << TypeRange;
  12075. }
  12076. // C++11 [class.friend]p3:
  12077. // A friend declaration that does not declare a function shall have one
  12078. // of the following forms:
  12079. // friend elaborated-type-specifier ;
  12080. // friend simple-type-specifier ;
  12081. // friend typename-specifier ;
  12082. if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
  12083. Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
  12084. }
  12085. // If the type specifier in a friend declaration designates a (possibly
  12086. // cv-qualified) class type, that class is declared as a friend; otherwise,
  12087. // the friend declaration is ignored.
  12088. return FriendDecl::Create(Context, CurContext,
  12089. TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
  12090. FriendLoc);
  12091. }
  12092. /// Handle a friend tag declaration where the scope specifier was
  12093. /// templated.
  12094. Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
  12095. unsigned TagSpec, SourceLocation TagLoc,
  12096. CXXScopeSpec &SS, IdentifierInfo *Name,
  12097. SourceLocation NameLoc,
  12098. const ParsedAttributesView &Attr,
  12099. MultiTemplateParamsArg TempParamLists) {
  12100. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12101. bool IsMemberSpecialization = false;
  12102. bool Invalid = false;
  12103. if (TemplateParameterList *TemplateParams =
  12104. MatchTemplateParametersToScopeSpecifier(
  12105. TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
  12106. IsMemberSpecialization, Invalid)) {
  12107. if (TemplateParams->size() > 0) {
  12108. // This is a declaration of a class template.
  12109. if (Invalid)
  12110. return nullptr;
  12111. return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
  12112. NameLoc, Attr, TemplateParams, AS_public,
  12113. /*ModulePrivateLoc=*/SourceLocation(),
  12114. FriendLoc, TempParamLists.size() - 1,
  12115. TempParamLists.data()).get();
  12116. } else {
  12117. // The "template<>" header is extraneous.
  12118. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12119. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12120. IsMemberSpecialization = true;
  12121. }
  12122. }
  12123. if (Invalid) return nullptr;
  12124. bool isAllExplicitSpecializations = true;
  12125. for (unsigned I = TempParamLists.size(); I-- > 0; ) {
  12126. if (TempParamLists[I]->size()) {
  12127. isAllExplicitSpecializations = false;
  12128. break;
  12129. }
  12130. }
  12131. // FIXME: don't ignore attributes.
  12132. // If it's explicit specializations all the way down, just forget
  12133. // about the template header and build an appropriate non-templated
  12134. // friend. TODO: for source fidelity, remember the headers.
  12135. if (isAllExplicitSpecializations) {
  12136. if (SS.isEmpty()) {
  12137. bool Owned = false;
  12138. bool IsDependent = false;
  12139. return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
  12140. Attr, AS_public,
  12141. /*ModulePrivateLoc=*/SourceLocation(),
  12142. MultiTemplateParamsArg(), Owned, IsDependent,
  12143. /*ScopedEnumKWLoc=*/SourceLocation(),
  12144. /*ScopedEnumUsesClassTag=*/false,
  12145. /*UnderlyingType=*/TypeResult(),
  12146. /*IsTypeSpecifier=*/false,
  12147. /*IsTemplateParamOrArg=*/false);
  12148. }
  12149. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  12150. ElaboratedTypeKeyword Keyword
  12151. = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  12152. QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
  12153. *Name, NameLoc);
  12154. if (T.isNull())
  12155. return nullptr;
  12156. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  12157. if (isa<DependentNameType>(T)) {
  12158. DependentNameTypeLoc TL =
  12159. TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  12160. TL.setElaboratedKeywordLoc(TagLoc);
  12161. TL.setQualifierLoc(QualifierLoc);
  12162. TL.setNameLoc(NameLoc);
  12163. } else {
  12164. ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
  12165. TL.setElaboratedKeywordLoc(TagLoc);
  12166. TL.setQualifierLoc(QualifierLoc);
  12167. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
  12168. }
  12169. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  12170. TSI, FriendLoc, TempParamLists);
  12171. Friend->setAccess(AS_public);
  12172. CurContext->addDecl(Friend);
  12173. return Friend;
  12174. }
  12175. assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
  12176. // Handle the case of a templated-scope friend class. e.g.
  12177. // template <class T> class A<T>::B;
  12178. // FIXME: we don't support these right now.
  12179. Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
  12180. << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
  12181. ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  12182. QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
  12183. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  12184. DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  12185. TL.setElaboratedKeywordLoc(TagLoc);
  12186. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  12187. TL.setNameLoc(NameLoc);
  12188. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  12189. TSI, FriendLoc, TempParamLists);
  12190. Friend->setAccess(AS_public);
  12191. Friend->setUnsupportedFriend(true);
  12192. CurContext->addDecl(Friend);
  12193. return Friend;
  12194. }
  12195. /// Handle a friend type declaration. This works in tandem with
  12196. /// ActOnTag.
  12197. ///
  12198. /// Notes on friend class templates:
  12199. ///
  12200. /// We generally treat friend class declarations as if they were
  12201. /// declaring a class. So, for example, the elaborated type specifier
  12202. /// in a friend declaration is required to obey the restrictions of a
  12203. /// class-head (i.e. no typedefs in the scope chain), template
  12204. /// parameters are required to match up with simple template-ids, &c.
  12205. /// However, unlike when declaring a template specialization, it's
  12206. /// okay to refer to a template specialization without an empty
  12207. /// template parameter declaration, e.g.
  12208. /// friend class A<T>::B<unsigned>;
  12209. /// We permit this as a special case; if there are any template
  12210. /// parameters present at all, require proper matching, i.e.
  12211. /// template <> template \<class T> friend class A<int>::B;
  12212. Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
  12213. MultiTemplateParamsArg TempParams) {
  12214. SourceLocation Loc = DS.getBeginLoc();
  12215. assert(DS.isFriendSpecified());
  12216. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  12217. // C++ [class.friend]p3:
  12218. // A friend declaration that does not declare a function shall have one of
  12219. // the following forms:
  12220. // friend elaborated-type-specifier ;
  12221. // friend simple-type-specifier ;
  12222. // friend typename-specifier ;
  12223. //
  12224. // Any declaration with a type qualifier does not have that form. (It's
  12225. // legal to specify a qualified type as a friend, you just can't write the
  12226. // keywords.)
  12227. if (DS.getTypeQualifiers()) {
  12228. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  12229. Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
  12230. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  12231. Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
  12232. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  12233. Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
  12234. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  12235. Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
  12236. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  12237. Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
  12238. }
  12239. // Try to convert the decl specifier to a type. This works for
  12240. // friend templates because ActOnTag never produces a ClassTemplateDecl
  12241. // for a TUK_Friend.
  12242. Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
  12243. TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
  12244. QualType T = TSI->getType();
  12245. if (TheDeclarator.isInvalidType())
  12246. return nullptr;
  12247. if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
  12248. return nullptr;
  12249. // This is definitely an error in C++98. It's probably meant to
  12250. // be forbidden in C++0x, too, but the specification is just
  12251. // poorly written.
  12252. //
  12253. // The problem is with declarations like the following:
  12254. // template <T> friend A<T>::foo;
  12255. // where deciding whether a class C is a friend or not now hinges
  12256. // on whether there exists an instantiation of A that causes
  12257. // 'foo' to equal C. There are restrictions on class-heads
  12258. // (which we declare (by fiat) elaborated friend declarations to
  12259. // be) that makes this tractable.
  12260. //
  12261. // FIXME: handle "template <> friend class A<T>;", which
  12262. // is possibly well-formed? Who even knows?
  12263. if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
  12264. Diag(Loc, diag::err_tagless_friend_type_template)
  12265. << DS.getSourceRange();
  12266. return nullptr;
  12267. }
  12268. // C++98 [class.friend]p1: A friend of a class is a function
  12269. // or class that is not a member of the class . . .
  12270. // This is fixed in DR77, which just barely didn't make the C++03
  12271. // deadline. It's also a very silly restriction that seriously
  12272. // affects inner classes and which nobody else seems to implement;
  12273. // thus we never diagnose it, not even in -pedantic.
  12274. //
  12275. // But note that we could warn about it: it's always useless to
  12276. // friend one of your own members (it's not, however, worthless to
  12277. // friend a member of an arbitrary specialization of your template).
  12278. Decl *D;
  12279. if (!TempParams.empty())
  12280. D = FriendTemplateDecl::Create(Context, CurContext, Loc,
  12281. TempParams,
  12282. TSI,
  12283. DS.getFriendSpecLoc());
  12284. else
  12285. D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
  12286. if (!D)
  12287. return nullptr;
  12288. D->setAccess(AS_public);
  12289. CurContext->addDecl(D);
  12290. return D;
  12291. }
  12292. NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
  12293. MultiTemplateParamsArg TemplateParams) {
  12294. const DeclSpec &DS = D.getDeclSpec();
  12295. assert(DS.isFriendSpecified());
  12296. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  12297. SourceLocation Loc = D.getIdentifierLoc();
  12298. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12299. // C++ [class.friend]p1
  12300. // A friend of a class is a function or class....
  12301. // Note that this sees through typedefs, which is intended.
  12302. // It *doesn't* see through dependent types, which is correct
  12303. // according to [temp.arg.type]p3:
  12304. // If a declaration acquires a function type through a
  12305. // type dependent on a template-parameter and this causes
  12306. // a declaration that does not use the syntactic form of a
  12307. // function declarator to have a function type, the program
  12308. // is ill-formed.
  12309. if (!TInfo->getType()->isFunctionType()) {
  12310. Diag(Loc, diag::err_unexpected_friend);
  12311. // It might be worthwhile to try to recover by creating an
  12312. // appropriate declaration.
  12313. return nullptr;
  12314. }
  12315. // C++ [namespace.memdef]p3
  12316. // - If a friend declaration in a non-local class first declares a
  12317. // class or function, the friend class or function is a member
  12318. // of the innermost enclosing namespace.
  12319. // - The name of the friend is not found by simple name lookup
  12320. // until a matching declaration is provided in that namespace
  12321. // scope (either before or after the class declaration granting
  12322. // friendship).
  12323. // - If a friend function is called, its name may be found by the
  12324. // name lookup that considers functions from namespaces and
  12325. // classes associated with the types of the function arguments.
  12326. // - When looking for a prior declaration of a class or a function
  12327. // declared as a friend, scopes outside the innermost enclosing
  12328. // namespace scope are not considered.
  12329. CXXScopeSpec &SS = D.getCXXScopeSpec();
  12330. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  12331. DeclarationName Name = NameInfo.getName();
  12332. assert(Name);
  12333. // Check for unexpanded parameter packs.
  12334. if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
  12335. DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
  12336. DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
  12337. return nullptr;
  12338. // The context we found the declaration in, or in which we should
  12339. // create the declaration.
  12340. DeclContext *DC;
  12341. Scope *DCScope = S;
  12342. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  12343. ForExternalRedeclaration);
  12344. // There are five cases here.
  12345. // - There's no scope specifier and we're in a local class. Only look
  12346. // for functions declared in the immediately-enclosing block scope.
  12347. // We recover from invalid scope qualifiers as if they just weren't there.
  12348. FunctionDecl *FunctionContainingLocalClass = nullptr;
  12349. if ((SS.isInvalid() || !SS.isSet()) &&
  12350. (FunctionContainingLocalClass =
  12351. cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
  12352. // C++11 [class.friend]p11:
  12353. // If a friend declaration appears in a local class and the name
  12354. // specified is an unqualified name, a prior declaration is
  12355. // looked up without considering scopes that are outside the
  12356. // innermost enclosing non-class scope. For a friend function
  12357. // declaration, if there is no prior declaration, the program is
  12358. // ill-formed.
  12359. // Find the innermost enclosing non-class scope. This is the block
  12360. // scope containing the local class definition (or for a nested class,
  12361. // the outer local class).
  12362. DCScope = S->getFnParent();
  12363. // Look up the function name in the scope.
  12364. Previous.clear(LookupLocalFriendName);
  12365. LookupName(Previous, S, /*AllowBuiltinCreation*/false);
  12366. if (!Previous.empty()) {
  12367. // All possible previous declarations must have the same context:
  12368. // either they were declared at block scope or they are members of
  12369. // one of the enclosing local classes.
  12370. DC = Previous.getRepresentativeDecl()->getDeclContext();
  12371. } else {
  12372. // This is ill-formed, but provide the context that we would have
  12373. // declared the function in, if we were permitted to, for error recovery.
  12374. DC = FunctionContainingLocalClass;
  12375. }
  12376. adjustContextForLocalExternDecl(DC);
  12377. // C++ [class.friend]p6:
  12378. // A function can be defined in a friend declaration of a class if and
  12379. // only if the class is a non-local class (9.8), the function name is
  12380. // unqualified, and the function has namespace scope.
  12381. if (D.isFunctionDefinition()) {
  12382. Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
  12383. }
  12384. // - There's no scope specifier, in which case we just go to the
  12385. // appropriate scope and look for a function or function template
  12386. // there as appropriate.
  12387. } else if (SS.isInvalid() || !SS.isSet()) {
  12388. // C++11 [namespace.memdef]p3:
  12389. // If the name in a friend declaration is neither qualified nor
  12390. // a template-id and the declaration is a function or an
  12391. // elaborated-type-specifier, the lookup to determine whether
  12392. // the entity has been previously declared shall not consider
  12393. // any scopes outside the innermost enclosing namespace.
  12394. bool isTemplateId =
  12395. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
  12396. // Find the appropriate context according to the above.
  12397. DC = CurContext;
  12398. // Skip class contexts. If someone can cite chapter and verse
  12399. // for this behavior, that would be nice --- it's what GCC and
  12400. // EDG do, and it seems like a reasonable intent, but the spec
  12401. // really only says that checks for unqualified existing
  12402. // declarations should stop at the nearest enclosing namespace,
  12403. // not that they should only consider the nearest enclosing
  12404. // namespace.
  12405. while (DC->isRecord())
  12406. DC = DC->getParent();
  12407. DeclContext *LookupDC = DC;
  12408. while (LookupDC->isTransparentContext())
  12409. LookupDC = LookupDC->getParent();
  12410. while (true) {
  12411. LookupQualifiedName(Previous, LookupDC);
  12412. if (!Previous.empty()) {
  12413. DC = LookupDC;
  12414. break;
  12415. }
  12416. if (isTemplateId) {
  12417. if (isa<TranslationUnitDecl>(LookupDC)) break;
  12418. } else {
  12419. if (LookupDC->isFileContext()) break;
  12420. }
  12421. LookupDC = LookupDC->getParent();
  12422. }
  12423. DCScope = getScopeForDeclContext(S, DC);
  12424. // - There's a non-dependent scope specifier, in which case we
  12425. // compute it and do a previous lookup there for a function
  12426. // or function template.
  12427. } else if (!SS.getScopeRep()->isDependent()) {
  12428. DC = computeDeclContext(SS);
  12429. if (!DC) return nullptr;
  12430. if (RequireCompleteDeclContext(SS, DC)) return nullptr;
  12431. LookupQualifiedName(Previous, DC);
  12432. // Ignore things found implicitly in the wrong scope.
  12433. // TODO: better diagnostics for this case. Suggesting the right
  12434. // qualified scope would be nice...
  12435. LookupResult::Filter F = Previous.makeFilter();
  12436. while (F.hasNext()) {
  12437. NamedDecl *D = F.next();
  12438. if (!DC->InEnclosingNamespaceSetOf(
  12439. D->getDeclContext()->getRedeclContext()))
  12440. F.erase();
  12441. }
  12442. F.done();
  12443. if (Previous.empty()) {
  12444. D.setInvalidType();
  12445. Diag(Loc, diag::err_qualified_friend_not_found)
  12446. << Name << TInfo->getType();
  12447. return nullptr;
  12448. }
  12449. // C++ [class.friend]p1: A friend of a class is a function or
  12450. // class that is not a member of the class . . .
  12451. if (DC->Equals(CurContext))
  12452. Diag(DS.getFriendSpecLoc(),
  12453. getLangOpts().CPlusPlus11 ?
  12454. diag::warn_cxx98_compat_friend_is_member :
  12455. diag::err_friend_is_member);
  12456. if (D.isFunctionDefinition()) {
  12457. // C++ [class.friend]p6:
  12458. // A function can be defined in a friend declaration of a class if and
  12459. // only if the class is a non-local class (9.8), the function name is
  12460. // unqualified, and the function has namespace scope.
  12461. SemaDiagnosticBuilder DB
  12462. = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
  12463. DB << SS.getScopeRep();
  12464. if (DC->isFileContext())
  12465. DB << FixItHint::CreateRemoval(SS.getRange());
  12466. SS.clear();
  12467. }
  12468. // - There's a scope specifier that does not match any template
  12469. // parameter lists, in which case we use some arbitrary context,
  12470. // create a method or method template, and wait for instantiation.
  12471. // - There's a scope specifier that does match some template
  12472. // parameter lists, which we don't handle right now.
  12473. } else {
  12474. if (D.isFunctionDefinition()) {
  12475. // C++ [class.friend]p6:
  12476. // A function can be defined in a friend declaration of a class if and
  12477. // only if the class is a non-local class (9.8), the function name is
  12478. // unqualified, and the function has namespace scope.
  12479. Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
  12480. << SS.getScopeRep();
  12481. }
  12482. DC = CurContext;
  12483. assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
  12484. }
  12485. if (!DC->isRecord()) {
  12486. int DiagArg = -1;
  12487. switch (D.getName().getKind()) {
  12488. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  12489. case UnqualifiedIdKind::IK_ConstructorName:
  12490. DiagArg = 0;
  12491. break;
  12492. case UnqualifiedIdKind::IK_DestructorName:
  12493. DiagArg = 1;
  12494. break;
  12495. case UnqualifiedIdKind::IK_ConversionFunctionId:
  12496. DiagArg = 2;
  12497. break;
  12498. case UnqualifiedIdKind::IK_DeductionGuideName:
  12499. DiagArg = 3;
  12500. break;
  12501. case UnqualifiedIdKind::IK_Identifier:
  12502. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  12503. case UnqualifiedIdKind::IK_LiteralOperatorId:
  12504. case UnqualifiedIdKind::IK_OperatorFunctionId:
  12505. case UnqualifiedIdKind::IK_TemplateId:
  12506. break;
  12507. }
  12508. // This implies that it has to be an operator or function.
  12509. if (DiagArg >= 0) {
  12510. Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
  12511. return nullptr;
  12512. }
  12513. }
  12514. // FIXME: This is an egregious hack to cope with cases where the scope stack
  12515. // does not contain the declaration context, i.e., in an out-of-line
  12516. // definition of a class.
  12517. Scope FakeDCScope(S, Scope::DeclScope, Diags);
  12518. if (!DCScope) {
  12519. FakeDCScope.setEntity(DC);
  12520. DCScope = &FakeDCScope;
  12521. }
  12522. bool AddToScope = true;
  12523. NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
  12524. TemplateParams, AddToScope);
  12525. if (!ND) return nullptr;
  12526. assert(ND->getLexicalDeclContext() == CurContext);
  12527. // If we performed typo correction, we might have added a scope specifier
  12528. // and changed the decl context.
  12529. DC = ND->getDeclContext();
  12530. // Add the function declaration to the appropriate lookup tables,
  12531. // adjusting the redeclarations list as necessary. We don't
  12532. // want to do this yet if the friending class is dependent.
  12533. //
  12534. // Also update the scope-based lookup if the target context's
  12535. // lookup context is in lexical scope.
  12536. if (!CurContext->isDependentContext()) {
  12537. DC = DC->getRedeclContext();
  12538. DC->makeDeclVisibleInContext(ND);
  12539. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  12540. PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
  12541. }
  12542. FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
  12543. D.getIdentifierLoc(), ND,
  12544. DS.getFriendSpecLoc());
  12545. FrD->setAccess(AS_public);
  12546. CurContext->addDecl(FrD);
  12547. if (ND->isInvalidDecl()) {
  12548. FrD->setInvalidDecl();
  12549. } else {
  12550. if (DC->isRecord()) CheckFriendAccess(ND);
  12551. FunctionDecl *FD;
  12552. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  12553. FD = FTD->getTemplatedDecl();
  12554. else
  12555. FD = cast<FunctionDecl>(ND);
  12556. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
  12557. // default argument expression, that declaration shall be a definition
  12558. // and shall be the only declaration of the function or function
  12559. // template in the translation unit.
  12560. if (functionDeclHasDefaultArgument(FD)) {
  12561. // We can't look at FD->getPreviousDecl() because it may not have been set
  12562. // if we're in a dependent context. If the function is known to be a
  12563. // redeclaration, we will have narrowed Previous down to the right decl.
  12564. if (D.isRedeclaration()) {
  12565. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  12566. Diag(Previous.getRepresentativeDecl()->getLocation(),
  12567. diag::note_previous_declaration);
  12568. } else if (!D.isFunctionDefinition())
  12569. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
  12570. }
  12571. // Mark templated-scope function declarations as unsupported.
  12572. if (FD->getNumTemplateParameterLists() && SS.isValid()) {
  12573. Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
  12574. << SS.getScopeRep() << SS.getRange()
  12575. << cast<CXXRecordDecl>(CurContext);
  12576. FrD->setUnsupportedFriend(true);
  12577. }
  12578. }
  12579. return ND;
  12580. }
  12581. void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
  12582. AdjustDeclIfTemplate(Dcl);
  12583. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
  12584. if (!Fn) {
  12585. Diag(DelLoc, diag::err_deleted_non_function);
  12586. return;
  12587. }
  12588. // Deleted function does not have a body.
  12589. Fn->setWillHaveBody(false);
  12590. if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
  12591. // Don't consider the implicit declaration we generate for explicit
  12592. // specializations. FIXME: Do not generate these implicit declarations.
  12593. if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
  12594. Prev->getPreviousDecl()) &&
  12595. !Prev->isDefined()) {
  12596. Diag(DelLoc, diag::err_deleted_decl_not_first);
  12597. Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
  12598. Prev->isImplicit() ? diag::note_previous_implicit_declaration
  12599. : diag::note_previous_declaration);
  12600. }
  12601. // If the declaration wasn't the first, we delete the function anyway for
  12602. // recovery.
  12603. Fn = Fn->getCanonicalDecl();
  12604. }
  12605. // dllimport/dllexport cannot be deleted.
  12606. if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
  12607. Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
  12608. Fn->setInvalidDecl();
  12609. }
  12610. if (Fn->isDeleted())
  12611. return;
  12612. // See if we're deleting a function which is already known to override a
  12613. // non-deleted virtual function.
  12614. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
  12615. bool IssuedDiagnostic = false;
  12616. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  12617. if (!(*MD->begin_overridden_methods())->isDeleted()) {
  12618. if (!IssuedDiagnostic) {
  12619. Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
  12620. IssuedDiagnostic = true;
  12621. }
  12622. Diag(O->getLocation(), diag::note_overridden_virtual_function);
  12623. }
  12624. }
  12625. // If this function was implicitly deleted because it was defaulted,
  12626. // explain why it was deleted.
  12627. if (IssuedDiagnostic && MD->isDefaulted())
  12628. ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
  12629. /*Diagnose*/true);
  12630. }
  12631. // C++11 [basic.start.main]p3:
  12632. // A program that defines main as deleted [...] is ill-formed.
  12633. if (Fn->isMain())
  12634. Diag(DelLoc, diag::err_deleted_main);
  12635. // C++11 [dcl.fct.def.delete]p4:
  12636. // A deleted function is implicitly inline.
  12637. Fn->setImplicitlyInline();
  12638. Fn->setDeletedAsWritten();
  12639. }
  12640. void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
  12641. CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
  12642. if (MD) {
  12643. if (MD->getParent()->isDependentType()) {
  12644. MD->setDefaulted();
  12645. MD->setExplicitlyDefaulted();
  12646. return;
  12647. }
  12648. CXXSpecialMember Member = getSpecialMember(MD);
  12649. if (Member == CXXInvalid) {
  12650. if (!MD->isInvalidDecl())
  12651. Diag(DefaultLoc, diag::err_default_special_members);
  12652. return;
  12653. }
  12654. MD->setDefaulted();
  12655. MD->setExplicitlyDefaulted();
  12656. // Unset that we will have a body for this function. We might not,
  12657. // if it turns out to be trivial, and we don't need this marking now
  12658. // that we've marked it as defaulted.
  12659. MD->setWillHaveBody(false);
  12660. // If this definition appears within the record, do the checking when
  12661. // the record is complete.
  12662. const FunctionDecl *Primary = MD;
  12663. if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
  12664. // Ask the template instantiation pattern that actually had the
  12665. // '= default' on it.
  12666. Primary = Pattern;
  12667. // If the method was defaulted on its first declaration, we will have
  12668. // already performed the checking in CheckCompletedCXXClass. Such a
  12669. // declaration doesn't trigger an implicit definition.
  12670. if (Primary->getCanonicalDecl()->isDefaulted())
  12671. return;
  12672. CheckExplicitlyDefaultedSpecialMember(MD);
  12673. if (!MD->isInvalidDecl())
  12674. DefineImplicitSpecialMember(*this, MD, DefaultLoc);
  12675. } else {
  12676. Diag(DefaultLoc, diag::err_default_special_members);
  12677. }
  12678. }
  12679. static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
  12680. for (Stmt *SubStmt : S->children()) {
  12681. if (!SubStmt)
  12682. continue;
  12683. if (isa<ReturnStmt>(SubStmt))
  12684. Self.Diag(SubStmt->getBeginLoc(),
  12685. diag::err_return_in_constructor_handler);
  12686. if (!isa<Expr>(SubStmt))
  12687. SearchForReturnInStmt(Self, SubStmt);
  12688. }
  12689. }
  12690. void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
  12691. for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
  12692. CXXCatchStmt *Handler = TryBlock->getHandler(I);
  12693. SearchForReturnInStmt(*this, Handler);
  12694. }
  12695. }
  12696. bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  12697. const CXXMethodDecl *Old) {
  12698. const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
  12699. const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
  12700. if (OldFT->hasExtParameterInfos()) {
  12701. for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
  12702. // A parameter of the overriding method should be annotated with noescape
  12703. // if the corresponding parameter of the overridden method is annotated.
  12704. if (OldFT->getExtParameterInfo(I).isNoEscape() &&
  12705. !NewFT->getExtParameterInfo(I).isNoEscape()) {
  12706. Diag(New->getParamDecl(I)->getLocation(),
  12707. diag::warn_overriding_method_missing_noescape);
  12708. Diag(Old->getParamDecl(I)->getLocation(),
  12709. diag::note_overridden_marked_noescape);
  12710. }
  12711. }
  12712. // Virtual overrides must have the same code_seg.
  12713. const auto *OldCSA = Old->getAttr<CodeSegAttr>();
  12714. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  12715. if ((NewCSA || OldCSA) &&
  12716. (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
  12717. Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
  12718. Diag(Old->getLocation(), diag::note_previous_declaration);
  12719. return true;
  12720. }
  12721. CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
  12722. // If the calling conventions match, everything is fine
  12723. if (NewCC == OldCC)
  12724. return false;
  12725. // If the calling conventions mismatch because the new function is static,
  12726. // suppress the calling convention mismatch error; the error about static
  12727. // function override (err_static_overrides_virtual from
  12728. // Sema::CheckFunctionDeclaration) is more clear.
  12729. if (New->getStorageClass() == SC_Static)
  12730. return false;
  12731. Diag(New->getLocation(),
  12732. diag::err_conflicting_overriding_cc_attributes)
  12733. << New->getDeclName() << New->getType() << Old->getType();
  12734. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  12735. return true;
  12736. }
  12737. bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
  12738. const CXXMethodDecl *Old) {
  12739. QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
  12740. QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
  12741. if (Context.hasSameType(NewTy, OldTy) ||
  12742. NewTy->isDependentType() || OldTy->isDependentType())
  12743. return false;
  12744. // Check if the return types are covariant
  12745. QualType NewClassTy, OldClassTy;
  12746. /// Both types must be pointers or references to classes.
  12747. if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
  12748. if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
  12749. NewClassTy = NewPT->getPointeeType();
  12750. OldClassTy = OldPT->getPointeeType();
  12751. }
  12752. } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
  12753. if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
  12754. if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
  12755. NewClassTy = NewRT->getPointeeType();
  12756. OldClassTy = OldRT->getPointeeType();
  12757. }
  12758. }
  12759. }
  12760. // The return types aren't either both pointers or references to a class type.
  12761. if (NewClassTy.isNull()) {
  12762. Diag(New->getLocation(),
  12763. diag::err_different_return_type_for_overriding_virtual_function)
  12764. << New->getDeclName() << NewTy << OldTy
  12765. << New->getReturnTypeSourceRange();
  12766. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12767. << Old->getReturnTypeSourceRange();
  12768. return true;
  12769. }
  12770. if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
  12771. // C++14 [class.virtual]p8:
  12772. // If the class type in the covariant return type of D::f differs from
  12773. // that of B::f, the class type in the return type of D::f shall be
  12774. // complete at the point of declaration of D::f or shall be the class
  12775. // type D.
  12776. if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
  12777. if (!RT->isBeingDefined() &&
  12778. RequireCompleteType(New->getLocation(), NewClassTy,
  12779. diag::err_covariant_return_incomplete,
  12780. New->getDeclName()))
  12781. return true;
  12782. }
  12783. // Check if the new class derives from the old class.
  12784. if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
  12785. Diag(New->getLocation(), diag::err_covariant_return_not_derived)
  12786. << New->getDeclName() << NewTy << OldTy
  12787. << New->getReturnTypeSourceRange();
  12788. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12789. << Old->getReturnTypeSourceRange();
  12790. return true;
  12791. }
  12792. // Check if we the conversion from derived to base is valid.
  12793. if (CheckDerivedToBaseConversion(
  12794. NewClassTy, OldClassTy,
  12795. diag::err_covariant_return_inaccessible_base,
  12796. diag::err_covariant_return_ambiguous_derived_to_base_conv,
  12797. New->getLocation(), New->getReturnTypeSourceRange(),
  12798. New->getDeclName(), nullptr)) {
  12799. // FIXME: this note won't trigger for delayed access control
  12800. // diagnostics, and it's impossible to get an undelayed error
  12801. // here from access control during the original parse because
  12802. // the ParsingDeclSpec/ParsingDeclarator are still in scope.
  12803. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12804. << Old->getReturnTypeSourceRange();
  12805. return true;
  12806. }
  12807. }
  12808. // The qualifiers of the return types must be the same.
  12809. if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
  12810. Diag(New->getLocation(),
  12811. diag::err_covariant_return_type_different_qualifications)
  12812. << New->getDeclName() << NewTy << OldTy
  12813. << New->getReturnTypeSourceRange();
  12814. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12815. << Old->getReturnTypeSourceRange();
  12816. return true;
  12817. }
  12818. // The new class type must have the same or less qualifiers as the old type.
  12819. if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
  12820. Diag(New->getLocation(),
  12821. diag::err_covariant_return_type_class_type_more_qualified)
  12822. << New->getDeclName() << NewTy << OldTy
  12823. << New->getReturnTypeSourceRange();
  12824. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12825. << Old->getReturnTypeSourceRange();
  12826. return true;
  12827. }
  12828. return false;
  12829. }
  12830. /// Mark the given method pure.
  12831. ///
  12832. /// \param Method the method to be marked pure.
  12833. ///
  12834. /// \param InitRange the source range that covers the "0" initializer.
  12835. bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
  12836. SourceLocation EndLoc = InitRange.getEnd();
  12837. if (EndLoc.isValid())
  12838. Method->setRangeEnd(EndLoc);
  12839. if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
  12840. Method->setPure();
  12841. return false;
  12842. }
  12843. if (!Method->isInvalidDecl())
  12844. Diag(Method->getLocation(), diag::err_non_virtual_pure)
  12845. << Method->getDeclName() << InitRange;
  12846. return true;
  12847. }
  12848. void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
  12849. if (D->getFriendObjectKind())
  12850. Diag(D->getLocation(), diag::err_pure_friend);
  12851. else if (auto *M = dyn_cast<CXXMethodDecl>(D))
  12852. CheckPureMethod(M, ZeroLoc);
  12853. else
  12854. Diag(D->getLocation(), diag::err_illegal_initializer);
  12855. }
  12856. /// Determine whether the given declaration is a global variable or
  12857. /// static data member.
  12858. static bool isNonlocalVariable(const Decl *D) {
  12859. if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
  12860. return Var->hasGlobalStorage();
  12861. return false;
  12862. }
  12863. /// Invoked when we are about to parse an initializer for the declaration
  12864. /// 'Dcl'.
  12865. ///
  12866. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
  12867. /// static data member of class X, names should be looked up in the scope of
  12868. /// class X. If the declaration had a scope specifier, a scope will have
  12869. /// been created and passed in for this purpose. Otherwise, S will be null.
  12870. void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
  12871. // If there is no declaration, there was an error parsing it.
  12872. if (!D || D->isInvalidDecl())
  12873. return;
  12874. // We will always have a nested name specifier here, but this declaration
  12875. // might not be out of line if the specifier names the current namespace:
  12876. // extern int n;
  12877. // int ::n = 0;
  12878. if (S && D->isOutOfLine())
  12879. EnterDeclaratorContext(S, D->getDeclContext());
  12880. // If we are parsing the initializer for a static data member, push a
  12881. // new expression evaluation context that is associated with this static
  12882. // data member.
  12883. if (isNonlocalVariable(D))
  12884. PushExpressionEvaluationContext(
  12885. ExpressionEvaluationContext::PotentiallyEvaluated, D);
  12886. }
  12887. /// Invoked after we are finished parsing an initializer for the declaration D.
  12888. void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
  12889. // If there is no declaration, there was an error parsing it.
  12890. if (!D || D->isInvalidDecl())
  12891. return;
  12892. if (isNonlocalVariable(D))
  12893. PopExpressionEvaluationContext();
  12894. if (S && D->isOutOfLine())
  12895. ExitDeclaratorContext(S);
  12896. }
  12897. /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
  12898. /// C++ if/switch/while/for statement.
  12899. /// e.g: "if (int x = f()) {...}"
  12900. DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
  12901. // C++ 6.4p2:
  12902. // The declarator shall not specify a function or an array.
  12903. // The type-specifier-seq shall not contain typedef and shall not declare a
  12904. // new class or enumeration.
  12905. assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  12906. "Parser allowed 'typedef' as storage class of condition decl.");
  12907. Decl *Dcl = ActOnDeclarator(S, D);
  12908. if (!Dcl)
  12909. return true;
  12910. if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
  12911. Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
  12912. << D.getSourceRange();
  12913. return true;
  12914. }
  12915. return Dcl;
  12916. }
  12917. void Sema::LoadExternalVTableUses() {
  12918. if (!ExternalSource)
  12919. return;
  12920. SmallVector<ExternalVTableUse, 4> VTables;
  12921. ExternalSource->ReadUsedVTables(VTables);
  12922. SmallVector<VTableUse, 4> NewUses;
  12923. for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
  12924. llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
  12925. = VTablesUsed.find(VTables[I].Record);
  12926. // Even if a definition wasn't required before, it may be required now.
  12927. if (Pos != VTablesUsed.end()) {
  12928. if (!Pos->second && VTables[I].DefinitionRequired)
  12929. Pos->second = true;
  12930. continue;
  12931. }
  12932. VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
  12933. NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
  12934. }
  12935. VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
  12936. }
  12937. void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
  12938. bool DefinitionRequired) {
  12939. // Ignore any vtable uses in unevaluated operands or for classes that do
  12940. // not have a vtable.
  12941. if (!Class->isDynamicClass() || Class->isDependentContext() ||
  12942. CurContext->isDependentContext() || isUnevaluatedContext())
  12943. return;
  12944. // Do not mark as used if compiling for the device outside of the target
  12945. // region.
  12946. if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  12947. !isInOpenMPDeclareTargetContext() &&
  12948. !isInOpenMPTargetExecutionDirective()) {
  12949. if (!DefinitionRequired)
  12950. MarkVirtualMembersReferenced(Loc, Class);
  12951. return;
  12952. }
  12953. // Try to insert this class into the map.
  12954. LoadExternalVTableUses();
  12955. Class = Class->getCanonicalDecl();
  12956. std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
  12957. Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
  12958. if (!Pos.second) {
  12959. // If we already had an entry, check to see if we are promoting this vtable
  12960. // to require a definition. If so, we need to reappend to the VTableUses
  12961. // list, since we may have already processed the first entry.
  12962. if (DefinitionRequired && !Pos.first->second) {
  12963. Pos.first->second = true;
  12964. } else {
  12965. // Otherwise, we can early exit.
  12966. return;
  12967. }
  12968. } else {
  12969. // The Microsoft ABI requires that we perform the destructor body
  12970. // checks (i.e. operator delete() lookup) when the vtable is marked used, as
  12971. // the deleting destructor is emitted with the vtable, not with the
  12972. // destructor definition as in the Itanium ABI.
  12973. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  12974. CXXDestructorDecl *DD = Class->getDestructor();
  12975. if (DD && DD->isVirtual() && !DD->isDeleted()) {
  12976. if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
  12977. // If this is an out-of-line declaration, marking it referenced will
  12978. // not do anything. Manually call CheckDestructor to look up operator
  12979. // delete().
  12980. ContextRAII SavedContext(*this, DD);
  12981. CheckDestructor(DD);
  12982. } else {
  12983. MarkFunctionReferenced(Loc, Class->getDestructor());
  12984. }
  12985. }
  12986. }
  12987. }
  12988. // Local classes need to have their virtual members marked
  12989. // immediately. For all other classes, we mark their virtual members
  12990. // at the end of the translation unit.
  12991. if (Class->isLocalClass())
  12992. MarkVirtualMembersReferenced(Loc, Class);
  12993. else
  12994. VTableUses.push_back(std::make_pair(Class, Loc));
  12995. }
  12996. bool Sema::DefineUsedVTables() {
  12997. LoadExternalVTableUses();
  12998. if (VTableUses.empty())
  12999. return false;
  13000. // Note: The VTableUses vector could grow as a result of marking
  13001. // the members of a class as "used", so we check the size each
  13002. // time through the loop and prefer indices (which are stable) to
  13003. // iterators (which are not).
  13004. bool DefinedAnything = false;
  13005. for (unsigned I = 0; I != VTableUses.size(); ++I) {
  13006. CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
  13007. if (!Class)
  13008. continue;
  13009. TemplateSpecializationKind ClassTSK =
  13010. Class->getTemplateSpecializationKind();
  13011. SourceLocation Loc = VTableUses[I].second;
  13012. bool DefineVTable = true;
  13013. // If this class has a key function, but that key function is
  13014. // defined in another translation unit, we don't need to emit the
  13015. // vtable even though we're using it.
  13016. const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
  13017. if (KeyFunction && !KeyFunction->hasBody()) {
  13018. // The key function is in another translation unit.
  13019. DefineVTable = false;
  13020. TemplateSpecializationKind TSK =
  13021. KeyFunction->getTemplateSpecializationKind();
  13022. assert(TSK != TSK_ExplicitInstantiationDefinition &&
  13023. TSK != TSK_ImplicitInstantiation &&
  13024. "Instantiations don't have key functions");
  13025. (void)TSK;
  13026. } else if (!KeyFunction) {
  13027. // If we have a class with no key function that is the subject
  13028. // of an explicit instantiation declaration, suppress the
  13029. // vtable; it will live with the explicit instantiation
  13030. // definition.
  13031. bool IsExplicitInstantiationDeclaration =
  13032. ClassTSK == TSK_ExplicitInstantiationDeclaration;
  13033. for (auto R : Class->redecls()) {
  13034. TemplateSpecializationKind TSK
  13035. = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
  13036. if (TSK == TSK_ExplicitInstantiationDeclaration)
  13037. IsExplicitInstantiationDeclaration = true;
  13038. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  13039. IsExplicitInstantiationDeclaration = false;
  13040. break;
  13041. }
  13042. }
  13043. if (IsExplicitInstantiationDeclaration)
  13044. DefineVTable = false;
  13045. }
  13046. // The exception specifications for all virtual members may be needed even
  13047. // if we are not providing an authoritative form of the vtable in this TU.
  13048. // We may choose to emit it available_externally anyway.
  13049. if (!DefineVTable) {
  13050. MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
  13051. continue;
  13052. }
  13053. // Mark all of the virtual members of this class as referenced, so
  13054. // that we can build a vtable. Then, tell the AST consumer that a
  13055. // vtable for this class is required.
  13056. DefinedAnything = true;
  13057. MarkVirtualMembersReferenced(Loc, Class);
  13058. CXXRecordDecl *Canonical = Class->getCanonicalDecl();
  13059. if (VTablesUsed[Canonical])
  13060. Consumer.HandleVTable(Class);
  13061. // Warn if we're emitting a weak vtable. The vtable will be weak if there is
  13062. // no key function or the key function is inlined. Don't warn in C++ ABIs
  13063. // that lack key functions, since the user won't be able to make one.
  13064. if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
  13065. Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
  13066. const FunctionDecl *KeyFunctionDef = nullptr;
  13067. if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
  13068. KeyFunctionDef->isInlined())) {
  13069. Diag(Class->getLocation(),
  13070. ClassTSK == TSK_ExplicitInstantiationDefinition
  13071. ? diag::warn_weak_template_vtable
  13072. : diag::warn_weak_vtable)
  13073. << Class;
  13074. }
  13075. }
  13076. }
  13077. VTableUses.clear();
  13078. return DefinedAnything;
  13079. }
  13080. void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
  13081. const CXXRecordDecl *RD) {
  13082. for (const auto *I : RD->methods())
  13083. if (I->isVirtual() && !I->isPure())
  13084. ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
  13085. }
  13086. void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
  13087. const CXXRecordDecl *RD) {
  13088. // Mark all functions which will appear in RD's vtable as used.
  13089. CXXFinalOverriderMap FinalOverriders;
  13090. RD->getFinalOverriders(FinalOverriders);
  13091. for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
  13092. E = FinalOverriders.end();
  13093. I != E; ++I) {
  13094. for (OverridingMethods::const_iterator OI = I->second.begin(),
  13095. OE = I->second.end();
  13096. OI != OE; ++OI) {
  13097. assert(OI->second.size() > 0 && "no final overrider");
  13098. CXXMethodDecl *Overrider = OI->second.front().Method;
  13099. // C++ [basic.def.odr]p2:
  13100. // [...] A virtual member function is used if it is not pure. [...]
  13101. if (!Overrider->isPure())
  13102. MarkFunctionReferenced(Loc, Overrider);
  13103. }
  13104. }
  13105. // Only classes that have virtual bases need a VTT.
  13106. if (RD->getNumVBases() == 0)
  13107. return;
  13108. for (const auto &I : RD->bases()) {
  13109. const CXXRecordDecl *Base =
  13110. cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  13111. if (Base->getNumVBases() == 0)
  13112. continue;
  13113. MarkVirtualMembersReferenced(Loc, Base);
  13114. }
  13115. }
  13116. /// SetIvarInitializers - This routine builds initialization ASTs for the
  13117. /// Objective-C implementation whose ivars need be initialized.
  13118. void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
  13119. if (!getLangOpts().CPlusPlus)
  13120. return;
  13121. if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
  13122. SmallVector<ObjCIvarDecl*, 8> ivars;
  13123. CollectIvarsToConstructOrDestruct(OID, ivars);
  13124. if (ivars.empty())
  13125. return;
  13126. SmallVector<CXXCtorInitializer*, 32> AllToInit;
  13127. for (unsigned i = 0; i < ivars.size(); i++) {
  13128. FieldDecl *Field = ivars[i];
  13129. if (Field->isInvalidDecl())
  13130. continue;
  13131. CXXCtorInitializer *Member;
  13132. InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
  13133. InitializationKind InitKind =
  13134. InitializationKind::CreateDefault(ObjCImplementation->getLocation());
  13135. InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
  13136. ExprResult MemberInit =
  13137. InitSeq.Perform(*this, InitEntity, InitKind, None);
  13138. MemberInit = MaybeCreateExprWithCleanups(MemberInit);
  13139. // Note, MemberInit could actually come back empty if no initialization
  13140. // is required (e.g., because it would call a trivial default constructor)
  13141. if (!MemberInit.get() || MemberInit.isInvalid())
  13142. continue;
  13143. Member =
  13144. new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
  13145. SourceLocation(),
  13146. MemberInit.getAs<Expr>(),
  13147. SourceLocation());
  13148. AllToInit.push_back(Member);
  13149. // Be sure that the destructor is accessible and is marked as referenced.
  13150. if (const RecordType *RecordTy =
  13151. Context.getBaseElementType(Field->getType())
  13152. ->getAs<RecordType>()) {
  13153. CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  13154. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  13155. MarkFunctionReferenced(Field->getLocation(), Destructor);
  13156. CheckDestructorAccess(Field->getLocation(), Destructor,
  13157. PDiag(diag::err_access_dtor_ivar)
  13158. << Context.getBaseElementType(Field->getType()));
  13159. }
  13160. }
  13161. }
  13162. ObjCImplementation->setIvarInitializers(Context,
  13163. AllToInit.data(), AllToInit.size());
  13164. }
  13165. }
  13166. static
  13167. void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
  13168. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
  13169. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
  13170. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
  13171. Sema &S) {
  13172. if (Ctor->isInvalidDecl())
  13173. return;
  13174. CXXConstructorDecl *Target = Ctor->getTargetConstructor();
  13175. // Target may not be determinable yet, for instance if this is a dependent
  13176. // call in an uninstantiated template.
  13177. if (Target) {
  13178. const FunctionDecl *FNTarget = nullptr;
  13179. (void)Target->hasBody(FNTarget);
  13180. Target = const_cast<CXXConstructorDecl*>(
  13181. cast_or_null<CXXConstructorDecl>(FNTarget));
  13182. }
  13183. CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
  13184. // Avoid dereferencing a null pointer here.
  13185. *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
  13186. if (!Current.insert(Canonical).second)
  13187. return;
  13188. // We know that beyond here, we aren't chaining into a cycle.
  13189. if (!Target || !Target->isDelegatingConstructor() ||
  13190. Target->isInvalidDecl() || Valid.count(TCanonical)) {
  13191. Valid.insert(Current.begin(), Current.end());
  13192. Current.clear();
  13193. // We've hit a cycle.
  13194. } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
  13195. Current.count(TCanonical)) {
  13196. // If we haven't diagnosed this cycle yet, do so now.
  13197. if (!Invalid.count(TCanonical)) {
  13198. S.Diag((*Ctor->init_begin())->getSourceLocation(),
  13199. diag::warn_delegating_ctor_cycle)
  13200. << Ctor;
  13201. // Don't add a note for a function delegating directly to itself.
  13202. if (TCanonical != Canonical)
  13203. S.Diag(Target->getLocation(), diag::note_it_delegates_to);
  13204. CXXConstructorDecl *C = Target;
  13205. while (C->getCanonicalDecl() != Canonical) {
  13206. const FunctionDecl *FNTarget = nullptr;
  13207. (void)C->getTargetConstructor()->hasBody(FNTarget);
  13208. assert(FNTarget && "Ctor cycle through bodiless function");
  13209. C = const_cast<CXXConstructorDecl*>(
  13210. cast<CXXConstructorDecl>(FNTarget));
  13211. S.Diag(C->getLocation(), diag::note_which_delegates_to);
  13212. }
  13213. }
  13214. Invalid.insert(Current.begin(), Current.end());
  13215. Current.clear();
  13216. } else {
  13217. DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
  13218. }
  13219. }
  13220. void Sema::CheckDelegatingCtorCycles() {
  13221. llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
  13222. for (DelegatingCtorDeclsType::iterator
  13223. I = DelegatingCtorDecls.begin(ExternalSource),
  13224. E = DelegatingCtorDecls.end();
  13225. I != E; ++I)
  13226. DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
  13227. for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
  13228. (*CI)->setInvalidDecl();
  13229. }
  13230. namespace {
  13231. /// AST visitor that finds references to the 'this' expression.
  13232. class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
  13233. Sema &S;
  13234. public:
  13235. explicit FindCXXThisExpr(Sema &S) : S(S) { }
  13236. bool VisitCXXThisExpr(CXXThisExpr *E) {
  13237. S.Diag(E->getLocation(), diag::err_this_static_member_func)
  13238. << E->isImplicit();
  13239. return false;
  13240. }
  13241. };
  13242. }
  13243. bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
  13244. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  13245. if (!TSInfo)
  13246. return false;
  13247. TypeLoc TL = TSInfo->getTypeLoc();
  13248. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  13249. if (!ProtoTL)
  13250. return false;
  13251. // C++11 [expr.prim.general]p3:
  13252. // [The expression this] shall not appear before the optional
  13253. // cv-qualifier-seq and it shall not appear within the declaration of a
  13254. // static member function (although its type and value category are defined
  13255. // within a static member function as they are within a non-static member
  13256. // function). [ Note: this is because declaration matching does not occur
  13257. // until the complete declarator is known. - end note ]
  13258. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  13259. FindCXXThisExpr Finder(*this);
  13260. // If the return type came after the cv-qualifier-seq, check it now.
  13261. if (Proto->hasTrailingReturn() &&
  13262. !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
  13263. return true;
  13264. // Check the exception specification.
  13265. if (checkThisInStaticMemberFunctionExceptionSpec(Method))
  13266. return true;
  13267. return checkThisInStaticMemberFunctionAttributes(Method);
  13268. }
  13269. bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
  13270. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  13271. if (!TSInfo)
  13272. return false;
  13273. TypeLoc TL = TSInfo->getTypeLoc();
  13274. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  13275. if (!ProtoTL)
  13276. return false;
  13277. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  13278. FindCXXThisExpr Finder(*this);
  13279. switch (Proto->getExceptionSpecType()) {
  13280. case EST_Unparsed:
  13281. case EST_Uninstantiated:
  13282. case EST_Unevaluated:
  13283. case EST_BasicNoexcept:
  13284. case EST_DynamicNone:
  13285. case EST_MSAny:
  13286. case EST_None:
  13287. break;
  13288. case EST_DependentNoexcept:
  13289. case EST_NoexceptFalse:
  13290. case EST_NoexceptTrue:
  13291. if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
  13292. return true;
  13293. LLVM_FALLTHROUGH;
  13294. case EST_Dynamic:
  13295. for (const auto &E : Proto->exceptions()) {
  13296. if (!Finder.TraverseType(E))
  13297. return true;
  13298. }
  13299. break;
  13300. }
  13301. return false;
  13302. }
  13303. bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
  13304. FindCXXThisExpr Finder(*this);
  13305. // Check attributes.
  13306. for (const auto *A : Method->attrs()) {
  13307. // FIXME: This should be emitted by tblgen.
  13308. Expr *Arg = nullptr;
  13309. ArrayRef<Expr *> Args;
  13310. if (const auto *G = dyn_cast<GuardedByAttr>(A))
  13311. Arg = G->getArg();
  13312. else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
  13313. Arg = G->getArg();
  13314. else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
  13315. Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
  13316. else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
  13317. Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
  13318. else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
  13319. Arg = ETLF->getSuccessValue();
  13320. Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
  13321. } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
  13322. Arg = STLF->getSuccessValue();
  13323. Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
  13324. } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
  13325. Arg = LR->getArg();
  13326. else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
  13327. Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
  13328. else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
  13329. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  13330. else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
  13331. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  13332. else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
  13333. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  13334. else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
  13335. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  13336. if (Arg && !Finder.TraverseStmt(Arg))
  13337. return true;
  13338. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  13339. if (!Finder.TraverseStmt(Args[I]))
  13340. return true;
  13341. }
  13342. }
  13343. return false;
  13344. }
  13345. void Sema::checkExceptionSpecification(
  13346. bool IsTopLevel, ExceptionSpecificationType EST,
  13347. ArrayRef<ParsedType> DynamicExceptions,
  13348. ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
  13349. SmallVectorImpl<QualType> &Exceptions,
  13350. FunctionProtoType::ExceptionSpecInfo &ESI) {
  13351. Exceptions.clear();
  13352. ESI.Type = EST;
  13353. if (EST == EST_Dynamic) {
  13354. Exceptions.reserve(DynamicExceptions.size());
  13355. for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
  13356. // FIXME: Preserve type source info.
  13357. QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
  13358. if (IsTopLevel) {
  13359. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  13360. collectUnexpandedParameterPacks(ET, Unexpanded);
  13361. if (!Unexpanded.empty()) {
  13362. DiagnoseUnexpandedParameterPacks(
  13363. DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
  13364. Unexpanded);
  13365. continue;
  13366. }
  13367. }
  13368. // Check that the type is valid for an exception spec, and
  13369. // drop it if not.
  13370. if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
  13371. Exceptions.push_back(ET);
  13372. }
  13373. ESI.Exceptions = Exceptions;
  13374. return;
  13375. }
  13376. if (isComputedNoexcept(EST)) {
  13377. assert((NoexceptExpr->isTypeDependent() ||
  13378. NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
  13379. Context.BoolTy) &&
  13380. "Parser should have made sure that the expression is boolean");
  13381. if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
  13382. ESI.Type = EST_BasicNoexcept;
  13383. return;
  13384. }
  13385. ESI.NoexceptExpr = NoexceptExpr;
  13386. return;
  13387. }
  13388. }
  13389. void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
  13390. ExceptionSpecificationType EST,
  13391. SourceRange SpecificationRange,
  13392. ArrayRef<ParsedType> DynamicExceptions,
  13393. ArrayRef<SourceRange> DynamicExceptionRanges,
  13394. Expr *NoexceptExpr) {
  13395. if (!MethodD)
  13396. return;
  13397. // Dig out the method we're referring to.
  13398. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
  13399. MethodD = FunTmpl->getTemplatedDecl();
  13400. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
  13401. if (!Method)
  13402. return;
  13403. // Check the exception specification.
  13404. llvm::SmallVector<QualType, 4> Exceptions;
  13405. FunctionProtoType::ExceptionSpecInfo ESI;
  13406. checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
  13407. DynamicExceptionRanges, NoexceptExpr, Exceptions,
  13408. ESI);
  13409. // Update the exception specification on the function type.
  13410. Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
  13411. if (Method->isStatic())
  13412. checkThisInStaticMemberFunctionExceptionSpec(Method);
  13413. if (Method->isVirtual()) {
  13414. // Check overrides, which we previously had to delay.
  13415. for (const CXXMethodDecl *O : Method->overridden_methods())
  13416. CheckOverridingFunctionExceptionSpec(Method, O);
  13417. }
  13418. }
  13419. /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
  13420. ///
  13421. MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
  13422. SourceLocation DeclStart, Declarator &D,
  13423. Expr *BitWidth,
  13424. InClassInitStyle InitStyle,
  13425. AccessSpecifier AS,
  13426. const ParsedAttr &MSPropertyAttr) {
  13427. IdentifierInfo *II = D.getIdentifier();
  13428. if (!II) {
  13429. Diag(DeclStart, diag::err_anonymous_property);
  13430. return nullptr;
  13431. }
  13432. SourceLocation Loc = D.getIdentifierLoc();
  13433. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13434. QualType T = TInfo->getType();
  13435. if (getLangOpts().CPlusPlus) {
  13436. CheckExtraCXXDefaultArguments(D);
  13437. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  13438. UPPC_DataMemberType)) {
  13439. D.setInvalidType();
  13440. T = Context.IntTy;
  13441. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  13442. }
  13443. }
  13444. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  13445. if (D.getDeclSpec().isInlineSpecified())
  13446. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13447. << getLangOpts().CPlusPlus17;
  13448. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13449. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13450. diag::err_invalid_thread)
  13451. << DeclSpec::getSpecifierName(TSCS);
  13452. // Check to see if this name was declared as a member previously
  13453. NamedDecl *PrevDecl = nullptr;
  13454. LookupResult Previous(*this, II, Loc, LookupMemberName,
  13455. ForVisibleRedeclaration);
  13456. LookupName(Previous, S);
  13457. switch (Previous.getResultKind()) {
  13458. case LookupResult::Found:
  13459. case LookupResult::FoundUnresolvedValue:
  13460. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13461. break;
  13462. case LookupResult::FoundOverloaded:
  13463. PrevDecl = Previous.getRepresentativeDecl();
  13464. break;
  13465. case LookupResult::NotFound:
  13466. case LookupResult::NotFoundInCurrentInstantiation:
  13467. case LookupResult::Ambiguous:
  13468. break;
  13469. }
  13470. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13471. // Maybe we will complain about the shadowed template parameter.
  13472. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13473. // Just pretend that we didn't see the previous declaration.
  13474. PrevDecl = nullptr;
  13475. }
  13476. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13477. PrevDecl = nullptr;
  13478. SourceLocation TSSL = D.getBeginLoc();
  13479. MSPropertyDecl *NewPD =
  13480. MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
  13481. MSPropertyAttr.getPropertyDataGetter(),
  13482. MSPropertyAttr.getPropertyDataSetter());
  13483. ProcessDeclAttributes(TUScope, NewPD, D);
  13484. NewPD->setAccess(AS);
  13485. if (NewPD->isInvalidDecl())
  13486. Record->setInvalidDecl();
  13487. if (D.getDeclSpec().isModulePrivateSpecified())
  13488. NewPD->setModulePrivate();
  13489. if (NewPD->isInvalidDecl() && PrevDecl) {
  13490. // Don't introduce NewFD into scope; there's already something
  13491. // with the same name in the same scope.
  13492. } else if (II) {
  13493. PushOnScopeChains(NewPD, S);
  13494. } else
  13495. Record->addDecl(NewPD);
  13496. return NewPD;
  13497. }