SemaDecl.cpp 683 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612
  1. //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for declarations.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TypeLocBuilder.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/CommentDiagnostic.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/EvaluatedExprVisitor.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/NonTrivialTypeVisitor.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/Basic/Builtins.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "clang/Basic/SourceManager.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  31. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  32. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  33. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  34. #include "clang/Sema/CXXFieldCollector.h"
  35. #include "clang/Sema/DeclSpec.h"
  36. #include "clang/Sema/DelayedDiagnostic.h"
  37. #include "clang/Sema/Initialization.h"
  38. #include "clang/Sema/Lookup.h"
  39. #include "clang/Sema/ParsedTemplate.h"
  40. #include "clang/Sema/Scope.h"
  41. #include "clang/Sema/ScopeInfo.h"
  42. #include "clang/Sema/SemaInternal.h"
  43. #include "clang/Sema/Template.h"
  44. #include "llvm/ADT/SmallString.h"
  45. #include "llvm/ADT/Triple.h"
  46. #include <algorithm>
  47. #include <cstring>
  48. #include <functional>
  49. using namespace clang;
  50. using namespace sema;
  51. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  52. if (OwnedType) {
  53. Decl *Group[2] = { OwnedType, Ptr };
  54. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  55. }
  56. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  57. }
  58. namespace {
  59. class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
  60. public:
  61. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
  62. bool AllowTemplates = false,
  63. bool AllowNonTemplates = true)
  64. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  65. AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
  66. WantExpressionKeywords = false;
  67. WantCXXNamedCasts = false;
  68. WantRemainingKeywords = false;
  69. }
  70. bool ValidateCandidate(const TypoCorrection &candidate) override {
  71. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  72. if (!AllowInvalidDecl && ND->isInvalidDecl())
  73. return false;
  74. if (getAsTypeTemplateDecl(ND))
  75. return AllowTemplates;
  76. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  77. if (!IsType)
  78. return false;
  79. if (AllowNonTemplates)
  80. return true;
  81. // An injected-class-name of a class template (specialization) is valid
  82. // as a template or as a non-template.
  83. if (AllowTemplates) {
  84. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  85. if (!RD || !RD->isInjectedClassName())
  86. return false;
  87. RD = cast<CXXRecordDecl>(RD->getDeclContext());
  88. return RD->getDescribedClassTemplate() ||
  89. isa<ClassTemplateSpecializationDecl>(RD);
  90. }
  91. return false;
  92. }
  93. return !WantClassName && candidate.isKeyword();
  94. }
  95. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  96. return std::make_unique<TypeNameValidatorCCC>(*this);
  97. }
  98. private:
  99. bool AllowInvalidDecl;
  100. bool WantClassName;
  101. bool AllowTemplates;
  102. bool AllowNonTemplates;
  103. };
  104. } // end anonymous namespace
  105. /// Determine whether the token kind starts a simple-type-specifier.
  106. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  107. switch (Kind) {
  108. // FIXME: Take into account the current language when deciding whether a
  109. // token kind is a valid type specifier
  110. case tok::kw_short:
  111. case tok::kw_long:
  112. case tok::kw___int64:
  113. case tok::kw___int128:
  114. case tok::kw_signed:
  115. case tok::kw_unsigned:
  116. case tok::kw_void:
  117. case tok::kw_char:
  118. case tok::kw_int:
  119. case tok::kw_half:
  120. case tok::kw_float:
  121. case tok::kw_double:
  122. case tok::kw__Float16:
  123. case tok::kw___float128:
  124. case tok::kw_wchar_t:
  125. case tok::kw_bool:
  126. case tok::kw___underlying_type:
  127. case tok::kw___auto_type:
  128. return true;
  129. case tok::annot_typename:
  130. case tok::kw_char16_t:
  131. case tok::kw_char32_t:
  132. case tok::kw_typeof:
  133. case tok::annot_decltype:
  134. case tok::kw_decltype:
  135. return getLangOpts().CPlusPlus;
  136. case tok::kw_char8_t:
  137. return getLangOpts().Char8;
  138. default:
  139. break;
  140. }
  141. return false;
  142. }
  143. namespace {
  144. enum class UnqualifiedTypeNameLookupResult {
  145. NotFound,
  146. FoundNonType,
  147. FoundType
  148. };
  149. } // end anonymous namespace
  150. /// Tries to perform unqualified lookup of the type decls in bases for
  151. /// dependent class.
  152. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  153. /// type decl, \a FoundType if only type decls are found.
  154. static UnqualifiedTypeNameLookupResult
  155. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  156. SourceLocation NameLoc,
  157. const CXXRecordDecl *RD) {
  158. if (!RD->hasDefinition())
  159. return UnqualifiedTypeNameLookupResult::NotFound;
  160. // Look for type decls in base classes.
  161. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  162. UnqualifiedTypeNameLookupResult::NotFound;
  163. for (const auto &Base : RD->bases()) {
  164. const CXXRecordDecl *BaseRD = nullptr;
  165. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  166. BaseRD = BaseTT->getAsCXXRecordDecl();
  167. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  168. // Look for type decls in dependent base classes that have known primary
  169. // templates.
  170. if (!TST || !TST->isDependentType())
  171. continue;
  172. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  173. if (!TD)
  174. continue;
  175. if (auto *BasePrimaryTemplate =
  176. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
  177. if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
  178. BaseRD = BasePrimaryTemplate;
  179. else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
  180. if (const ClassTemplatePartialSpecializationDecl *PS =
  181. CTD->findPartialSpecialization(Base.getType()))
  182. if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
  183. BaseRD = PS;
  184. }
  185. }
  186. }
  187. if (BaseRD) {
  188. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  189. if (!isa<TypeDecl>(ND))
  190. return UnqualifiedTypeNameLookupResult::FoundNonType;
  191. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  192. }
  193. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  194. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  195. case UnqualifiedTypeNameLookupResult::FoundNonType:
  196. return UnqualifiedTypeNameLookupResult::FoundNonType;
  197. case UnqualifiedTypeNameLookupResult::FoundType:
  198. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  199. break;
  200. case UnqualifiedTypeNameLookupResult::NotFound:
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. return FoundTypeDecl;
  207. }
  208. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  209. const IdentifierInfo &II,
  210. SourceLocation NameLoc) {
  211. // Lookup in the parent class template context, if any.
  212. const CXXRecordDecl *RD = nullptr;
  213. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  214. UnqualifiedTypeNameLookupResult::NotFound;
  215. for (DeclContext *DC = S.CurContext;
  216. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  217. DC = DC->getParent()) {
  218. // Look for type decls in dependent base classes that have known primary
  219. // templates.
  220. RD = dyn_cast<CXXRecordDecl>(DC);
  221. if (RD && RD->getDescribedClassTemplate())
  222. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  223. }
  224. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  225. return nullptr;
  226. // We found some types in dependent base classes. Recover as if the user
  227. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  228. // lookup during template instantiation.
  229. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  230. ASTContext &Context = S.Context;
  231. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  232. cast<Type>(Context.getRecordType(RD)));
  233. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  234. CXXScopeSpec SS;
  235. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  236. TypeLocBuilder Builder;
  237. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  238. DepTL.setNameLoc(NameLoc);
  239. DepTL.setElaboratedKeywordLoc(SourceLocation());
  240. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  241. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  242. }
  243. /// If the identifier refers to a type name within this scope,
  244. /// return the declaration of that type.
  245. ///
  246. /// This routine performs ordinary name lookup of the identifier II
  247. /// within the given scope, with optional C++ scope specifier SS, to
  248. /// determine whether the name refers to a type. If so, returns an
  249. /// opaque pointer (actually a QualType) corresponding to that
  250. /// type. Otherwise, returns NULL.
  251. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  252. Scope *S, CXXScopeSpec *SS,
  253. bool isClassName, bool HasTrailingDot,
  254. ParsedType ObjectTypePtr,
  255. bool IsCtorOrDtorName,
  256. bool WantNontrivialTypeSourceInfo,
  257. bool IsClassTemplateDeductionContext,
  258. IdentifierInfo **CorrectedII) {
  259. // FIXME: Consider allowing this outside C++1z mode as an extension.
  260. bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
  261. getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
  262. !isClassName && !HasTrailingDot;
  263. // Determine where we will perform name lookup.
  264. DeclContext *LookupCtx = nullptr;
  265. if (ObjectTypePtr) {
  266. QualType ObjectType = ObjectTypePtr.get();
  267. if (ObjectType->isRecordType())
  268. LookupCtx = computeDeclContext(ObjectType);
  269. } else if (SS && SS->isNotEmpty()) {
  270. LookupCtx = computeDeclContext(*SS, false);
  271. if (!LookupCtx) {
  272. if (isDependentScopeSpecifier(*SS)) {
  273. // C++ [temp.res]p3:
  274. // A qualified-id that refers to a type and in which the
  275. // nested-name-specifier depends on a template-parameter (14.6.2)
  276. // shall be prefixed by the keyword typename to indicate that the
  277. // qualified-id denotes a type, forming an
  278. // elaborated-type-specifier (7.1.5.3).
  279. //
  280. // We therefore do not perform any name lookup if the result would
  281. // refer to a member of an unknown specialization.
  282. if (!isClassName && !IsCtorOrDtorName)
  283. return nullptr;
  284. // We know from the grammar that this name refers to a type,
  285. // so build a dependent node to describe the type.
  286. if (WantNontrivialTypeSourceInfo)
  287. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  288. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  289. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  290. II, NameLoc);
  291. return ParsedType::make(T);
  292. }
  293. return nullptr;
  294. }
  295. if (!LookupCtx->isDependentContext() &&
  296. RequireCompleteDeclContext(*SS, LookupCtx))
  297. return nullptr;
  298. }
  299. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  300. // lookup for class-names.
  301. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  302. LookupOrdinaryName;
  303. LookupResult Result(*this, &II, NameLoc, Kind);
  304. if (LookupCtx) {
  305. // Perform "qualified" name lookup into the declaration context we
  306. // computed, which is either the type of the base of a member access
  307. // expression or the declaration context associated with a prior
  308. // nested-name-specifier.
  309. LookupQualifiedName(Result, LookupCtx);
  310. if (ObjectTypePtr && Result.empty()) {
  311. // C++ [basic.lookup.classref]p3:
  312. // If the unqualified-id is ~type-name, the type-name is looked up
  313. // in the context of the entire postfix-expression. If the type T of
  314. // the object expression is of a class type C, the type-name is also
  315. // looked up in the scope of class C. At least one of the lookups shall
  316. // find a name that refers to (possibly cv-qualified) T.
  317. LookupName(Result, S);
  318. }
  319. } else {
  320. // Perform unqualified name lookup.
  321. LookupName(Result, S);
  322. // For unqualified lookup in a class template in MSVC mode, look into
  323. // dependent base classes where the primary class template is known.
  324. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  325. if (ParsedType TypeInBase =
  326. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  327. return TypeInBase;
  328. }
  329. }
  330. NamedDecl *IIDecl = nullptr;
  331. switch (Result.getResultKind()) {
  332. case LookupResult::NotFound:
  333. case LookupResult::NotFoundInCurrentInstantiation:
  334. if (CorrectedII) {
  335. TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
  336. AllowDeducedTemplate);
  337. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
  338. S, SS, CCC, CTK_ErrorRecovery);
  339. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  340. TemplateTy Template;
  341. bool MemberOfUnknownSpecialization;
  342. UnqualifiedId TemplateName;
  343. TemplateName.setIdentifier(NewII, NameLoc);
  344. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  345. CXXScopeSpec NewSS, *NewSSPtr = SS;
  346. if (SS && NNS) {
  347. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  348. NewSSPtr = &NewSS;
  349. }
  350. if (Correction && (NNS || NewII != &II) &&
  351. // Ignore a correction to a template type as the to-be-corrected
  352. // identifier is not a template (typo correction for template names
  353. // is handled elsewhere).
  354. !(getLangOpts().CPlusPlus && NewSSPtr &&
  355. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  356. Template, MemberOfUnknownSpecialization))) {
  357. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  358. isClassName, HasTrailingDot, ObjectTypePtr,
  359. IsCtorOrDtorName,
  360. WantNontrivialTypeSourceInfo,
  361. IsClassTemplateDeductionContext);
  362. if (Ty) {
  363. diagnoseTypo(Correction,
  364. PDiag(diag::err_unknown_type_or_class_name_suggest)
  365. << Result.getLookupName() << isClassName);
  366. if (SS && NNS)
  367. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  368. *CorrectedII = NewII;
  369. return Ty;
  370. }
  371. }
  372. }
  373. // If typo correction failed or was not performed, fall through
  374. LLVM_FALLTHROUGH;
  375. case LookupResult::FoundOverloaded:
  376. case LookupResult::FoundUnresolvedValue:
  377. Result.suppressDiagnostics();
  378. return nullptr;
  379. case LookupResult::Ambiguous:
  380. // Recover from type-hiding ambiguities by hiding the type. We'll
  381. // do the lookup again when looking for an object, and we can
  382. // diagnose the error then. If we don't do this, then the error
  383. // about hiding the type will be immediately followed by an error
  384. // that only makes sense if the identifier was treated like a type.
  385. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  386. Result.suppressDiagnostics();
  387. return nullptr;
  388. }
  389. // Look to see if we have a type anywhere in the list of results.
  390. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  391. Res != ResEnd; ++Res) {
  392. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
  393. (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
  394. if (!IIDecl ||
  395. (*Res)->getLocation().getRawEncoding() <
  396. IIDecl->getLocation().getRawEncoding())
  397. IIDecl = *Res;
  398. }
  399. }
  400. if (!IIDecl) {
  401. // None of the entities we found is a type, so there is no way
  402. // to even assume that the result is a type. In this case, don't
  403. // complain about the ambiguity. The parser will either try to
  404. // perform this lookup again (e.g., as an object name), which
  405. // will produce the ambiguity, or will complain that it expected
  406. // a type name.
  407. Result.suppressDiagnostics();
  408. return nullptr;
  409. }
  410. // We found a type within the ambiguous lookup; diagnose the
  411. // ambiguity and then return that type. This might be the right
  412. // answer, or it might not be, but it suppresses any attempt to
  413. // perform the name lookup again.
  414. break;
  415. case LookupResult::Found:
  416. IIDecl = Result.getFoundDecl();
  417. break;
  418. }
  419. assert(IIDecl && "Didn't find decl");
  420. QualType T;
  421. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  422. // C++ [class.qual]p2: A lookup that would find the injected-class-name
  423. // instead names the constructors of the class, except when naming a class.
  424. // This is ill-formed when we're not actually forming a ctor or dtor name.
  425. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  426. auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
  427. if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
  428. FoundRD->isInjectedClassName() &&
  429. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  430. Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
  431. << &II << /*Type*/1;
  432. DiagnoseUseOfDecl(IIDecl, NameLoc);
  433. T = Context.getTypeDeclType(TD);
  434. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  435. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  436. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  437. if (!HasTrailingDot)
  438. T = Context.getObjCInterfaceType(IDecl);
  439. } else if (AllowDeducedTemplate) {
  440. if (auto *TD = getAsTypeTemplateDecl(IIDecl))
  441. T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  442. QualType(), false);
  443. }
  444. if (T.isNull()) {
  445. // If it's not plausibly a type, suppress diagnostics.
  446. Result.suppressDiagnostics();
  447. return nullptr;
  448. }
  449. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  450. // constructor or destructor name (in such a case, the scope specifier
  451. // will be attached to the enclosing Expr or Decl node).
  452. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
  453. !isa<ObjCInterfaceDecl>(IIDecl)) {
  454. if (WantNontrivialTypeSourceInfo) {
  455. // Construct a type with type-source information.
  456. TypeLocBuilder Builder;
  457. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  458. T = getElaboratedType(ETK_None, *SS, T);
  459. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  460. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  461. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  462. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  463. } else {
  464. T = getElaboratedType(ETK_None, *SS, T);
  465. }
  466. }
  467. return ParsedType::make(T);
  468. }
  469. // Builds a fake NNS for the given decl context.
  470. static NestedNameSpecifier *
  471. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  472. for (;; DC = DC->getLookupParent()) {
  473. DC = DC->getPrimaryContext();
  474. auto *ND = dyn_cast<NamespaceDecl>(DC);
  475. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  476. return NestedNameSpecifier::Create(Context, nullptr, ND);
  477. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  478. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  479. RD->getTypeForDecl());
  480. else if (isa<TranslationUnitDecl>(DC))
  481. return NestedNameSpecifier::GlobalSpecifier(Context);
  482. }
  483. llvm_unreachable("something isn't in TU scope?");
  484. }
  485. /// Find the parent class with dependent bases of the innermost enclosing method
  486. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  487. /// up allowing unqualified dependent type names at class-level, which MSVC
  488. /// correctly rejects.
  489. static const CXXRecordDecl *
  490. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  491. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  492. DC = DC->getPrimaryContext();
  493. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  494. if (MD->getParent()->hasAnyDependentBases())
  495. return MD->getParent();
  496. }
  497. return nullptr;
  498. }
  499. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  500. SourceLocation NameLoc,
  501. bool IsTemplateTypeArg) {
  502. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  503. NestedNameSpecifier *NNS = nullptr;
  504. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  505. // If we weren't able to parse a default template argument, delay lookup
  506. // until instantiation time by making a non-dependent DependentTypeName. We
  507. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  508. // lookup is retried.
  509. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  510. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  511. // name specifiers.
  512. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  513. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  514. } else if (const CXXRecordDecl *RD =
  515. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  516. // Build a DependentNameType that will perform lookup into RD at
  517. // instantiation time.
  518. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  519. RD->getTypeForDecl());
  520. // Diagnose that this identifier was undeclared, and retry the lookup during
  521. // template instantiation.
  522. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  523. << RD;
  524. } else {
  525. // This is not a situation that we should recover from.
  526. return ParsedType();
  527. }
  528. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  529. // Build type location information. We synthesized the qualifier, so we have
  530. // to build a fake NestedNameSpecifierLoc.
  531. NestedNameSpecifierLocBuilder NNSLocBuilder;
  532. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  533. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  534. TypeLocBuilder Builder;
  535. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  536. DepTL.setNameLoc(NameLoc);
  537. DepTL.setElaboratedKeywordLoc(SourceLocation());
  538. DepTL.setQualifierLoc(QualifierLoc);
  539. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  540. }
  541. /// isTagName() - This method is called *for error recovery purposes only*
  542. /// to determine if the specified name is a valid tag name ("struct foo"). If
  543. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  544. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  545. /// cases in C where the user forgot to specify the tag.
  546. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  547. // Do a tag name lookup in this scope.
  548. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  549. LookupName(R, S, false);
  550. R.suppressDiagnostics();
  551. if (R.getResultKind() == LookupResult::Found)
  552. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  553. switch (TD->getTagKind()) {
  554. case TTK_Struct: return DeclSpec::TST_struct;
  555. case TTK_Interface: return DeclSpec::TST_interface;
  556. case TTK_Union: return DeclSpec::TST_union;
  557. case TTK_Class: return DeclSpec::TST_class;
  558. case TTK_Enum: return DeclSpec::TST_enum;
  559. }
  560. }
  561. return DeclSpec::TST_unspecified;
  562. }
  563. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  564. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  565. /// then downgrade the missing typename error to a warning.
  566. /// This is needed for MSVC compatibility; Example:
  567. /// @code
  568. /// template<class T> class A {
  569. /// public:
  570. /// typedef int TYPE;
  571. /// };
  572. /// template<class T> class B : public A<T> {
  573. /// public:
  574. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  575. /// };
  576. /// @endcode
  577. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  578. if (CurContext->isRecord()) {
  579. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  580. return true;
  581. const Type *Ty = SS->getScopeRep()->getAsType();
  582. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  583. for (const auto &Base : RD->bases())
  584. if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  585. return true;
  586. return S->isFunctionPrototypeScope();
  587. }
  588. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  589. }
  590. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  591. SourceLocation IILoc,
  592. Scope *S,
  593. CXXScopeSpec *SS,
  594. ParsedType &SuggestedType,
  595. bool IsTemplateName) {
  596. // Don't report typename errors for editor placeholders.
  597. if (II->isEditorPlaceholder())
  598. return;
  599. // We don't have anything to suggest (yet).
  600. SuggestedType = nullptr;
  601. // There may have been a typo in the name of the type. Look up typo
  602. // results, in case we have something that we can suggest.
  603. TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
  604. /*AllowTemplates=*/IsTemplateName,
  605. /*AllowNonTemplates=*/!IsTemplateName);
  606. if (TypoCorrection Corrected =
  607. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  608. CCC, CTK_ErrorRecovery)) {
  609. // FIXME: Support error recovery for the template-name case.
  610. bool CanRecover = !IsTemplateName;
  611. if (Corrected.isKeyword()) {
  612. // We corrected to a keyword.
  613. diagnoseTypo(Corrected,
  614. PDiag(IsTemplateName ? diag::err_no_template_suggest
  615. : diag::err_unknown_typename_suggest)
  616. << II);
  617. II = Corrected.getCorrectionAsIdentifierInfo();
  618. } else {
  619. // We found a similarly-named type or interface; suggest that.
  620. if (!SS || !SS->isSet()) {
  621. diagnoseTypo(Corrected,
  622. PDiag(IsTemplateName ? diag::err_no_template_suggest
  623. : diag::err_unknown_typename_suggest)
  624. << II, CanRecover);
  625. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  626. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  627. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  628. II->getName().equals(CorrectedStr);
  629. diagnoseTypo(Corrected,
  630. PDiag(IsTemplateName
  631. ? diag::err_no_member_template_suggest
  632. : diag::err_unknown_nested_typename_suggest)
  633. << II << DC << DroppedSpecifier << SS->getRange(),
  634. CanRecover);
  635. } else {
  636. llvm_unreachable("could not have corrected a typo here");
  637. }
  638. if (!CanRecover)
  639. return;
  640. CXXScopeSpec tmpSS;
  641. if (Corrected.getCorrectionSpecifier())
  642. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  643. SourceRange(IILoc));
  644. // FIXME: Support class template argument deduction here.
  645. SuggestedType =
  646. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  647. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  648. /*IsCtorOrDtorName=*/false,
  649. /*WantNontrivialTypeSourceInfo=*/true);
  650. }
  651. return;
  652. }
  653. if (getLangOpts().CPlusPlus && !IsTemplateName) {
  654. // See if II is a class template that the user forgot to pass arguments to.
  655. UnqualifiedId Name;
  656. Name.setIdentifier(II, IILoc);
  657. CXXScopeSpec EmptySS;
  658. TemplateTy TemplateResult;
  659. bool MemberOfUnknownSpecialization;
  660. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  661. Name, nullptr, true, TemplateResult,
  662. MemberOfUnknownSpecialization) == TNK_Type_template) {
  663. diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
  664. return;
  665. }
  666. }
  667. // FIXME: Should we move the logic that tries to recover from a missing tag
  668. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  669. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  670. Diag(IILoc, IsTemplateName ? diag::err_no_template
  671. : diag::err_unknown_typename)
  672. << II;
  673. else if (DeclContext *DC = computeDeclContext(*SS, false))
  674. Diag(IILoc, IsTemplateName ? diag::err_no_member_template
  675. : diag::err_typename_nested_not_found)
  676. << II << DC << SS->getRange();
  677. else if (isDependentScopeSpecifier(*SS)) {
  678. unsigned DiagID = diag::err_typename_missing;
  679. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  680. DiagID = diag::ext_typename_missing;
  681. Diag(SS->getRange().getBegin(), DiagID)
  682. << SS->getScopeRep() << II->getName()
  683. << SourceRange(SS->getRange().getBegin(), IILoc)
  684. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  685. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  686. *SS, *II, IILoc).get();
  687. } else {
  688. assert(SS && SS->isInvalid() &&
  689. "Invalid scope specifier has already been diagnosed");
  690. }
  691. }
  692. /// Determine whether the given result set contains either a type name
  693. /// or
  694. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  695. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  696. NextToken.is(tok::less);
  697. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  698. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  699. return true;
  700. if (CheckTemplate && isa<TemplateDecl>(*I))
  701. return true;
  702. }
  703. return false;
  704. }
  705. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  706. Scope *S, CXXScopeSpec &SS,
  707. IdentifierInfo *&Name,
  708. SourceLocation NameLoc) {
  709. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  710. SemaRef.LookupParsedName(R, S, &SS);
  711. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  712. StringRef FixItTagName;
  713. switch (Tag->getTagKind()) {
  714. case TTK_Class:
  715. FixItTagName = "class ";
  716. break;
  717. case TTK_Enum:
  718. FixItTagName = "enum ";
  719. break;
  720. case TTK_Struct:
  721. FixItTagName = "struct ";
  722. break;
  723. case TTK_Interface:
  724. FixItTagName = "__interface ";
  725. break;
  726. case TTK_Union:
  727. FixItTagName = "union ";
  728. break;
  729. }
  730. StringRef TagName = FixItTagName.drop_back();
  731. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  732. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  733. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  734. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  735. I != IEnd; ++I)
  736. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  737. << Name << TagName;
  738. // Replace lookup results with just the tag decl.
  739. Result.clear(Sema::LookupTagName);
  740. SemaRef.LookupParsedName(Result, S, &SS);
  741. return true;
  742. }
  743. return false;
  744. }
  745. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  746. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  747. QualType T, SourceLocation NameLoc) {
  748. ASTContext &Context = S.Context;
  749. TypeLocBuilder Builder;
  750. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  751. T = S.getElaboratedType(ETK_None, SS, T);
  752. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  753. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  754. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  755. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  756. }
  757. Sema::NameClassification
  758. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  759. SourceLocation NameLoc, const Token &NextToken,
  760. bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) {
  761. DeclarationNameInfo NameInfo(Name, NameLoc);
  762. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  763. if (NextToken.is(tok::coloncolon)) {
  764. NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
  765. BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
  766. } else if (getLangOpts().CPlusPlus && SS.isSet() &&
  767. isCurrentClassName(*Name, S, &SS)) {
  768. // Per [class.qual]p2, this names the constructors of SS, not the
  769. // injected-class-name. We don't have a classification for that.
  770. // There's not much point caching this result, since the parser
  771. // will reject it later.
  772. return NameClassification::Unknown();
  773. }
  774. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  775. LookupParsedName(Result, S, &SS, !CurMethod);
  776. // For unqualified lookup in a class template in MSVC mode, look into
  777. // dependent base classes where the primary class template is known.
  778. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  779. if (ParsedType TypeInBase =
  780. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  781. return TypeInBase;
  782. }
  783. // Perform lookup for Objective-C instance variables (including automatically
  784. // synthesized instance variables), if we're in an Objective-C method.
  785. // FIXME: This lookup really, really needs to be folded in to the normal
  786. // unqualified lookup mechanism.
  787. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  788. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  789. if (E.get() || E.isInvalid())
  790. return E;
  791. }
  792. bool SecondTry = false;
  793. bool IsFilteredTemplateName = false;
  794. Corrected:
  795. switch (Result.getResultKind()) {
  796. case LookupResult::NotFound:
  797. // If an unqualified-id is followed by a '(', then we have a function
  798. // call.
  799. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  800. // In C++, this is an ADL-only call.
  801. // FIXME: Reference?
  802. if (getLangOpts().CPlusPlus)
  803. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  804. // C90 6.3.2.2:
  805. // If the expression that precedes the parenthesized argument list in a
  806. // function call consists solely of an identifier, and if no
  807. // declaration is visible for this identifier, the identifier is
  808. // implicitly declared exactly as if, in the innermost block containing
  809. // the function call, the declaration
  810. //
  811. // extern int identifier ();
  812. //
  813. // appeared.
  814. //
  815. // We also allow this in C99 as an extension.
  816. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  817. Result.addDecl(D);
  818. Result.resolveKind();
  819. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  820. }
  821. }
  822. if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
  823. // In C++20 onwards, this could be an ADL-only call to a function
  824. // template, and we're required to assume that this is a template name.
  825. //
  826. // FIXME: Find a way to still do typo correction in this case.
  827. TemplateName Template =
  828. Context.getAssumedTemplateName(NameInfo.getName());
  829. return NameClassification::UndeclaredTemplate(Template);
  830. }
  831. // In C, we first see whether there is a tag type by the same name, in
  832. // which case it's likely that the user just forgot to write "enum",
  833. // "struct", or "union".
  834. if (!getLangOpts().CPlusPlus && !SecondTry &&
  835. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  836. break;
  837. }
  838. // Perform typo correction to determine if there is another name that is
  839. // close to this name.
  840. if (!SecondTry && CCC) {
  841. SecondTry = true;
  842. if (TypoCorrection Corrected =
  843. CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
  844. &SS, *CCC, CTK_ErrorRecovery)) {
  845. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  846. unsigned QualifiedDiag = diag::err_no_member_suggest;
  847. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  848. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  849. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  850. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  851. UnqualifiedDiag = diag::err_no_template_suggest;
  852. QualifiedDiag = diag::err_no_member_template_suggest;
  853. } else if (UnderlyingFirstDecl &&
  854. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  855. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  856. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  857. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  858. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  859. }
  860. if (SS.isEmpty()) {
  861. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  862. } else {// FIXME: is this even reachable? Test it.
  863. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  864. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  865. Name->getName().equals(CorrectedStr);
  866. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  867. << Name << computeDeclContext(SS, false)
  868. << DroppedSpecifier << SS.getRange());
  869. }
  870. // Update the name, so that the caller has the new name.
  871. Name = Corrected.getCorrectionAsIdentifierInfo();
  872. // Typo correction corrected to a keyword.
  873. if (Corrected.isKeyword())
  874. return Name;
  875. // Also update the LookupResult...
  876. // FIXME: This should probably go away at some point
  877. Result.clear();
  878. Result.setLookupName(Corrected.getCorrection());
  879. if (FirstDecl)
  880. Result.addDecl(FirstDecl);
  881. // If we found an Objective-C instance variable, let
  882. // LookupInObjCMethod build the appropriate expression to
  883. // reference the ivar.
  884. // FIXME: This is a gross hack.
  885. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  886. Result.clear();
  887. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  888. return E;
  889. }
  890. goto Corrected;
  891. }
  892. }
  893. // We failed to correct; just fall through and let the parser deal with it.
  894. Result.suppressDiagnostics();
  895. return NameClassification::Unknown();
  896. case LookupResult::NotFoundInCurrentInstantiation: {
  897. // We performed name lookup into the current instantiation, and there were
  898. // dependent bases, so we treat this result the same way as any other
  899. // dependent nested-name-specifier.
  900. // C++ [temp.res]p2:
  901. // A name used in a template declaration or definition and that is
  902. // dependent on a template-parameter is assumed not to name a type
  903. // unless the applicable name lookup finds a type name or the name is
  904. // qualified by the keyword typename.
  905. //
  906. // FIXME: If the next token is '<', we might want to ask the parser to
  907. // perform some heroics to see if we actually have a
  908. // template-argument-list, which would indicate a missing 'template'
  909. // keyword here.
  910. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  911. NameInfo, IsAddressOfOperand,
  912. /*TemplateArgs=*/nullptr);
  913. }
  914. case LookupResult::Found:
  915. case LookupResult::FoundOverloaded:
  916. case LookupResult::FoundUnresolvedValue:
  917. break;
  918. case LookupResult::Ambiguous:
  919. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  920. hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
  921. /*AllowDependent=*/false)) {
  922. // C++ [temp.local]p3:
  923. // A lookup that finds an injected-class-name (10.2) can result in an
  924. // ambiguity in certain cases (for example, if it is found in more than
  925. // one base class). If all of the injected-class-names that are found
  926. // refer to specializations of the same class template, and if the name
  927. // is followed by a template-argument-list, the reference refers to the
  928. // class template itself and not a specialization thereof, and is not
  929. // ambiguous.
  930. //
  931. // This filtering can make an ambiguous result into an unambiguous one,
  932. // so try again after filtering out template names.
  933. FilterAcceptableTemplateNames(Result);
  934. if (!Result.isAmbiguous()) {
  935. IsFilteredTemplateName = true;
  936. break;
  937. }
  938. }
  939. // Diagnose the ambiguity and return an error.
  940. return NameClassification::Error();
  941. }
  942. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  943. (IsFilteredTemplateName ||
  944. hasAnyAcceptableTemplateNames(
  945. Result, /*AllowFunctionTemplates=*/true,
  946. /*AllowDependent=*/false,
  947. /*AllowNonTemplateFunctions*/ !SS.isSet() &&
  948. getLangOpts().CPlusPlus2a))) {
  949. // C++ [temp.names]p3:
  950. // After name lookup (3.4) finds that a name is a template-name or that
  951. // an operator-function-id or a literal- operator-id refers to a set of
  952. // overloaded functions any member of which is a function template if
  953. // this is followed by a <, the < is always taken as the delimiter of a
  954. // template-argument-list and never as the less-than operator.
  955. // C++2a [temp.names]p2:
  956. // A name is also considered to refer to a template if it is an
  957. // unqualified-id followed by a < and name lookup finds either one
  958. // or more functions or finds nothing.
  959. if (!IsFilteredTemplateName)
  960. FilterAcceptableTemplateNames(Result);
  961. bool IsFunctionTemplate;
  962. bool IsVarTemplate;
  963. TemplateName Template;
  964. if (Result.end() - Result.begin() > 1) {
  965. IsFunctionTemplate = true;
  966. Template = Context.getOverloadedTemplateName(Result.begin(),
  967. Result.end());
  968. } else if (!Result.empty()) {
  969. auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
  970. *Result.begin(), /*AllowFunctionTemplates=*/true,
  971. /*AllowDependent=*/false));
  972. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  973. IsVarTemplate = isa<VarTemplateDecl>(TD);
  974. if (SS.isSet() && !SS.isInvalid())
  975. Template =
  976. Context.getQualifiedTemplateName(SS.getScopeRep(),
  977. /*TemplateKeyword=*/false, TD);
  978. else
  979. Template = TemplateName(TD);
  980. } else {
  981. // All results were non-template functions. This is a function template
  982. // name.
  983. IsFunctionTemplate = true;
  984. Template = Context.getAssumedTemplateName(NameInfo.getName());
  985. }
  986. if (IsFunctionTemplate) {
  987. // Function templates always go through overload resolution, at which
  988. // point we'll perform the various checks (e.g., accessibility) we need
  989. // to based on which function we selected.
  990. Result.suppressDiagnostics();
  991. return NameClassification::FunctionTemplate(Template);
  992. }
  993. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  994. : NameClassification::TypeTemplate(Template);
  995. }
  996. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  997. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  998. DiagnoseUseOfDecl(Type, NameLoc);
  999. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  1000. QualType T = Context.getTypeDeclType(Type);
  1001. if (SS.isNotEmpty())
  1002. return buildNestedType(*this, SS, T, NameLoc);
  1003. return ParsedType::make(T);
  1004. }
  1005. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  1006. if (!Class) {
  1007. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  1008. if (ObjCCompatibleAliasDecl *Alias =
  1009. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  1010. Class = Alias->getClassInterface();
  1011. }
  1012. if (Class) {
  1013. DiagnoseUseOfDecl(Class, NameLoc);
  1014. if (NextToken.is(tok::period)) {
  1015. // Interface. <something> is parsed as a property reference expression.
  1016. // Just return "unknown" as a fall-through for now.
  1017. Result.suppressDiagnostics();
  1018. return NameClassification::Unknown();
  1019. }
  1020. QualType T = Context.getObjCInterfaceType(Class);
  1021. return ParsedType::make(T);
  1022. }
  1023. // We can have a type template here if we're classifying a template argument.
  1024. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
  1025. !isa<VarTemplateDecl>(FirstDecl))
  1026. return NameClassification::TypeTemplate(
  1027. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1028. // Check for a tag type hidden by a non-type decl in a few cases where it
  1029. // seems likely a type is wanted instead of the non-type that was found.
  1030. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  1031. if ((NextToken.is(tok::identifier) ||
  1032. (NextIsOp &&
  1033. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  1034. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  1035. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  1036. DiagnoseUseOfDecl(Type, NameLoc);
  1037. QualType T = Context.getTypeDeclType(Type);
  1038. if (SS.isNotEmpty())
  1039. return buildNestedType(*this, SS, T, NameLoc);
  1040. return ParsedType::make(T);
  1041. }
  1042. if (FirstDecl->isCXXClassMember())
  1043. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  1044. nullptr, S);
  1045. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1046. return BuildDeclarationNameExpr(SS, Result, ADL);
  1047. }
  1048. Sema::TemplateNameKindForDiagnostics
  1049. Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
  1050. auto *TD = Name.getAsTemplateDecl();
  1051. if (!TD)
  1052. return TemplateNameKindForDiagnostics::DependentTemplate;
  1053. if (isa<ClassTemplateDecl>(TD))
  1054. return TemplateNameKindForDiagnostics::ClassTemplate;
  1055. if (isa<FunctionTemplateDecl>(TD))
  1056. return TemplateNameKindForDiagnostics::FunctionTemplate;
  1057. if (isa<VarTemplateDecl>(TD))
  1058. return TemplateNameKindForDiagnostics::VarTemplate;
  1059. if (isa<TypeAliasTemplateDecl>(TD))
  1060. return TemplateNameKindForDiagnostics::AliasTemplate;
  1061. if (isa<TemplateTemplateParmDecl>(TD))
  1062. return TemplateNameKindForDiagnostics::TemplateTemplateParam;
  1063. if (isa<ConceptDecl>(TD))
  1064. return TemplateNameKindForDiagnostics::Concept;
  1065. return TemplateNameKindForDiagnostics::DependentTemplate;
  1066. }
  1067. // Determines the context to return to after temporarily entering a
  1068. // context. This depends in an unnecessarily complicated way on the
  1069. // exact ordering of callbacks from the parser.
  1070. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  1071. // Functions defined inline within classes aren't parsed until we've
  1072. // finished parsing the top-level class, so the top-level class is
  1073. // the context we'll need to return to.
  1074. // A Lambda call operator whose parent is a class must not be treated
  1075. // as an inline member function. A Lambda can be used legally
  1076. // either as an in-class member initializer or a default argument. These
  1077. // are parsed once the class has been marked complete and so the containing
  1078. // context would be the nested class (when the lambda is defined in one);
  1079. // If the class is not complete, then the lambda is being used in an
  1080. // ill-formed fashion (such as to specify the width of a bit-field, or
  1081. // in an array-bound) - in which case we still want to return the
  1082. // lexically containing DC (which could be a nested class).
  1083. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  1084. DC = DC->getLexicalParent();
  1085. // A function not defined within a class will always return to its
  1086. // lexical context.
  1087. if (!isa<CXXRecordDecl>(DC))
  1088. return DC;
  1089. // A C++ inline method/friend is parsed *after* the topmost class
  1090. // it was declared in is fully parsed ("complete"); the topmost
  1091. // class is the context we need to return to.
  1092. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  1093. DC = RD;
  1094. // Return the declaration context of the topmost class the inline method is
  1095. // declared in.
  1096. return DC;
  1097. }
  1098. return DC->getLexicalParent();
  1099. }
  1100. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  1101. assert(getContainingDC(DC) == CurContext &&
  1102. "The next DeclContext should be lexically contained in the current one.");
  1103. CurContext = DC;
  1104. S->setEntity(DC);
  1105. }
  1106. void Sema::PopDeclContext() {
  1107. assert(CurContext && "DeclContext imbalance!");
  1108. CurContext = getContainingDC(CurContext);
  1109. assert(CurContext && "Popped translation unit!");
  1110. }
  1111. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1112. Decl *D) {
  1113. // Unlike PushDeclContext, the context to which we return is not necessarily
  1114. // the containing DC of TD, because the new context will be some pre-existing
  1115. // TagDecl definition instead of a fresh one.
  1116. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1117. CurContext = cast<TagDecl>(D)->getDefinition();
  1118. assert(CurContext && "skipping definition of undefined tag");
  1119. // Start lookups from the parent of the current context; we don't want to look
  1120. // into the pre-existing complete definition.
  1121. S->setEntity(CurContext->getLookupParent());
  1122. return Result;
  1123. }
  1124. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1125. CurContext = static_cast<decltype(CurContext)>(Context);
  1126. }
  1127. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1128. /// of a declarator's nested name specifier.
  1129. ///
  1130. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1131. // C++0x [basic.lookup.unqual]p13:
  1132. // A name used in the definition of a static data member of class
  1133. // X (after the qualified-id of the static member) is looked up as
  1134. // if the name was used in a member function of X.
  1135. // C++0x [basic.lookup.unqual]p14:
  1136. // If a variable member of a namespace is defined outside of the
  1137. // scope of its namespace then any name used in the definition of
  1138. // the variable member (after the declarator-id) is looked up as
  1139. // if the definition of the variable member occurred in its
  1140. // namespace.
  1141. // Both of these imply that we should push a scope whose context
  1142. // is the semantic context of the declaration. We can't use
  1143. // PushDeclContext here because that context is not necessarily
  1144. // lexically contained in the current context. Fortunately,
  1145. // the containing scope should have the appropriate information.
  1146. assert(!S->getEntity() && "scope already has entity");
  1147. #ifndef NDEBUG
  1148. Scope *Ancestor = S->getParent();
  1149. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1150. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1151. #endif
  1152. CurContext = DC;
  1153. S->setEntity(DC);
  1154. }
  1155. void Sema::ExitDeclaratorContext(Scope *S) {
  1156. assert(S->getEntity() == CurContext && "Context imbalance!");
  1157. // Switch back to the lexical context. The safety of this is
  1158. // enforced by an assert in EnterDeclaratorContext.
  1159. Scope *Ancestor = S->getParent();
  1160. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1161. CurContext = Ancestor->getEntity();
  1162. // We don't need to do anything with the scope, which is going to
  1163. // disappear.
  1164. }
  1165. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1166. // We assume that the caller has already called
  1167. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1168. FunctionDecl *FD = D->getAsFunction();
  1169. if (!FD)
  1170. return;
  1171. // Same implementation as PushDeclContext, but enters the context
  1172. // from the lexical parent, rather than the top-level class.
  1173. assert(CurContext == FD->getLexicalParent() &&
  1174. "The next DeclContext should be lexically contained in the current one.");
  1175. CurContext = FD;
  1176. S->setEntity(CurContext);
  1177. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1178. ParmVarDecl *Param = FD->getParamDecl(P);
  1179. // If the parameter has an identifier, then add it to the scope
  1180. if (Param->getIdentifier()) {
  1181. S->AddDecl(Param);
  1182. IdResolver.AddDecl(Param);
  1183. }
  1184. }
  1185. }
  1186. void Sema::ActOnExitFunctionContext() {
  1187. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1188. // rather than the top-level class.
  1189. assert(CurContext && "DeclContext imbalance!");
  1190. CurContext = CurContext->getLexicalParent();
  1191. assert(CurContext && "Popped translation unit!");
  1192. }
  1193. /// Determine whether we allow overloading of the function
  1194. /// PrevDecl with another declaration.
  1195. ///
  1196. /// This routine determines whether overloading is possible, not
  1197. /// whether some new function is actually an overload. It will return
  1198. /// true in C++ (where we can always provide overloads) or, as an
  1199. /// extension, in C when the previous function is already an
  1200. /// overloaded function declaration or has the "overloadable"
  1201. /// attribute.
  1202. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1203. ASTContext &Context,
  1204. const FunctionDecl *New) {
  1205. if (Context.getLangOpts().CPlusPlus)
  1206. return true;
  1207. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1208. return true;
  1209. return Previous.getResultKind() == LookupResult::Found &&
  1210. (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
  1211. New->hasAttr<OverloadableAttr>());
  1212. }
  1213. /// Add this decl to the scope shadowed decl chains.
  1214. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1215. // Move up the scope chain until we find the nearest enclosing
  1216. // non-transparent context. The declaration will be introduced into this
  1217. // scope.
  1218. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1219. S = S->getParent();
  1220. // Add scoped declarations into their context, so that they can be
  1221. // found later. Declarations without a context won't be inserted
  1222. // into any context.
  1223. if (AddToContext)
  1224. CurContext->addDecl(D);
  1225. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1226. // are function-local declarations.
  1227. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1228. !D->getDeclContext()->getRedeclContext()->Equals(
  1229. D->getLexicalDeclContext()->getRedeclContext()) &&
  1230. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1231. return;
  1232. // Template instantiations should also not be pushed into scope.
  1233. if (isa<FunctionDecl>(D) &&
  1234. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1235. return;
  1236. // If this replaces anything in the current scope,
  1237. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1238. IEnd = IdResolver.end();
  1239. for (; I != IEnd; ++I) {
  1240. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1241. S->RemoveDecl(*I);
  1242. IdResolver.RemoveDecl(*I);
  1243. // Should only need to replace one decl.
  1244. break;
  1245. }
  1246. }
  1247. S->AddDecl(D);
  1248. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1249. // Implicitly-generated labels may end up getting generated in an order that
  1250. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1251. // the label at the appropriate place in the identifier chain.
  1252. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1253. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1254. if (IDC == CurContext) {
  1255. if (!S->isDeclScope(*I))
  1256. continue;
  1257. } else if (IDC->Encloses(CurContext))
  1258. break;
  1259. }
  1260. IdResolver.InsertDeclAfter(I, D);
  1261. } else {
  1262. IdResolver.AddDecl(D);
  1263. }
  1264. }
  1265. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1266. bool AllowInlineNamespace) {
  1267. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1268. }
  1269. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1270. DeclContext *TargetDC = DC->getPrimaryContext();
  1271. do {
  1272. if (DeclContext *ScopeDC = S->getEntity())
  1273. if (ScopeDC->getPrimaryContext() == TargetDC)
  1274. return S;
  1275. } while ((S = S->getParent()));
  1276. return nullptr;
  1277. }
  1278. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1279. DeclContext*,
  1280. ASTContext&);
  1281. /// Filters out lookup results that don't fall within the given scope
  1282. /// as determined by isDeclInScope.
  1283. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1284. bool ConsiderLinkage,
  1285. bool AllowInlineNamespace) {
  1286. LookupResult::Filter F = R.makeFilter();
  1287. while (F.hasNext()) {
  1288. NamedDecl *D = F.next();
  1289. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1290. continue;
  1291. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1292. continue;
  1293. F.erase();
  1294. }
  1295. F.done();
  1296. }
  1297. /// We've determined that \p New is a redeclaration of \p Old. Check that they
  1298. /// have compatible owning modules.
  1299. bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
  1300. // FIXME: The Modules TS is not clear about how friend declarations are
  1301. // to be treated. It's not meaningful to have different owning modules for
  1302. // linkage in redeclarations of the same entity, so for now allow the
  1303. // redeclaration and change the owning modules to match.
  1304. if (New->getFriendObjectKind() &&
  1305. Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
  1306. New->setLocalOwningModule(Old->getOwningModule());
  1307. makeMergedDefinitionVisible(New);
  1308. return false;
  1309. }
  1310. Module *NewM = New->getOwningModule();
  1311. Module *OldM = Old->getOwningModule();
  1312. if (NewM && NewM->Kind == Module::PrivateModuleFragment)
  1313. NewM = NewM->Parent;
  1314. if (OldM && OldM->Kind == Module::PrivateModuleFragment)
  1315. OldM = OldM->Parent;
  1316. if (NewM == OldM)
  1317. return false;
  1318. bool NewIsModuleInterface = NewM && NewM->isModulePurview();
  1319. bool OldIsModuleInterface = OldM && OldM->isModulePurview();
  1320. if (NewIsModuleInterface || OldIsModuleInterface) {
  1321. // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
  1322. // if a declaration of D [...] appears in the purview of a module, all
  1323. // other such declarations shall appear in the purview of the same module
  1324. Diag(New->getLocation(), diag::err_mismatched_owning_module)
  1325. << New
  1326. << NewIsModuleInterface
  1327. << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
  1328. << OldIsModuleInterface
  1329. << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
  1330. Diag(Old->getLocation(), diag::note_previous_declaration);
  1331. New->setInvalidDecl();
  1332. return true;
  1333. }
  1334. return false;
  1335. }
  1336. static bool isUsingDecl(NamedDecl *D) {
  1337. return isa<UsingShadowDecl>(D) ||
  1338. isa<UnresolvedUsingTypenameDecl>(D) ||
  1339. isa<UnresolvedUsingValueDecl>(D);
  1340. }
  1341. /// Removes using shadow declarations from the lookup results.
  1342. static void RemoveUsingDecls(LookupResult &R) {
  1343. LookupResult::Filter F = R.makeFilter();
  1344. while (F.hasNext())
  1345. if (isUsingDecl(F.next()))
  1346. F.erase();
  1347. F.done();
  1348. }
  1349. /// Check for this common pattern:
  1350. /// @code
  1351. /// class S {
  1352. /// S(const S&); // DO NOT IMPLEMENT
  1353. /// void operator=(const S&); // DO NOT IMPLEMENT
  1354. /// };
  1355. /// @endcode
  1356. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1357. // FIXME: Should check for private access too but access is set after we get
  1358. // the decl here.
  1359. if (D->doesThisDeclarationHaveABody())
  1360. return false;
  1361. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1362. return CD->isCopyConstructor();
  1363. return D->isCopyAssignmentOperator();
  1364. }
  1365. // We need this to handle
  1366. //
  1367. // typedef struct {
  1368. // void *foo() { return 0; }
  1369. // } A;
  1370. //
  1371. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1372. // for example. If 'A', foo will have external linkage. If we have '*A',
  1373. // foo will have no linkage. Since we can't know until we get to the end
  1374. // of the typedef, this function finds out if D might have non-external linkage.
  1375. // Callers should verify at the end of the TU if it D has external linkage or
  1376. // not.
  1377. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1378. const DeclContext *DC = D->getDeclContext();
  1379. while (!DC->isTranslationUnit()) {
  1380. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1381. if (!RD->hasNameForLinkage())
  1382. return true;
  1383. }
  1384. DC = DC->getParent();
  1385. }
  1386. return !D->isExternallyVisible();
  1387. }
  1388. // FIXME: This needs to be refactored; some other isInMainFile users want
  1389. // these semantics.
  1390. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1391. if (S.TUKind != TU_Complete)
  1392. return false;
  1393. return S.SourceMgr.isInMainFile(Loc);
  1394. }
  1395. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1396. assert(D);
  1397. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1398. return false;
  1399. // Ignore all entities declared within templates, and out-of-line definitions
  1400. // of members of class templates.
  1401. if (D->getDeclContext()->isDependentContext() ||
  1402. D->getLexicalDeclContext()->isDependentContext())
  1403. return false;
  1404. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1405. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1406. return false;
  1407. // A non-out-of-line declaration of a member specialization was implicitly
  1408. // instantiated; it's the out-of-line declaration that we're interested in.
  1409. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1410. FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
  1411. return false;
  1412. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1413. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1414. return false;
  1415. } else {
  1416. // 'static inline' functions are defined in headers; don't warn.
  1417. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1418. return false;
  1419. }
  1420. if (FD->doesThisDeclarationHaveABody() &&
  1421. Context.DeclMustBeEmitted(FD))
  1422. return false;
  1423. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1424. // Constants and utility variables are defined in headers with internal
  1425. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1426. // like "inline".)
  1427. if (!isMainFileLoc(*this, VD->getLocation()))
  1428. return false;
  1429. if (Context.DeclMustBeEmitted(VD))
  1430. return false;
  1431. if (VD->isStaticDataMember() &&
  1432. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1433. return false;
  1434. if (VD->isStaticDataMember() &&
  1435. VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1436. VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
  1437. return false;
  1438. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1439. return false;
  1440. } else {
  1441. return false;
  1442. }
  1443. // Only warn for unused decls internal to the translation unit.
  1444. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1445. // for inline functions defined in the main source file, for instance.
  1446. return mightHaveNonExternalLinkage(D);
  1447. }
  1448. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1449. if (!D)
  1450. return;
  1451. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1452. const FunctionDecl *First = FD->getFirstDecl();
  1453. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1454. return; // First should already be in the vector.
  1455. }
  1456. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1457. const VarDecl *First = VD->getFirstDecl();
  1458. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1459. return; // First should already be in the vector.
  1460. }
  1461. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1462. UnusedFileScopedDecls.push_back(D);
  1463. }
  1464. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1465. if (D->isInvalidDecl())
  1466. return false;
  1467. bool Referenced = false;
  1468. if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
  1469. // For a decomposition declaration, warn if none of the bindings are
  1470. // referenced, instead of if the variable itself is referenced (which
  1471. // it is, by the bindings' expressions).
  1472. for (auto *BD : DD->bindings()) {
  1473. if (BD->isReferenced()) {
  1474. Referenced = true;
  1475. break;
  1476. }
  1477. }
  1478. } else if (!D->getDeclName()) {
  1479. return false;
  1480. } else if (D->isReferenced() || D->isUsed()) {
  1481. Referenced = true;
  1482. }
  1483. if (Referenced || D->hasAttr<UnusedAttr>() ||
  1484. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1485. return false;
  1486. if (isa<LabelDecl>(D))
  1487. return true;
  1488. // Except for labels, we only care about unused decls that are local to
  1489. // functions.
  1490. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1491. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1492. // For dependent types, the diagnostic is deferred.
  1493. WithinFunction =
  1494. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1495. if (!WithinFunction)
  1496. return false;
  1497. if (isa<TypedefNameDecl>(D))
  1498. return true;
  1499. // White-list anything that isn't a local variable.
  1500. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1501. return false;
  1502. // Types of valid local variables should be complete, so this should succeed.
  1503. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1504. // White-list anything with an __attribute__((unused)) type.
  1505. const auto *Ty = VD->getType().getTypePtr();
  1506. // Only look at the outermost level of typedef.
  1507. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1508. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1509. return false;
  1510. }
  1511. // If we failed to complete the type for some reason, or if the type is
  1512. // dependent, don't diagnose the variable.
  1513. if (Ty->isIncompleteType() || Ty->isDependentType())
  1514. return false;
  1515. // Look at the element type to ensure that the warning behaviour is
  1516. // consistent for both scalars and arrays.
  1517. Ty = Ty->getBaseElementTypeUnsafe();
  1518. if (const TagType *TT = Ty->getAs<TagType>()) {
  1519. const TagDecl *Tag = TT->getDecl();
  1520. if (Tag->hasAttr<UnusedAttr>())
  1521. return false;
  1522. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1523. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1524. return false;
  1525. if (const Expr *Init = VD->getInit()) {
  1526. if (const ExprWithCleanups *Cleanups =
  1527. dyn_cast<ExprWithCleanups>(Init))
  1528. Init = Cleanups->getSubExpr();
  1529. const CXXConstructExpr *Construct =
  1530. dyn_cast<CXXConstructExpr>(Init);
  1531. if (Construct && !Construct->isElidable()) {
  1532. CXXConstructorDecl *CD = Construct->getConstructor();
  1533. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
  1534. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  1535. return false;
  1536. }
  1537. }
  1538. }
  1539. }
  1540. // TODO: __attribute__((unused)) templates?
  1541. }
  1542. return true;
  1543. }
  1544. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1545. FixItHint &Hint) {
  1546. if (isa<LabelDecl>(D)) {
  1547. SourceLocation AfterColon = Lexer::findLocationAfterToken(
  1548. D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
  1549. true);
  1550. if (AfterColon.isInvalid())
  1551. return;
  1552. Hint = FixItHint::CreateRemoval(
  1553. CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
  1554. }
  1555. }
  1556. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1557. if (D->getTypeForDecl()->isDependentType())
  1558. return;
  1559. for (auto *TmpD : D->decls()) {
  1560. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1561. DiagnoseUnusedDecl(T);
  1562. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1563. DiagnoseUnusedNestedTypedefs(R);
  1564. }
  1565. }
  1566. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1567. /// unless they are marked attr(unused).
  1568. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1569. if (!ShouldDiagnoseUnusedDecl(D))
  1570. return;
  1571. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1572. // typedefs can be referenced later on, so the diagnostics are emitted
  1573. // at end-of-translation-unit.
  1574. UnusedLocalTypedefNameCandidates.insert(TD);
  1575. return;
  1576. }
  1577. FixItHint Hint;
  1578. GenerateFixForUnusedDecl(D, Context, Hint);
  1579. unsigned DiagID;
  1580. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1581. DiagID = diag::warn_unused_exception_param;
  1582. else if (isa<LabelDecl>(D))
  1583. DiagID = diag::warn_unused_label;
  1584. else
  1585. DiagID = diag::warn_unused_variable;
  1586. Diag(D->getLocation(), DiagID) << D << Hint;
  1587. }
  1588. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1589. // Verify that we have no forward references left. If so, there was a goto
  1590. // or address of a label taken, but no definition of it. Label fwd
  1591. // definitions are indicated with a null substmt which is also not a resolved
  1592. // MS inline assembly label name.
  1593. bool Diagnose = false;
  1594. if (L->isMSAsmLabel())
  1595. Diagnose = !L->isResolvedMSAsmLabel();
  1596. else
  1597. Diagnose = L->getStmt() == nullptr;
  1598. if (Diagnose)
  1599. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1600. }
  1601. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1602. S->mergeNRVOIntoParent();
  1603. if (S->decl_empty()) return;
  1604. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1605. "Scope shouldn't contain decls!");
  1606. for (auto *TmpD : S->decls()) {
  1607. assert(TmpD && "This decl didn't get pushed??");
  1608. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1609. NamedDecl *D = cast<NamedDecl>(TmpD);
  1610. // Diagnose unused variables in this scope.
  1611. if (!S->hasUnrecoverableErrorOccurred()) {
  1612. DiagnoseUnusedDecl(D);
  1613. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1614. DiagnoseUnusedNestedTypedefs(RD);
  1615. }
  1616. if (!D->getDeclName()) continue;
  1617. // If this was a forward reference to a label, verify it was defined.
  1618. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1619. CheckPoppedLabel(LD, *this);
  1620. // Remove this name from our lexical scope, and warn on it if we haven't
  1621. // already.
  1622. IdResolver.RemoveDecl(D);
  1623. auto ShadowI = ShadowingDecls.find(D);
  1624. if (ShadowI != ShadowingDecls.end()) {
  1625. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1626. Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
  1627. << D << FD << FD->getParent();
  1628. Diag(FD->getLocation(), diag::note_previous_declaration);
  1629. }
  1630. ShadowingDecls.erase(ShadowI);
  1631. }
  1632. }
  1633. }
  1634. /// Look for an Objective-C class in the translation unit.
  1635. ///
  1636. /// \param Id The name of the Objective-C class we're looking for. If
  1637. /// typo-correction fixes this name, the Id will be updated
  1638. /// to the fixed name.
  1639. ///
  1640. /// \param IdLoc The location of the name in the translation unit.
  1641. ///
  1642. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1643. /// if there is no class with the given name.
  1644. ///
  1645. /// \returns The declaration of the named Objective-C class, or NULL if the
  1646. /// class could not be found.
  1647. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1648. SourceLocation IdLoc,
  1649. bool DoTypoCorrection) {
  1650. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1651. // creation from this context.
  1652. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1653. if (!IDecl && DoTypoCorrection) {
  1654. // Perform typo correction at the given location, but only if we
  1655. // find an Objective-C class name.
  1656. DeclFilterCCC<ObjCInterfaceDecl> CCC{};
  1657. if (TypoCorrection C =
  1658. CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
  1659. TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
  1660. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1661. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1662. Id = IDecl->getIdentifier();
  1663. }
  1664. }
  1665. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1666. // This routine must always return a class definition, if any.
  1667. if (Def && Def->getDefinition())
  1668. Def = Def->getDefinition();
  1669. return Def;
  1670. }
  1671. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1672. /// from S, where a non-field would be declared. This routine copes
  1673. /// with the difference between C and C++ scoping rules in structs and
  1674. /// unions. For example, the following code is well-formed in C but
  1675. /// ill-formed in C++:
  1676. /// @code
  1677. /// struct S6 {
  1678. /// enum { BAR } e;
  1679. /// };
  1680. ///
  1681. /// void test_S6() {
  1682. /// struct S6 a;
  1683. /// a.e = BAR;
  1684. /// }
  1685. /// @endcode
  1686. /// For the declaration of BAR, this routine will return a different
  1687. /// scope. The scope S will be the scope of the unnamed enumeration
  1688. /// within S6. In C++, this routine will return the scope associated
  1689. /// with S6, because the enumeration's scope is a transparent
  1690. /// context but structures can contain non-field names. In C, this
  1691. /// routine will return the translation unit scope, since the
  1692. /// enumeration's scope is a transparent context and structures cannot
  1693. /// contain non-field names.
  1694. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1695. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1696. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1697. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1698. S = S->getParent();
  1699. return S;
  1700. }
  1701. /// Looks up the declaration of "struct objc_super" and
  1702. /// saves it for later use in building builtin declaration of
  1703. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1704. /// pre-existing declaration exists no action takes place.
  1705. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1706. IdentifierInfo *II) {
  1707. if (!II->isStr("objc_msgSendSuper"))
  1708. return;
  1709. ASTContext &Context = ThisSema.Context;
  1710. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1711. SourceLocation(), Sema::LookupTagName);
  1712. ThisSema.LookupName(Result, S);
  1713. if (Result.getResultKind() == LookupResult::Found)
  1714. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1715. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1716. }
  1717. static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
  1718. ASTContext::GetBuiltinTypeError Error) {
  1719. switch (Error) {
  1720. case ASTContext::GE_None:
  1721. return "";
  1722. case ASTContext::GE_Missing_type:
  1723. return BuiltinInfo.getHeaderName(ID);
  1724. case ASTContext::GE_Missing_stdio:
  1725. return "stdio.h";
  1726. case ASTContext::GE_Missing_setjmp:
  1727. return "setjmp.h";
  1728. case ASTContext::GE_Missing_ucontext:
  1729. return "ucontext.h";
  1730. }
  1731. llvm_unreachable("unhandled error kind");
  1732. }
  1733. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1734. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1735. /// if we're creating this built-in in anticipation of redeclaring the
  1736. /// built-in.
  1737. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1738. Scope *S, bool ForRedeclaration,
  1739. SourceLocation Loc) {
  1740. LookupPredefedObjCSuperType(*this, S, II);
  1741. ASTContext::GetBuiltinTypeError Error;
  1742. QualType R = Context.GetBuiltinType(ID, Error);
  1743. if (Error) {
  1744. if (!ForRedeclaration)
  1745. return nullptr;
  1746. // If we have a builtin without an associated type we should not emit a
  1747. // warning when we were not able to find a type for it.
  1748. if (Error == ASTContext::GE_Missing_type)
  1749. return nullptr;
  1750. // If we could not find a type for setjmp it is because the jmp_buf type was
  1751. // not defined prior to the setjmp declaration.
  1752. if (Error == ASTContext::GE_Missing_setjmp) {
  1753. Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
  1754. << Context.BuiltinInfo.getName(ID);
  1755. return nullptr;
  1756. }
  1757. // Generally, we emit a warning that the declaration requires the
  1758. // appropriate header.
  1759. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1760. << getHeaderName(Context.BuiltinInfo, ID, Error)
  1761. << Context.BuiltinInfo.getName(ID);
  1762. return nullptr;
  1763. }
  1764. if (!ForRedeclaration &&
  1765. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1766. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1767. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1768. << Context.BuiltinInfo.getName(ID) << R;
  1769. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1770. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1771. Diag(Loc, diag::note_include_header_or_declare)
  1772. << Context.BuiltinInfo.getHeaderName(ID)
  1773. << Context.BuiltinInfo.getName(ID);
  1774. }
  1775. if (R.isNull())
  1776. return nullptr;
  1777. DeclContext *Parent = Context.getTranslationUnitDecl();
  1778. if (getLangOpts().CPlusPlus) {
  1779. LinkageSpecDecl *CLinkageDecl =
  1780. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1781. LinkageSpecDecl::lang_c, false);
  1782. CLinkageDecl->setImplicit();
  1783. Parent->addDecl(CLinkageDecl);
  1784. Parent = CLinkageDecl;
  1785. }
  1786. FunctionDecl *New = FunctionDecl::Create(Context,
  1787. Parent,
  1788. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1789. SC_Extern,
  1790. false,
  1791. R->isFunctionProtoType());
  1792. New->setImplicit();
  1793. // Create Decl objects for each parameter, adding them to the
  1794. // FunctionDecl.
  1795. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1796. SmallVector<ParmVarDecl*, 16> Params;
  1797. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1798. ParmVarDecl *parm =
  1799. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1800. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1801. SC_None, nullptr);
  1802. parm->setScopeInfo(0, i);
  1803. Params.push_back(parm);
  1804. }
  1805. New->setParams(Params);
  1806. }
  1807. AddKnownFunctionAttributes(New);
  1808. RegisterLocallyScopedExternCDecl(New, S);
  1809. // TUScope is the translation-unit scope to insert this function into.
  1810. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1811. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1812. // entirely, but we're not there yet.
  1813. DeclContext *SavedContext = CurContext;
  1814. CurContext = Parent;
  1815. PushOnScopeChains(New, TUScope);
  1816. CurContext = SavedContext;
  1817. return New;
  1818. }
  1819. /// Typedef declarations don't have linkage, but they still denote the same
  1820. /// entity if their types are the same.
  1821. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1822. /// isSameEntity.
  1823. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1824. TypedefNameDecl *Decl,
  1825. LookupResult &Previous) {
  1826. // This is only interesting when modules are enabled.
  1827. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1828. return;
  1829. // Empty sets are uninteresting.
  1830. if (Previous.empty())
  1831. return;
  1832. LookupResult::Filter Filter = Previous.makeFilter();
  1833. while (Filter.hasNext()) {
  1834. NamedDecl *Old = Filter.next();
  1835. // Non-hidden declarations are never ignored.
  1836. if (S.isVisible(Old))
  1837. continue;
  1838. // Declarations of the same entity are not ignored, even if they have
  1839. // different linkages.
  1840. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1841. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1842. Decl->getUnderlyingType()))
  1843. continue;
  1844. // If both declarations give a tag declaration a typedef name for linkage
  1845. // purposes, then they declare the same entity.
  1846. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1847. Decl->getAnonDeclWithTypedefName())
  1848. continue;
  1849. }
  1850. Filter.erase();
  1851. }
  1852. Filter.done();
  1853. }
  1854. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1855. QualType OldType;
  1856. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1857. OldType = OldTypedef->getUnderlyingType();
  1858. else
  1859. OldType = Context.getTypeDeclType(Old);
  1860. QualType NewType = New->getUnderlyingType();
  1861. if (NewType->isVariablyModifiedType()) {
  1862. // Must not redefine a typedef with a variably-modified type.
  1863. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1864. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1865. << Kind << NewType;
  1866. if (Old->getLocation().isValid())
  1867. notePreviousDefinition(Old, New->getLocation());
  1868. New->setInvalidDecl();
  1869. return true;
  1870. }
  1871. if (OldType != NewType &&
  1872. !OldType->isDependentType() &&
  1873. !NewType->isDependentType() &&
  1874. !Context.hasSameType(OldType, NewType)) {
  1875. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1876. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1877. << Kind << NewType << OldType;
  1878. if (Old->getLocation().isValid())
  1879. notePreviousDefinition(Old, New->getLocation());
  1880. New->setInvalidDecl();
  1881. return true;
  1882. }
  1883. return false;
  1884. }
  1885. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1886. /// same name and scope as a previous declaration 'Old'. Figure out
  1887. /// how to resolve this situation, merging decls or emitting
  1888. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1889. ///
  1890. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1891. LookupResult &OldDecls) {
  1892. // If the new decl is known invalid already, don't bother doing any
  1893. // merging checks.
  1894. if (New->isInvalidDecl()) return;
  1895. // Allow multiple definitions for ObjC built-in typedefs.
  1896. // FIXME: Verify the underlying types are equivalent!
  1897. if (getLangOpts().ObjC) {
  1898. const IdentifierInfo *TypeID = New->getIdentifier();
  1899. switch (TypeID->getLength()) {
  1900. default: break;
  1901. case 2:
  1902. {
  1903. if (!TypeID->isStr("id"))
  1904. break;
  1905. QualType T = New->getUnderlyingType();
  1906. if (!T->isPointerType())
  1907. break;
  1908. if (!T->isVoidPointerType()) {
  1909. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1910. if (!PT->isStructureType())
  1911. break;
  1912. }
  1913. Context.setObjCIdRedefinitionType(T);
  1914. // Install the built-in type for 'id', ignoring the current definition.
  1915. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1916. return;
  1917. }
  1918. case 5:
  1919. if (!TypeID->isStr("Class"))
  1920. break;
  1921. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1922. // Install the built-in type for 'Class', ignoring the current definition.
  1923. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1924. return;
  1925. case 3:
  1926. if (!TypeID->isStr("SEL"))
  1927. break;
  1928. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1929. // Install the built-in type for 'SEL', ignoring the current definition.
  1930. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1931. return;
  1932. }
  1933. // Fall through - the typedef name was not a builtin type.
  1934. }
  1935. // Verify the old decl was also a type.
  1936. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1937. if (!Old) {
  1938. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1939. << New->getDeclName();
  1940. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1941. if (OldD->getLocation().isValid())
  1942. notePreviousDefinition(OldD, New->getLocation());
  1943. return New->setInvalidDecl();
  1944. }
  1945. // If the old declaration is invalid, just give up here.
  1946. if (Old->isInvalidDecl())
  1947. return New->setInvalidDecl();
  1948. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1949. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1950. auto *NewTag = New->getAnonDeclWithTypedefName();
  1951. NamedDecl *Hidden = nullptr;
  1952. if (OldTag && NewTag &&
  1953. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1954. !hasVisibleDefinition(OldTag, &Hidden)) {
  1955. // There is a definition of this tag, but it is not visible. Use it
  1956. // instead of our tag.
  1957. New->setTypeForDecl(OldTD->getTypeForDecl());
  1958. if (OldTD->isModed())
  1959. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1960. OldTD->getUnderlyingType());
  1961. else
  1962. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1963. // Make the old tag definition visible.
  1964. makeMergedDefinitionVisible(Hidden);
  1965. // If this was an unscoped enumeration, yank all of its enumerators
  1966. // out of the scope.
  1967. if (isa<EnumDecl>(NewTag)) {
  1968. Scope *EnumScope = getNonFieldDeclScope(S);
  1969. for (auto *D : NewTag->decls()) {
  1970. auto *ED = cast<EnumConstantDecl>(D);
  1971. assert(EnumScope->isDeclScope(ED));
  1972. EnumScope->RemoveDecl(ED);
  1973. IdResolver.RemoveDecl(ED);
  1974. ED->getLexicalDeclContext()->removeDecl(ED);
  1975. }
  1976. }
  1977. }
  1978. }
  1979. // If the typedef types are not identical, reject them in all languages and
  1980. // with any extensions enabled.
  1981. if (isIncompatibleTypedef(Old, New))
  1982. return;
  1983. // The types match. Link up the redeclaration chain and merge attributes if
  1984. // the old declaration was a typedef.
  1985. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1986. New->setPreviousDecl(Typedef);
  1987. mergeDeclAttributes(New, Old);
  1988. }
  1989. if (getLangOpts().MicrosoftExt)
  1990. return;
  1991. if (getLangOpts().CPlusPlus) {
  1992. // C++ [dcl.typedef]p2:
  1993. // In a given non-class scope, a typedef specifier can be used to
  1994. // redefine the name of any type declared in that scope to refer
  1995. // to the type to which it already refers.
  1996. if (!isa<CXXRecordDecl>(CurContext))
  1997. return;
  1998. // C++0x [dcl.typedef]p4:
  1999. // In a given class scope, a typedef specifier can be used to redefine
  2000. // any class-name declared in that scope that is not also a typedef-name
  2001. // to refer to the type to which it already refers.
  2002. //
  2003. // This wording came in via DR424, which was a correction to the
  2004. // wording in DR56, which accidentally banned code like:
  2005. //
  2006. // struct S {
  2007. // typedef struct A { } A;
  2008. // };
  2009. //
  2010. // in the C++03 standard. We implement the C++0x semantics, which
  2011. // allow the above but disallow
  2012. //
  2013. // struct S {
  2014. // typedef int I;
  2015. // typedef int I;
  2016. // };
  2017. //
  2018. // since that was the intent of DR56.
  2019. if (!isa<TypedefNameDecl>(Old))
  2020. return;
  2021. Diag(New->getLocation(), diag::err_redefinition)
  2022. << New->getDeclName();
  2023. notePreviousDefinition(Old, New->getLocation());
  2024. return New->setInvalidDecl();
  2025. }
  2026. // Modules always permit redefinition of typedefs, as does C11.
  2027. if (getLangOpts().Modules || getLangOpts().C11)
  2028. return;
  2029. // If we have a redefinition of a typedef in C, emit a warning. This warning
  2030. // is normally mapped to an error, but can be controlled with
  2031. // -Wtypedef-redefinition. If either the original or the redefinition is
  2032. // in a system header, don't emit this for compatibility with GCC.
  2033. if (getDiagnostics().getSuppressSystemWarnings() &&
  2034. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  2035. (Old->isImplicit() ||
  2036. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  2037. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  2038. return;
  2039. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  2040. << New->getDeclName();
  2041. notePreviousDefinition(Old, New->getLocation());
  2042. }
  2043. /// DeclhasAttr - returns true if decl Declaration already has the target
  2044. /// attribute.
  2045. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  2046. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  2047. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  2048. for (const auto *i : D->attrs())
  2049. if (i->getKind() == A->getKind()) {
  2050. if (Ann) {
  2051. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  2052. return true;
  2053. continue;
  2054. }
  2055. // FIXME: Don't hardcode this check
  2056. if (OA && isa<OwnershipAttr>(i))
  2057. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  2058. return true;
  2059. }
  2060. return false;
  2061. }
  2062. static bool isAttributeTargetADefinition(Decl *D) {
  2063. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  2064. return VD->isThisDeclarationADefinition();
  2065. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  2066. return TD->isCompleteDefinition() || TD->isBeingDefined();
  2067. return true;
  2068. }
  2069. /// Merge alignment attributes from \p Old to \p New, taking into account the
  2070. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  2071. ///
  2072. /// \return \c true if any attributes were added to \p New.
  2073. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  2074. // Look for alignas attributes on Old, and pick out whichever attribute
  2075. // specifies the strictest alignment requirement.
  2076. AlignedAttr *OldAlignasAttr = nullptr;
  2077. AlignedAttr *OldStrictestAlignAttr = nullptr;
  2078. unsigned OldAlign = 0;
  2079. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  2080. // FIXME: We have no way of representing inherited dependent alignments
  2081. // in a case like:
  2082. // template<int A, int B> struct alignas(A) X;
  2083. // template<int A, int B> struct alignas(B) X {};
  2084. // For now, we just ignore any alignas attributes which are not on the
  2085. // definition in such a case.
  2086. if (I->isAlignmentDependent())
  2087. return false;
  2088. if (I->isAlignas())
  2089. OldAlignasAttr = I;
  2090. unsigned Align = I->getAlignment(S.Context);
  2091. if (Align > OldAlign) {
  2092. OldAlign = Align;
  2093. OldStrictestAlignAttr = I;
  2094. }
  2095. }
  2096. // Look for alignas attributes on New.
  2097. AlignedAttr *NewAlignasAttr = nullptr;
  2098. unsigned NewAlign = 0;
  2099. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2100. if (I->isAlignmentDependent())
  2101. return false;
  2102. if (I->isAlignas())
  2103. NewAlignasAttr = I;
  2104. unsigned Align = I->getAlignment(S.Context);
  2105. if (Align > NewAlign)
  2106. NewAlign = Align;
  2107. }
  2108. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2109. // Both declarations have 'alignas' attributes. We require them to match.
  2110. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2111. // fall short. (If two declarations both have alignas, they must both match
  2112. // every definition, and so must match each other if there is a definition.)
  2113. // If either declaration only contains 'alignas(0)' specifiers, then it
  2114. // specifies the natural alignment for the type.
  2115. if (OldAlign == 0 || NewAlign == 0) {
  2116. QualType Ty;
  2117. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2118. Ty = VD->getType();
  2119. else
  2120. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2121. if (OldAlign == 0)
  2122. OldAlign = S.Context.getTypeAlign(Ty);
  2123. if (NewAlign == 0)
  2124. NewAlign = S.Context.getTypeAlign(Ty);
  2125. }
  2126. if (OldAlign != NewAlign) {
  2127. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2128. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2129. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2130. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2131. }
  2132. }
  2133. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2134. // C++11 [dcl.align]p6:
  2135. // if any declaration of an entity has an alignment-specifier,
  2136. // every defining declaration of that entity shall specify an
  2137. // equivalent alignment.
  2138. // C11 6.7.5/7:
  2139. // If the definition of an object does not have an alignment
  2140. // specifier, any other declaration of that object shall also
  2141. // have no alignment specifier.
  2142. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2143. << OldAlignasAttr;
  2144. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2145. << OldAlignasAttr;
  2146. }
  2147. bool AnyAdded = false;
  2148. // Ensure we have an attribute representing the strictest alignment.
  2149. if (OldAlign > NewAlign) {
  2150. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2151. Clone->setInherited(true);
  2152. New->addAttr(Clone);
  2153. AnyAdded = true;
  2154. }
  2155. // Ensure we have an alignas attribute if the old declaration had one.
  2156. if (OldAlignasAttr && !NewAlignasAttr &&
  2157. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2158. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2159. Clone->setInherited(true);
  2160. New->addAttr(Clone);
  2161. AnyAdded = true;
  2162. }
  2163. return AnyAdded;
  2164. }
  2165. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2166. const InheritableAttr *Attr,
  2167. Sema::AvailabilityMergeKind AMK) {
  2168. // This function copies an attribute Attr from a previous declaration to the
  2169. // new declaration D if the new declaration doesn't itself have that attribute
  2170. // yet or if that attribute allows duplicates.
  2171. // If you're adding a new attribute that requires logic different from
  2172. // "use explicit attribute on decl if present, else use attribute from
  2173. // previous decl", for example if the attribute needs to be consistent
  2174. // between redeclarations, you need to call a custom merge function here.
  2175. InheritableAttr *NewAttr = nullptr;
  2176. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2177. NewAttr = S.mergeAvailabilityAttr(
  2178. D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
  2179. AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
  2180. AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
  2181. AA->getPriority());
  2182. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2183. NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
  2184. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2185. NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
  2186. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2187. NewAttr = S.mergeDLLImportAttr(D, *ImportA);
  2188. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2189. NewAttr = S.mergeDLLExportAttr(D, *ExportA);
  2190. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2191. NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
  2192. FA->getFirstArg());
  2193. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2194. NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
  2195. else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
  2196. NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
  2197. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2198. NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
  2199. IA->getSemanticSpelling());
  2200. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2201. NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
  2202. &S.Context.Idents.get(AA->getSpelling()));
  2203. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2204. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2205. isa<CUDAGlobalAttr>(Attr))) {
  2206. // CUDA target attributes are part of function signature for
  2207. // overloading purposes and must not be merged.
  2208. return false;
  2209. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2210. NewAttr = S.mergeMinSizeAttr(D, *MA);
  2211. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2212. NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
  2213. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2214. NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
  2215. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2216. NewAttr = S.mergeCommonAttr(D, *CommonA);
  2217. else if (isa<AlignedAttr>(Attr))
  2218. // AlignedAttrs are handled separately, because we need to handle all
  2219. // such attributes on a declaration at the same time.
  2220. NewAttr = nullptr;
  2221. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2222. (AMK == Sema::AMK_Override ||
  2223. AMK == Sema::AMK_ProtocolImplementation))
  2224. NewAttr = nullptr;
  2225. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2226. NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
  2227. else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
  2228. NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
  2229. else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
  2230. NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
  2231. else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
  2232. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2233. if (NewAttr) {
  2234. NewAttr->setInherited(true);
  2235. D->addAttr(NewAttr);
  2236. if (isa<MSInheritanceAttr>(NewAttr))
  2237. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2238. return true;
  2239. }
  2240. return false;
  2241. }
  2242. static const NamedDecl *getDefinition(const Decl *D) {
  2243. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2244. return TD->getDefinition();
  2245. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2246. const VarDecl *Def = VD->getDefinition();
  2247. if (Def)
  2248. return Def;
  2249. return VD->getActingDefinition();
  2250. }
  2251. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2252. return FD->getDefinition();
  2253. return nullptr;
  2254. }
  2255. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2256. for (const auto *Attribute : D->attrs())
  2257. if (Attribute->getKind() == Kind)
  2258. return true;
  2259. return false;
  2260. }
  2261. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2262. /// there are no new attributes in this declaration.
  2263. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2264. if (!New->hasAttrs())
  2265. return;
  2266. const NamedDecl *Def = getDefinition(Old);
  2267. if (!Def || Def == New)
  2268. return;
  2269. AttrVec &NewAttributes = New->getAttrs();
  2270. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2271. const Attr *NewAttribute = NewAttributes[I];
  2272. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2273. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2274. Sema::SkipBodyInfo SkipBody;
  2275. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2276. // If we're skipping this definition, drop the "alias" attribute.
  2277. if (SkipBody.ShouldSkip) {
  2278. NewAttributes.erase(NewAttributes.begin() + I);
  2279. --E;
  2280. continue;
  2281. }
  2282. } else {
  2283. VarDecl *VD = cast<VarDecl>(New);
  2284. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2285. VarDecl::TentativeDefinition
  2286. ? diag::err_alias_after_tentative
  2287. : diag::err_redefinition;
  2288. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2289. if (Diag == diag::err_redefinition)
  2290. S.notePreviousDefinition(Def, VD->getLocation());
  2291. else
  2292. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2293. VD->setInvalidDecl();
  2294. }
  2295. ++I;
  2296. continue;
  2297. }
  2298. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2299. // Tentative definitions are only interesting for the alias check above.
  2300. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2301. ++I;
  2302. continue;
  2303. }
  2304. }
  2305. if (hasAttribute(Def, NewAttribute->getKind())) {
  2306. ++I;
  2307. continue; // regular attr merging will take care of validating this.
  2308. }
  2309. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2310. // C's _Noreturn is allowed to be added to a function after it is defined.
  2311. ++I;
  2312. continue;
  2313. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2314. if (AA->isAlignas()) {
  2315. // C++11 [dcl.align]p6:
  2316. // if any declaration of an entity has an alignment-specifier,
  2317. // every defining declaration of that entity shall specify an
  2318. // equivalent alignment.
  2319. // C11 6.7.5/7:
  2320. // If the definition of an object does not have an alignment
  2321. // specifier, any other declaration of that object shall also
  2322. // have no alignment specifier.
  2323. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2324. << AA;
  2325. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2326. << AA;
  2327. NewAttributes.erase(NewAttributes.begin() + I);
  2328. --E;
  2329. continue;
  2330. }
  2331. } else if (isa<SelectAnyAttr>(NewAttribute) &&
  2332. cast<VarDecl>(New)->isInline() &&
  2333. !cast<VarDecl>(New)->isInlineSpecified()) {
  2334. // Don't warn about applying selectany to implicitly inline variables.
  2335. // Older compilers and language modes would require the use of selectany
  2336. // to make such variables inline, and it would have no effect if we
  2337. // honored it.
  2338. ++I;
  2339. continue;
  2340. }
  2341. S.Diag(NewAttribute->getLocation(),
  2342. diag::warn_attribute_precede_definition);
  2343. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2344. NewAttributes.erase(NewAttributes.begin() + I);
  2345. --E;
  2346. }
  2347. }
  2348. static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
  2349. const ConstInitAttr *CIAttr,
  2350. bool AttrBeforeInit) {
  2351. SourceLocation InsertLoc = InitDecl->getInnerLocStart();
  2352. // Figure out a good way to write this specifier on the old declaration.
  2353. // FIXME: We should just use the spelling of CIAttr, but we don't preserve
  2354. // enough of the attribute list spelling information to extract that without
  2355. // heroics.
  2356. std::string SuitableSpelling;
  2357. if (S.getLangOpts().CPlusPlus2a)
  2358. SuitableSpelling =
  2359. S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
  2360. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
  2361. SuitableSpelling = S.PP.getLastMacroWithSpelling(
  2362. InsertLoc,
  2363. {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
  2364. tok::coloncolon,
  2365. S.PP.getIdentifierInfo("require_constant_initialization"),
  2366. tok::r_square, tok::r_square});
  2367. if (SuitableSpelling.empty())
  2368. SuitableSpelling = S.PP.getLastMacroWithSpelling(
  2369. InsertLoc,
  2370. {tok::kw___attribute, tok::l_paren, tok::r_paren,
  2371. S.PP.getIdentifierInfo("require_constant_initialization"),
  2372. tok::r_paren, tok::r_paren});
  2373. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
  2374. SuitableSpelling = "constinit";
  2375. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
  2376. SuitableSpelling = "[[clang::require_constant_initialization]]";
  2377. if (SuitableSpelling.empty())
  2378. SuitableSpelling = "__attribute__((require_constant_initialization))";
  2379. SuitableSpelling += " ";
  2380. if (AttrBeforeInit) {
  2381. // extern constinit int a;
  2382. // int a = 0; // error (missing 'constinit'), accepted as extension
  2383. assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
  2384. S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
  2385. << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
  2386. S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
  2387. } else {
  2388. // int a = 0;
  2389. // constinit extern int a; // error (missing 'constinit')
  2390. S.Diag(CIAttr->getLocation(),
  2391. CIAttr->isConstinit() ? diag::err_constinit_added_too_late
  2392. : diag::warn_require_const_init_added_too_late)
  2393. << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
  2394. S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
  2395. << CIAttr->isConstinit()
  2396. << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
  2397. }
  2398. }
  2399. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2400. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2401. AvailabilityMergeKind AMK) {
  2402. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2403. UsedAttr *NewAttr = OldAttr->clone(Context);
  2404. NewAttr->setInherited(true);
  2405. New->addAttr(NewAttr);
  2406. }
  2407. if (!Old->hasAttrs() && !New->hasAttrs())
  2408. return;
  2409. // [dcl.constinit]p1:
  2410. // If the [constinit] specifier is applied to any declaration of a
  2411. // variable, it shall be applied to the initializing declaration.
  2412. const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
  2413. const auto *NewConstInit = New->getAttr<ConstInitAttr>();
  2414. if (bool(OldConstInit) != bool(NewConstInit)) {
  2415. const auto *OldVD = cast<VarDecl>(Old);
  2416. auto *NewVD = cast<VarDecl>(New);
  2417. // Find the initializing declaration. Note that we might not have linked
  2418. // the new declaration into the redeclaration chain yet.
  2419. const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
  2420. if (!InitDecl &&
  2421. (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
  2422. InitDecl = NewVD;
  2423. if (InitDecl == NewVD) {
  2424. // This is the initializing declaration. If it would inherit 'constinit',
  2425. // that's ill-formed. (Note that we do not apply this to the attribute
  2426. // form).
  2427. if (OldConstInit && OldConstInit->isConstinit())
  2428. diagnoseMissingConstinit(*this, NewVD, OldConstInit,
  2429. /*AttrBeforeInit=*/true);
  2430. } else if (NewConstInit) {
  2431. // This is the first time we've been told that this declaration should
  2432. // have a constant initializer. If we already saw the initializing
  2433. // declaration, this is too late.
  2434. if (InitDecl && InitDecl != NewVD) {
  2435. diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
  2436. /*AttrBeforeInit=*/false);
  2437. NewVD->dropAttr<ConstInitAttr>();
  2438. }
  2439. }
  2440. }
  2441. // Attributes declared post-definition are currently ignored.
  2442. checkNewAttributesAfterDef(*this, New, Old);
  2443. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2444. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2445. if (!OldA->isEquivalent(NewA)) {
  2446. // This redeclaration changes __asm__ label.
  2447. Diag(New->getLocation(), diag::err_different_asm_label);
  2448. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2449. }
  2450. } else if (Old->isUsed()) {
  2451. // This redeclaration adds an __asm__ label to a declaration that has
  2452. // already been ODR-used.
  2453. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2454. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2455. }
  2456. }
  2457. // Re-declaration cannot add abi_tag's.
  2458. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2459. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2460. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2461. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2462. NewTag) == OldAbiTagAttr->tags_end()) {
  2463. Diag(NewAbiTagAttr->getLocation(),
  2464. diag::err_new_abi_tag_on_redeclaration)
  2465. << NewTag;
  2466. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2467. }
  2468. }
  2469. } else {
  2470. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2471. Diag(Old->getLocation(), diag::note_previous_declaration);
  2472. }
  2473. }
  2474. // This redeclaration adds a section attribute.
  2475. if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
  2476. if (auto *VD = dyn_cast<VarDecl>(New)) {
  2477. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
  2478. Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
  2479. Diag(Old->getLocation(), diag::note_previous_declaration);
  2480. }
  2481. }
  2482. }
  2483. // Redeclaration adds code-seg attribute.
  2484. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  2485. if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
  2486. !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
  2487. Diag(New->getLocation(), diag::warn_mismatched_section)
  2488. << 0 /*codeseg*/;
  2489. Diag(Old->getLocation(), diag::note_previous_declaration);
  2490. }
  2491. if (!Old->hasAttrs())
  2492. return;
  2493. bool foundAny = New->hasAttrs();
  2494. // Ensure that any moving of objects within the allocated map is done before
  2495. // we process them.
  2496. if (!foundAny) New->setAttrs(AttrVec());
  2497. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2498. // Ignore deprecated/unavailable/availability attributes if requested.
  2499. AvailabilityMergeKind LocalAMK = AMK_None;
  2500. if (isa<DeprecatedAttr>(I) ||
  2501. isa<UnavailableAttr>(I) ||
  2502. isa<AvailabilityAttr>(I)) {
  2503. switch (AMK) {
  2504. case AMK_None:
  2505. continue;
  2506. case AMK_Redeclaration:
  2507. case AMK_Override:
  2508. case AMK_ProtocolImplementation:
  2509. LocalAMK = AMK;
  2510. break;
  2511. }
  2512. }
  2513. // Already handled.
  2514. if (isa<UsedAttr>(I))
  2515. continue;
  2516. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2517. foundAny = true;
  2518. }
  2519. if (mergeAlignedAttrs(*this, New, Old))
  2520. foundAny = true;
  2521. if (!foundAny) New->dropAttrs();
  2522. }
  2523. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2524. /// to the new one.
  2525. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2526. const ParmVarDecl *oldDecl,
  2527. Sema &S) {
  2528. // C++11 [dcl.attr.depend]p2:
  2529. // The first declaration of a function shall specify the
  2530. // carries_dependency attribute for its declarator-id if any declaration
  2531. // of the function specifies the carries_dependency attribute.
  2532. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2533. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2534. S.Diag(CDA->getLocation(),
  2535. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2536. // Find the first declaration of the parameter.
  2537. // FIXME: Should we build redeclaration chains for function parameters?
  2538. const FunctionDecl *FirstFD =
  2539. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2540. const ParmVarDecl *FirstVD =
  2541. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2542. S.Diag(FirstVD->getLocation(),
  2543. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2544. }
  2545. if (!oldDecl->hasAttrs())
  2546. return;
  2547. bool foundAny = newDecl->hasAttrs();
  2548. // Ensure that any moving of objects within the allocated map is
  2549. // done before we process them.
  2550. if (!foundAny) newDecl->setAttrs(AttrVec());
  2551. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2552. if (!DeclHasAttr(newDecl, I)) {
  2553. InheritableAttr *newAttr =
  2554. cast<InheritableParamAttr>(I->clone(S.Context));
  2555. newAttr->setInherited(true);
  2556. newDecl->addAttr(newAttr);
  2557. foundAny = true;
  2558. }
  2559. }
  2560. if (!foundAny) newDecl->dropAttrs();
  2561. }
  2562. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2563. const ParmVarDecl *OldParam,
  2564. Sema &S) {
  2565. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2566. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2567. if (*Oldnullability != *Newnullability) {
  2568. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2569. << DiagNullabilityKind(
  2570. *Newnullability,
  2571. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2572. != 0))
  2573. << DiagNullabilityKind(
  2574. *Oldnullability,
  2575. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2576. != 0));
  2577. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2578. }
  2579. } else {
  2580. QualType NewT = NewParam->getType();
  2581. NewT = S.Context.getAttributedType(
  2582. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2583. NewT, NewT);
  2584. NewParam->setType(NewT);
  2585. }
  2586. }
  2587. }
  2588. namespace {
  2589. /// Used in MergeFunctionDecl to keep track of function parameters in
  2590. /// C.
  2591. struct GNUCompatibleParamWarning {
  2592. ParmVarDecl *OldParm;
  2593. ParmVarDecl *NewParm;
  2594. QualType PromotedType;
  2595. };
  2596. } // end anonymous namespace
  2597. /// getSpecialMember - get the special member enum for a method.
  2598. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2599. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2600. if (Ctor->isDefaultConstructor())
  2601. return Sema::CXXDefaultConstructor;
  2602. if (Ctor->isCopyConstructor())
  2603. return Sema::CXXCopyConstructor;
  2604. if (Ctor->isMoveConstructor())
  2605. return Sema::CXXMoveConstructor;
  2606. } else if (isa<CXXDestructorDecl>(MD)) {
  2607. return Sema::CXXDestructor;
  2608. } else if (MD->isCopyAssignmentOperator()) {
  2609. return Sema::CXXCopyAssignment;
  2610. } else if (MD->isMoveAssignmentOperator()) {
  2611. return Sema::CXXMoveAssignment;
  2612. }
  2613. return Sema::CXXInvalid;
  2614. }
  2615. // Determine whether the previous declaration was a definition, implicit
  2616. // declaration, or a declaration.
  2617. template <typename T>
  2618. static std::pair<diag::kind, SourceLocation>
  2619. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2620. diag::kind PrevDiag;
  2621. SourceLocation OldLocation = Old->getLocation();
  2622. if (Old->isThisDeclarationADefinition())
  2623. PrevDiag = diag::note_previous_definition;
  2624. else if (Old->isImplicit()) {
  2625. PrevDiag = diag::note_previous_implicit_declaration;
  2626. if (OldLocation.isInvalid())
  2627. OldLocation = New->getLocation();
  2628. } else
  2629. PrevDiag = diag::note_previous_declaration;
  2630. return std::make_pair(PrevDiag, OldLocation);
  2631. }
  2632. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2633. /// only extern inline functions can be redefined, and even then only in
  2634. /// GNU89 mode.
  2635. static bool canRedefineFunction(const FunctionDecl *FD,
  2636. const LangOptions& LangOpts) {
  2637. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2638. !LangOpts.CPlusPlus &&
  2639. FD->isInlineSpecified() &&
  2640. FD->getStorageClass() == SC_Extern);
  2641. }
  2642. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2643. const AttributedType *AT = T->getAs<AttributedType>();
  2644. while (AT && !AT->isCallingConv())
  2645. AT = AT->getModifiedType()->getAs<AttributedType>();
  2646. return AT;
  2647. }
  2648. template <typename T>
  2649. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2650. const DeclContext *DC = Old->getDeclContext();
  2651. if (DC->isRecord())
  2652. return false;
  2653. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2654. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2655. return true;
  2656. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2657. return true;
  2658. return false;
  2659. }
  2660. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2661. static bool isExternC(VarTemplateDecl *) { return false; }
  2662. /// Check whether a redeclaration of an entity introduced by a
  2663. /// using-declaration is valid, given that we know it's not an overload
  2664. /// (nor a hidden tag declaration).
  2665. template<typename ExpectedDecl>
  2666. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2667. ExpectedDecl *New) {
  2668. // C++11 [basic.scope.declarative]p4:
  2669. // Given a set of declarations in a single declarative region, each of
  2670. // which specifies the same unqualified name,
  2671. // -- they shall all refer to the same entity, or all refer to functions
  2672. // and function templates; or
  2673. // -- exactly one declaration shall declare a class name or enumeration
  2674. // name that is not a typedef name and the other declarations shall all
  2675. // refer to the same variable or enumerator, or all refer to functions
  2676. // and function templates; in this case the class name or enumeration
  2677. // name is hidden (3.3.10).
  2678. // C++11 [namespace.udecl]p14:
  2679. // If a function declaration in namespace scope or block scope has the
  2680. // same name and the same parameter-type-list as a function introduced
  2681. // by a using-declaration, and the declarations do not declare the same
  2682. // function, the program is ill-formed.
  2683. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2684. if (Old &&
  2685. !Old->getDeclContext()->getRedeclContext()->Equals(
  2686. New->getDeclContext()->getRedeclContext()) &&
  2687. !(isExternC(Old) && isExternC(New)))
  2688. Old = nullptr;
  2689. if (!Old) {
  2690. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2691. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2692. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2693. return true;
  2694. }
  2695. return false;
  2696. }
  2697. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2698. const FunctionDecl *B) {
  2699. assert(A->getNumParams() == B->getNumParams());
  2700. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2701. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2702. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2703. if (AttrA == AttrB)
  2704. return true;
  2705. return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
  2706. AttrA->isDynamic() == AttrB->isDynamic();
  2707. };
  2708. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2709. }
  2710. /// If necessary, adjust the semantic declaration context for a qualified
  2711. /// declaration to name the correct inline namespace within the qualifier.
  2712. static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
  2713. DeclaratorDecl *OldD) {
  2714. // The only case where we need to update the DeclContext is when
  2715. // redeclaration lookup for a qualified name finds a declaration
  2716. // in an inline namespace within the context named by the qualifier:
  2717. //
  2718. // inline namespace N { int f(); }
  2719. // int ::f(); // Sema DC needs adjusting from :: to N::.
  2720. //
  2721. // For unqualified declarations, the semantic context *can* change
  2722. // along the redeclaration chain (for local extern declarations,
  2723. // extern "C" declarations, and friend declarations in particular).
  2724. if (!NewD->getQualifier())
  2725. return;
  2726. // NewD is probably already in the right context.
  2727. auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
  2728. auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
  2729. if (NamedDC->Equals(SemaDC))
  2730. return;
  2731. assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
  2732. NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
  2733. "unexpected context for redeclaration");
  2734. auto *LexDC = NewD->getLexicalDeclContext();
  2735. auto FixSemaDC = [=](NamedDecl *D) {
  2736. if (!D)
  2737. return;
  2738. D->setDeclContext(SemaDC);
  2739. D->setLexicalDeclContext(LexDC);
  2740. };
  2741. FixSemaDC(NewD);
  2742. if (auto *FD = dyn_cast<FunctionDecl>(NewD))
  2743. FixSemaDC(FD->getDescribedFunctionTemplate());
  2744. else if (auto *VD = dyn_cast<VarDecl>(NewD))
  2745. FixSemaDC(VD->getDescribedVarTemplate());
  2746. }
  2747. /// MergeFunctionDecl - We just parsed a function 'New' from
  2748. /// declarator D which has the same name and scope as a previous
  2749. /// declaration 'Old'. Figure out how to resolve this situation,
  2750. /// merging decls or emitting diagnostics as appropriate.
  2751. ///
  2752. /// In C++, New and Old must be declarations that are not
  2753. /// overloaded. Use IsOverload to determine whether New and Old are
  2754. /// overloaded, and to select the Old declaration that New should be
  2755. /// merged with.
  2756. ///
  2757. /// Returns true if there was an error, false otherwise.
  2758. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2759. Scope *S, bool MergeTypeWithOld) {
  2760. // Verify the old decl was also a function.
  2761. FunctionDecl *Old = OldD->getAsFunction();
  2762. if (!Old) {
  2763. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2764. if (New->getFriendObjectKind()) {
  2765. Diag(New->getLocation(), diag::err_using_decl_friend);
  2766. Diag(Shadow->getTargetDecl()->getLocation(),
  2767. diag::note_using_decl_target);
  2768. Diag(Shadow->getUsingDecl()->getLocation(),
  2769. diag::note_using_decl) << 0;
  2770. return true;
  2771. }
  2772. // Check whether the two declarations might declare the same function.
  2773. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2774. return true;
  2775. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2776. } else {
  2777. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2778. << New->getDeclName();
  2779. notePreviousDefinition(OldD, New->getLocation());
  2780. return true;
  2781. }
  2782. }
  2783. // If the old declaration is invalid, just give up here.
  2784. if (Old->isInvalidDecl())
  2785. return true;
  2786. // Disallow redeclaration of some builtins.
  2787. if (!getASTContext().canBuiltinBeRedeclared(Old)) {
  2788. Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
  2789. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  2790. << Old << Old->getType();
  2791. return true;
  2792. }
  2793. diag::kind PrevDiag;
  2794. SourceLocation OldLocation;
  2795. std::tie(PrevDiag, OldLocation) =
  2796. getNoteDiagForInvalidRedeclaration(Old, New);
  2797. // Don't complain about this if we're in GNU89 mode and the old function
  2798. // is an extern inline function.
  2799. // Don't complain about specializations. They are not supposed to have
  2800. // storage classes.
  2801. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2802. New->getStorageClass() == SC_Static &&
  2803. Old->hasExternalFormalLinkage() &&
  2804. !New->getTemplateSpecializationInfo() &&
  2805. !canRedefineFunction(Old, getLangOpts())) {
  2806. if (getLangOpts().MicrosoftExt) {
  2807. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2808. Diag(OldLocation, PrevDiag);
  2809. } else {
  2810. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2811. Diag(OldLocation, PrevDiag);
  2812. return true;
  2813. }
  2814. }
  2815. if (New->hasAttr<InternalLinkageAttr>() &&
  2816. !Old->hasAttr<InternalLinkageAttr>()) {
  2817. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2818. << New->getDeclName();
  2819. notePreviousDefinition(Old, New->getLocation());
  2820. New->dropAttr<InternalLinkageAttr>();
  2821. }
  2822. if (CheckRedeclarationModuleOwnership(New, Old))
  2823. return true;
  2824. if (!getLangOpts().CPlusPlus) {
  2825. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  2826. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  2827. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  2828. << New << OldOvl;
  2829. // Try our best to find a decl that actually has the overloadable
  2830. // attribute for the note. In most cases (e.g. programs with only one
  2831. // broken declaration/definition), this won't matter.
  2832. //
  2833. // FIXME: We could do this if we juggled some extra state in
  2834. // OverloadableAttr, rather than just removing it.
  2835. const Decl *DiagOld = Old;
  2836. if (OldOvl) {
  2837. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  2838. const auto *A = D->getAttr<OverloadableAttr>();
  2839. return A && !A->isImplicit();
  2840. });
  2841. // If we've implicitly added *all* of the overloadable attrs to this
  2842. // chain, emitting a "previous redecl" note is pointless.
  2843. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  2844. }
  2845. if (DiagOld)
  2846. Diag(DiagOld->getLocation(),
  2847. diag::note_attribute_overloadable_prev_overload)
  2848. << OldOvl;
  2849. if (OldOvl)
  2850. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  2851. else
  2852. New->dropAttr<OverloadableAttr>();
  2853. }
  2854. }
  2855. // If a function is first declared with a calling convention, but is later
  2856. // declared or defined without one, all following decls assume the calling
  2857. // convention of the first.
  2858. //
  2859. // It's OK if a function is first declared without a calling convention,
  2860. // but is later declared or defined with the default calling convention.
  2861. //
  2862. // To test if either decl has an explicit calling convention, we look for
  2863. // AttributedType sugar nodes on the type as written. If they are missing or
  2864. // were canonicalized away, we assume the calling convention was implicit.
  2865. //
  2866. // Note also that we DO NOT return at this point, because we still have
  2867. // other tests to run.
  2868. QualType OldQType = Context.getCanonicalType(Old->getType());
  2869. QualType NewQType = Context.getCanonicalType(New->getType());
  2870. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2871. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2872. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2873. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2874. bool RequiresAdjustment = false;
  2875. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2876. FunctionDecl *First = Old->getFirstDecl();
  2877. const FunctionType *FT =
  2878. First->getType().getCanonicalType()->castAs<FunctionType>();
  2879. FunctionType::ExtInfo FI = FT->getExtInfo();
  2880. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2881. if (!NewCCExplicit) {
  2882. // Inherit the CC from the previous declaration if it was specified
  2883. // there but not here.
  2884. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2885. RequiresAdjustment = true;
  2886. } else if (New->getBuiltinID()) {
  2887. // Calling Conventions on a Builtin aren't really useful and setting a
  2888. // default calling convention and cdecl'ing some builtin redeclarations is
  2889. // common, so warn and ignore the calling convention on the redeclaration.
  2890. Diag(New->getLocation(), diag::warn_cconv_unsupported)
  2891. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2892. << (int)CallingConventionIgnoredReason::BuiltinFunction;
  2893. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2894. RequiresAdjustment = true;
  2895. } else {
  2896. // Calling conventions aren't compatible, so complain.
  2897. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2898. Diag(New->getLocation(), diag::err_cconv_change)
  2899. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2900. << !FirstCCExplicit
  2901. << (!FirstCCExplicit ? "" :
  2902. FunctionType::getNameForCallConv(FI.getCC()));
  2903. // Put the note on the first decl, since it is the one that matters.
  2904. Diag(First->getLocation(), diag::note_previous_declaration);
  2905. return true;
  2906. }
  2907. }
  2908. // FIXME: diagnose the other way around?
  2909. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2910. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2911. RequiresAdjustment = true;
  2912. }
  2913. // Merge regparm attribute.
  2914. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2915. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2916. if (NewTypeInfo.getHasRegParm()) {
  2917. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2918. << NewType->getRegParmType()
  2919. << OldType->getRegParmType();
  2920. Diag(OldLocation, diag::note_previous_declaration);
  2921. return true;
  2922. }
  2923. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2924. RequiresAdjustment = true;
  2925. }
  2926. // Merge ns_returns_retained attribute.
  2927. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2928. if (NewTypeInfo.getProducesResult()) {
  2929. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  2930. << "'ns_returns_retained'";
  2931. Diag(OldLocation, diag::note_previous_declaration);
  2932. return true;
  2933. }
  2934. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2935. RequiresAdjustment = true;
  2936. }
  2937. if (OldTypeInfo.getNoCallerSavedRegs() !=
  2938. NewTypeInfo.getNoCallerSavedRegs()) {
  2939. if (NewTypeInfo.getNoCallerSavedRegs()) {
  2940. AnyX86NoCallerSavedRegistersAttr *Attr =
  2941. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  2942. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  2943. Diag(OldLocation, diag::note_previous_declaration);
  2944. return true;
  2945. }
  2946. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  2947. RequiresAdjustment = true;
  2948. }
  2949. if (RequiresAdjustment) {
  2950. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2951. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2952. New->setType(QualType(AdjustedType, 0));
  2953. NewQType = Context.getCanonicalType(New->getType());
  2954. }
  2955. // If this redeclaration makes the function inline, we may need to add it to
  2956. // UndefinedButUsed.
  2957. if (!Old->isInlined() && New->isInlined() &&
  2958. !New->hasAttr<GNUInlineAttr>() &&
  2959. !getLangOpts().GNUInline &&
  2960. Old->isUsed(false) &&
  2961. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2962. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2963. SourceLocation()));
  2964. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2965. // about it.
  2966. if (New->hasAttr<GNUInlineAttr>() &&
  2967. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2968. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2969. }
  2970. // If pass_object_size params don't match up perfectly, this isn't a valid
  2971. // redeclaration.
  2972. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  2973. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  2974. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  2975. << New->getDeclName();
  2976. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2977. return true;
  2978. }
  2979. if (getLangOpts().CPlusPlus) {
  2980. // C++1z [over.load]p2
  2981. // Certain function declarations cannot be overloaded:
  2982. // -- Function declarations that differ only in the return type,
  2983. // the exception specification, or both cannot be overloaded.
  2984. // Check the exception specifications match. This may recompute the type of
  2985. // both Old and New if it resolved exception specifications, so grab the
  2986. // types again after this. Because this updates the type, we do this before
  2987. // any of the other checks below, which may update the "de facto" NewQType
  2988. // but do not necessarily update the type of New.
  2989. if (CheckEquivalentExceptionSpec(Old, New))
  2990. return true;
  2991. OldQType = Context.getCanonicalType(Old->getType());
  2992. NewQType = Context.getCanonicalType(New->getType());
  2993. // Go back to the type source info to compare the declared return types,
  2994. // per C++1y [dcl.type.auto]p13:
  2995. // Redeclarations or specializations of a function or function template
  2996. // with a declared return type that uses a placeholder type shall also
  2997. // use that placeholder, not a deduced type.
  2998. QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
  2999. QualType NewDeclaredReturnType = New->getDeclaredReturnType();
  3000. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  3001. canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
  3002. OldDeclaredReturnType)) {
  3003. QualType ResQT;
  3004. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  3005. OldDeclaredReturnType->isObjCObjectPointerType())
  3006. // FIXME: This does the wrong thing for a deduced return type.
  3007. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  3008. if (ResQT.isNull()) {
  3009. if (New->isCXXClassMember() && New->isOutOfLine())
  3010. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  3011. << New << New->getReturnTypeSourceRange();
  3012. else
  3013. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  3014. << New->getReturnTypeSourceRange();
  3015. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  3016. << Old->getReturnTypeSourceRange();
  3017. return true;
  3018. }
  3019. else
  3020. NewQType = ResQT;
  3021. }
  3022. QualType OldReturnType = OldType->getReturnType();
  3023. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  3024. if (OldReturnType != NewReturnType) {
  3025. // If this function has a deduced return type and has already been
  3026. // defined, copy the deduced value from the old declaration.
  3027. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  3028. if (OldAT && OldAT->isDeduced()) {
  3029. New->setType(
  3030. SubstAutoType(New->getType(),
  3031. OldAT->isDependentType() ? Context.DependentTy
  3032. : OldAT->getDeducedType()));
  3033. NewQType = Context.getCanonicalType(
  3034. SubstAutoType(NewQType,
  3035. OldAT->isDependentType() ? Context.DependentTy
  3036. : OldAT->getDeducedType()));
  3037. }
  3038. }
  3039. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  3040. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  3041. if (OldMethod && NewMethod) {
  3042. // Preserve triviality.
  3043. NewMethod->setTrivial(OldMethod->isTrivial());
  3044. // MSVC allows explicit template specialization at class scope:
  3045. // 2 CXXMethodDecls referring to the same function will be injected.
  3046. // We don't want a redeclaration error.
  3047. bool IsClassScopeExplicitSpecialization =
  3048. OldMethod->isFunctionTemplateSpecialization() &&
  3049. NewMethod->isFunctionTemplateSpecialization();
  3050. bool isFriend = NewMethod->getFriendObjectKind();
  3051. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  3052. !IsClassScopeExplicitSpecialization) {
  3053. // -- Member function declarations with the same name and the
  3054. // same parameter types cannot be overloaded if any of them
  3055. // is a static member function declaration.
  3056. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  3057. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  3058. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3059. return true;
  3060. }
  3061. // C++ [class.mem]p1:
  3062. // [...] A member shall not be declared twice in the
  3063. // member-specification, except that a nested class or member
  3064. // class template can be declared and then later defined.
  3065. if (!inTemplateInstantiation()) {
  3066. unsigned NewDiag;
  3067. if (isa<CXXConstructorDecl>(OldMethod))
  3068. NewDiag = diag::err_constructor_redeclared;
  3069. else if (isa<CXXDestructorDecl>(NewMethod))
  3070. NewDiag = diag::err_destructor_redeclared;
  3071. else if (isa<CXXConversionDecl>(NewMethod))
  3072. NewDiag = diag::err_conv_function_redeclared;
  3073. else
  3074. NewDiag = diag::err_member_redeclared;
  3075. Diag(New->getLocation(), NewDiag);
  3076. } else {
  3077. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  3078. << New << New->getType();
  3079. }
  3080. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3081. return true;
  3082. // Complain if this is an explicit declaration of a special
  3083. // member that was initially declared implicitly.
  3084. //
  3085. // As an exception, it's okay to befriend such methods in order
  3086. // to permit the implicit constructor/destructor/operator calls.
  3087. } else if (OldMethod->isImplicit()) {
  3088. if (isFriend) {
  3089. NewMethod->setImplicit();
  3090. } else {
  3091. Diag(NewMethod->getLocation(),
  3092. diag::err_definition_of_implicitly_declared_member)
  3093. << New << getSpecialMember(OldMethod);
  3094. return true;
  3095. }
  3096. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  3097. Diag(NewMethod->getLocation(),
  3098. diag::err_definition_of_explicitly_defaulted_member)
  3099. << getSpecialMember(OldMethod);
  3100. return true;
  3101. }
  3102. }
  3103. // C++11 [dcl.attr.noreturn]p1:
  3104. // The first declaration of a function shall specify the noreturn
  3105. // attribute if any declaration of that function specifies the noreturn
  3106. // attribute.
  3107. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  3108. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  3109. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  3110. Diag(Old->getFirstDecl()->getLocation(),
  3111. diag::note_noreturn_missing_first_decl);
  3112. }
  3113. // C++11 [dcl.attr.depend]p2:
  3114. // The first declaration of a function shall specify the
  3115. // carries_dependency attribute for its declarator-id if any declaration
  3116. // of the function specifies the carries_dependency attribute.
  3117. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  3118. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  3119. Diag(CDA->getLocation(),
  3120. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  3121. Diag(Old->getFirstDecl()->getLocation(),
  3122. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  3123. }
  3124. // (C++98 8.3.5p3):
  3125. // All declarations for a function shall agree exactly in both the
  3126. // return type and the parameter-type-list.
  3127. // We also want to respect all the extended bits except noreturn.
  3128. // noreturn should now match unless the old type info didn't have it.
  3129. QualType OldQTypeForComparison = OldQType;
  3130. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  3131. auto *OldType = OldQType->castAs<FunctionProtoType>();
  3132. const FunctionType *OldTypeForComparison
  3133. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  3134. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  3135. assert(OldQTypeForComparison.isCanonical());
  3136. }
  3137. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3138. // As a special case, retain the language linkage from previous
  3139. // declarations of a friend function as an extension.
  3140. //
  3141. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  3142. // and is useful because there's otherwise no way to specify language
  3143. // linkage within class scope.
  3144. //
  3145. // Check cautiously as the friend object kind isn't yet complete.
  3146. if (New->getFriendObjectKind() != Decl::FOK_None) {
  3147. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  3148. Diag(OldLocation, PrevDiag);
  3149. } else {
  3150. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3151. Diag(OldLocation, PrevDiag);
  3152. return true;
  3153. }
  3154. }
  3155. // If the function types are compatible, merge the declarations. Ignore the
  3156. // exception specifier because it was already checked above in
  3157. // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
  3158. // about incompatible types under -fms-compatibility.
  3159. if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
  3160. NewQType))
  3161. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3162. // If the types are imprecise (due to dependent constructs in friends or
  3163. // local extern declarations), it's OK if they differ. We'll check again
  3164. // during instantiation.
  3165. if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
  3166. return false;
  3167. // Fall through for conflicting redeclarations and redefinitions.
  3168. }
  3169. // C: Function types need to be compatible, not identical. This handles
  3170. // duplicate function decls like "void f(int); void f(enum X);" properly.
  3171. if (!getLangOpts().CPlusPlus &&
  3172. Context.typesAreCompatible(OldQType, NewQType)) {
  3173. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  3174. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  3175. const FunctionProtoType *OldProto = nullptr;
  3176. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  3177. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  3178. // The old declaration provided a function prototype, but the
  3179. // new declaration does not. Merge in the prototype.
  3180. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  3181. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  3182. NewQType =
  3183. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  3184. OldProto->getExtProtoInfo());
  3185. New->setType(NewQType);
  3186. New->setHasInheritedPrototype();
  3187. // Synthesize parameters with the same types.
  3188. SmallVector<ParmVarDecl*, 16> Params;
  3189. for (const auto &ParamType : OldProto->param_types()) {
  3190. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  3191. SourceLocation(), nullptr,
  3192. ParamType, /*TInfo=*/nullptr,
  3193. SC_None, nullptr);
  3194. Param->setScopeInfo(0, Params.size());
  3195. Param->setImplicit();
  3196. Params.push_back(Param);
  3197. }
  3198. New->setParams(Params);
  3199. }
  3200. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3201. }
  3202. // GNU C permits a K&R definition to follow a prototype declaration
  3203. // if the declared types of the parameters in the K&R definition
  3204. // match the types in the prototype declaration, even when the
  3205. // promoted types of the parameters from the K&R definition differ
  3206. // from the types in the prototype. GCC then keeps the types from
  3207. // the prototype.
  3208. //
  3209. // If a variadic prototype is followed by a non-variadic K&R definition,
  3210. // the K&R definition becomes variadic. This is sort of an edge case, but
  3211. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  3212. // C99 6.9.1p8.
  3213. if (!getLangOpts().CPlusPlus &&
  3214. Old->hasPrototype() && !New->hasPrototype() &&
  3215. New->getType()->getAs<FunctionProtoType>() &&
  3216. Old->getNumParams() == New->getNumParams()) {
  3217. SmallVector<QualType, 16> ArgTypes;
  3218. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  3219. const FunctionProtoType *OldProto
  3220. = Old->getType()->getAs<FunctionProtoType>();
  3221. const FunctionProtoType *NewProto
  3222. = New->getType()->getAs<FunctionProtoType>();
  3223. // Determine whether this is the GNU C extension.
  3224. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  3225. NewProto->getReturnType());
  3226. bool LooseCompatible = !MergedReturn.isNull();
  3227. for (unsigned Idx = 0, End = Old->getNumParams();
  3228. LooseCompatible && Idx != End; ++Idx) {
  3229. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  3230. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  3231. if (Context.typesAreCompatible(OldParm->getType(),
  3232. NewProto->getParamType(Idx))) {
  3233. ArgTypes.push_back(NewParm->getType());
  3234. } else if (Context.typesAreCompatible(OldParm->getType(),
  3235. NewParm->getType(),
  3236. /*CompareUnqualified=*/true)) {
  3237. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  3238. NewProto->getParamType(Idx) };
  3239. Warnings.push_back(Warn);
  3240. ArgTypes.push_back(NewParm->getType());
  3241. } else
  3242. LooseCompatible = false;
  3243. }
  3244. if (LooseCompatible) {
  3245. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3246. Diag(Warnings[Warn].NewParm->getLocation(),
  3247. diag::ext_param_promoted_not_compatible_with_prototype)
  3248. << Warnings[Warn].PromotedType
  3249. << Warnings[Warn].OldParm->getType();
  3250. if (Warnings[Warn].OldParm->getLocation().isValid())
  3251. Diag(Warnings[Warn].OldParm->getLocation(),
  3252. diag::note_previous_declaration);
  3253. }
  3254. if (MergeTypeWithOld)
  3255. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3256. OldProto->getExtProtoInfo()));
  3257. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3258. }
  3259. // Fall through to diagnose conflicting types.
  3260. }
  3261. // A function that has already been declared has been redeclared or
  3262. // defined with a different type; show an appropriate diagnostic.
  3263. // If the previous declaration was an implicitly-generated builtin
  3264. // declaration, then at the very least we should use a specialized note.
  3265. unsigned BuiltinID;
  3266. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3267. // If it's actually a library-defined builtin function like 'malloc'
  3268. // or 'printf', just warn about the incompatible redeclaration.
  3269. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3270. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3271. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3272. << Old << Old->getType();
  3273. // If this is a global redeclaration, just forget hereafter
  3274. // about the "builtin-ness" of the function.
  3275. //
  3276. // Doing this for local extern declarations is problematic. If
  3277. // the builtin declaration remains visible, a second invalid
  3278. // local declaration will produce a hard error; if it doesn't
  3279. // remain visible, a single bogus local redeclaration (which is
  3280. // actually only a warning) could break all the downstream code.
  3281. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  3282. New->getIdentifier()->revertBuiltin();
  3283. return false;
  3284. }
  3285. PrevDiag = diag::note_previous_builtin_declaration;
  3286. }
  3287. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3288. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3289. return true;
  3290. }
  3291. /// Completes the merge of two function declarations that are
  3292. /// known to be compatible.
  3293. ///
  3294. /// This routine handles the merging of attributes and other
  3295. /// properties of function declarations from the old declaration to
  3296. /// the new declaration, once we know that New is in fact a
  3297. /// redeclaration of Old.
  3298. ///
  3299. /// \returns false
  3300. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3301. Scope *S, bool MergeTypeWithOld) {
  3302. // Merge the attributes
  3303. mergeDeclAttributes(New, Old);
  3304. // Merge "pure" flag.
  3305. if (Old->isPure())
  3306. New->setPure();
  3307. // Merge "used" flag.
  3308. if (Old->getMostRecentDecl()->isUsed(false))
  3309. New->setIsUsed();
  3310. // Merge attributes from the parameters. These can mismatch with K&R
  3311. // declarations.
  3312. if (New->getNumParams() == Old->getNumParams())
  3313. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3314. ParmVarDecl *NewParam = New->getParamDecl(i);
  3315. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3316. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3317. mergeParamDeclTypes(NewParam, OldParam, *this);
  3318. }
  3319. if (getLangOpts().CPlusPlus)
  3320. return MergeCXXFunctionDecl(New, Old, S);
  3321. // Merge the function types so the we get the composite types for the return
  3322. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3323. // was visible.
  3324. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3325. if (!Merged.isNull() && MergeTypeWithOld)
  3326. New->setType(Merged);
  3327. return false;
  3328. }
  3329. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3330. ObjCMethodDecl *oldMethod) {
  3331. // Merge the attributes, including deprecated/unavailable
  3332. AvailabilityMergeKind MergeKind =
  3333. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3334. ? AMK_ProtocolImplementation
  3335. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3336. : AMK_Override;
  3337. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3338. // Merge attributes from the parameters.
  3339. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3340. oe = oldMethod->param_end();
  3341. for (ObjCMethodDecl::param_iterator
  3342. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3343. ni != ne && oi != oe; ++ni, ++oi)
  3344. mergeParamDeclAttributes(*ni, *oi, *this);
  3345. CheckObjCMethodOverride(newMethod, oldMethod);
  3346. }
  3347. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3348. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3349. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3350. ? diag::err_redefinition_different_type
  3351. : diag::err_redeclaration_different_type)
  3352. << New->getDeclName() << New->getType() << Old->getType();
  3353. diag::kind PrevDiag;
  3354. SourceLocation OldLocation;
  3355. std::tie(PrevDiag, OldLocation)
  3356. = getNoteDiagForInvalidRedeclaration(Old, New);
  3357. S.Diag(OldLocation, PrevDiag);
  3358. New->setInvalidDecl();
  3359. }
  3360. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3361. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3362. /// emitting diagnostics as appropriate.
  3363. ///
  3364. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3365. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3366. /// is attached.
  3367. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3368. bool MergeTypeWithOld) {
  3369. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3370. return;
  3371. QualType MergedT;
  3372. if (getLangOpts().CPlusPlus) {
  3373. if (New->getType()->isUndeducedType()) {
  3374. // We don't know what the new type is until the initializer is attached.
  3375. return;
  3376. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3377. // These could still be something that needs exception specs checked.
  3378. return MergeVarDeclExceptionSpecs(New, Old);
  3379. }
  3380. // C++ [basic.link]p10:
  3381. // [...] the types specified by all declarations referring to a given
  3382. // object or function shall be identical, except that declarations for an
  3383. // array object can specify array types that differ by the presence or
  3384. // absence of a major array bound (8.3.4).
  3385. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3386. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3387. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3388. // We are merging a variable declaration New into Old. If it has an array
  3389. // bound, and that bound differs from Old's bound, we should diagnose the
  3390. // mismatch.
  3391. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3392. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3393. PrevVD = PrevVD->getPreviousDecl()) {
  3394. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3395. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3396. continue;
  3397. if (!Context.hasSameType(NewArray, PrevVDTy))
  3398. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3399. }
  3400. }
  3401. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3402. if (Context.hasSameType(OldArray->getElementType(),
  3403. NewArray->getElementType()))
  3404. MergedT = New->getType();
  3405. }
  3406. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3407. // has no array bound, it should not inherit one from Old, if Old is not
  3408. // visible.
  3409. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3410. if (Context.hasSameType(OldArray->getElementType(),
  3411. NewArray->getElementType()))
  3412. MergedT = Old->getType();
  3413. }
  3414. }
  3415. else if (New->getType()->isObjCObjectPointerType() &&
  3416. Old->getType()->isObjCObjectPointerType()) {
  3417. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3418. Old->getType());
  3419. }
  3420. } else {
  3421. // C 6.2.7p2:
  3422. // All declarations that refer to the same object or function shall have
  3423. // compatible type.
  3424. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3425. }
  3426. if (MergedT.isNull()) {
  3427. // It's OK if we couldn't merge types if either type is dependent, for a
  3428. // block-scope variable. In other cases (static data members of class
  3429. // templates, variable templates, ...), we require the types to be
  3430. // equivalent.
  3431. // FIXME: The C++ standard doesn't say anything about this.
  3432. if ((New->getType()->isDependentType() ||
  3433. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3434. // If the old type was dependent, we can't merge with it, so the new type
  3435. // becomes dependent for now. We'll reproduce the original type when we
  3436. // instantiate the TypeSourceInfo for the variable.
  3437. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3438. New->setType(Context.DependentTy);
  3439. return;
  3440. }
  3441. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3442. }
  3443. // Don't actually update the type on the new declaration if the old
  3444. // declaration was an extern declaration in a different scope.
  3445. if (MergeTypeWithOld)
  3446. New->setType(MergedT);
  3447. }
  3448. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3449. LookupResult &Previous) {
  3450. // C11 6.2.7p4:
  3451. // For an identifier with internal or external linkage declared
  3452. // in a scope in which a prior declaration of that identifier is
  3453. // visible, if the prior declaration specifies internal or
  3454. // external linkage, the type of the identifier at the later
  3455. // declaration becomes the composite type.
  3456. //
  3457. // If the variable isn't visible, we do not merge with its type.
  3458. if (Previous.isShadowed())
  3459. return false;
  3460. if (S.getLangOpts().CPlusPlus) {
  3461. // C++11 [dcl.array]p3:
  3462. // If there is a preceding declaration of the entity in the same
  3463. // scope in which the bound was specified, an omitted array bound
  3464. // is taken to be the same as in that earlier declaration.
  3465. return NewVD->isPreviousDeclInSameBlockScope() ||
  3466. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3467. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3468. } else {
  3469. // If the old declaration was function-local, don't merge with its
  3470. // type unless we're in the same function.
  3471. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3472. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3473. }
  3474. }
  3475. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3476. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3477. /// situation, merging decls or emitting diagnostics as appropriate.
  3478. ///
  3479. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3480. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3481. /// definitions here, since the initializer hasn't been attached.
  3482. ///
  3483. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3484. // If the new decl is already invalid, don't do any other checking.
  3485. if (New->isInvalidDecl())
  3486. return;
  3487. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3488. return;
  3489. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3490. // Verify the old decl was also a variable or variable template.
  3491. VarDecl *Old = nullptr;
  3492. VarTemplateDecl *OldTemplate = nullptr;
  3493. if (Previous.isSingleResult()) {
  3494. if (NewTemplate) {
  3495. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3496. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3497. if (auto *Shadow =
  3498. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3499. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3500. return New->setInvalidDecl();
  3501. } else {
  3502. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3503. if (auto *Shadow =
  3504. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3505. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3506. return New->setInvalidDecl();
  3507. }
  3508. }
  3509. if (!Old) {
  3510. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3511. << New->getDeclName();
  3512. notePreviousDefinition(Previous.getRepresentativeDecl(),
  3513. New->getLocation());
  3514. return New->setInvalidDecl();
  3515. }
  3516. // Ensure the template parameters are compatible.
  3517. if (NewTemplate &&
  3518. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3519. OldTemplate->getTemplateParameters(),
  3520. /*Complain=*/true, TPL_TemplateMatch))
  3521. return New->setInvalidDecl();
  3522. // C++ [class.mem]p1:
  3523. // A member shall not be declared twice in the member-specification [...]
  3524. //
  3525. // Here, we need only consider static data members.
  3526. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3527. Diag(New->getLocation(), diag::err_duplicate_member)
  3528. << New->getIdentifier();
  3529. Diag(Old->getLocation(), diag::note_previous_declaration);
  3530. New->setInvalidDecl();
  3531. }
  3532. mergeDeclAttributes(New, Old);
  3533. // Warn if an already-declared variable is made a weak_import in a subsequent
  3534. // declaration
  3535. if (New->hasAttr<WeakImportAttr>() &&
  3536. Old->getStorageClass() == SC_None &&
  3537. !Old->hasAttr<WeakImportAttr>()) {
  3538. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3539. notePreviousDefinition(Old, New->getLocation());
  3540. // Remove weak_import attribute on new declaration.
  3541. New->dropAttr<WeakImportAttr>();
  3542. }
  3543. if (New->hasAttr<InternalLinkageAttr>() &&
  3544. !Old->hasAttr<InternalLinkageAttr>()) {
  3545. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3546. << New->getDeclName();
  3547. notePreviousDefinition(Old, New->getLocation());
  3548. New->dropAttr<InternalLinkageAttr>();
  3549. }
  3550. // Merge the types.
  3551. VarDecl *MostRecent = Old->getMostRecentDecl();
  3552. if (MostRecent != Old) {
  3553. MergeVarDeclTypes(New, MostRecent,
  3554. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3555. if (New->isInvalidDecl())
  3556. return;
  3557. }
  3558. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3559. if (New->isInvalidDecl())
  3560. return;
  3561. diag::kind PrevDiag;
  3562. SourceLocation OldLocation;
  3563. std::tie(PrevDiag, OldLocation) =
  3564. getNoteDiagForInvalidRedeclaration(Old, New);
  3565. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3566. if (New->getStorageClass() == SC_Static &&
  3567. !New->isStaticDataMember() &&
  3568. Old->hasExternalFormalLinkage()) {
  3569. if (getLangOpts().MicrosoftExt) {
  3570. Diag(New->getLocation(), diag::ext_static_non_static)
  3571. << New->getDeclName();
  3572. Diag(OldLocation, PrevDiag);
  3573. } else {
  3574. Diag(New->getLocation(), diag::err_static_non_static)
  3575. << New->getDeclName();
  3576. Diag(OldLocation, PrevDiag);
  3577. return New->setInvalidDecl();
  3578. }
  3579. }
  3580. // C99 6.2.2p4:
  3581. // For an identifier declared with the storage-class specifier
  3582. // extern in a scope in which a prior declaration of that
  3583. // identifier is visible,23) if the prior declaration specifies
  3584. // internal or external linkage, the linkage of the identifier at
  3585. // the later declaration is the same as the linkage specified at
  3586. // the prior declaration. If no prior declaration is visible, or
  3587. // if the prior declaration specifies no linkage, then the
  3588. // identifier has external linkage.
  3589. if (New->hasExternalStorage() && Old->hasLinkage())
  3590. /* Okay */;
  3591. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3592. !New->isStaticDataMember() &&
  3593. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3594. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3595. Diag(OldLocation, PrevDiag);
  3596. return New->setInvalidDecl();
  3597. }
  3598. // Check if extern is followed by non-extern and vice-versa.
  3599. if (New->hasExternalStorage() &&
  3600. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3601. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3602. Diag(OldLocation, PrevDiag);
  3603. return New->setInvalidDecl();
  3604. }
  3605. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3606. !New->hasExternalStorage()) {
  3607. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3608. Diag(OldLocation, PrevDiag);
  3609. return New->setInvalidDecl();
  3610. }
  3611. if (CheckRedeclarationModuleOwnership(New, Old))
  3612. return;
  3613. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3614. // FIXME: The test for external storage here seems wrong? We still
  3615. // need to check for mismatches.
  3616. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3617. // Don't complain about out-of-line definitions of static members.
  3618. !(Old->getLexicalDeclContext()->isRecord() &&
  3619. !New->getLexicalDeclContext()->isRecord())) {
  3620. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3621. Diag(OldLocation, PrevDiag);
  3622. return New->setInvalidDecl();
  3623. }
  3624. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3625. if (VarDecl *Def = Old->getDefinition()) {
  3626. // C++1z [dcl.fcn.spec]p4:
  3627. // If the definition of a variable appears in a translation unit before
  3628. // its first declaration as inline, the program is ill-formed.
  3629. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3630. Diag(Def->getLocation(), diag::note_previous_definition);
  3631. }
  3632. }
  3633. // If this redeclaration makes the variable inline, we may need to add it to
  3634. // UndefinedButUsed.
  3635. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3636. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3637. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3638. SourceLocation()));
  3639. if (New->getTLSKind() != Old->getTLSKind()) {
  3640. if (!Old->getTLSKind()) {
  3641. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3642. Diag(OldLocation, PrevDiag);
  3643. } else if (!New->getTLSKind()) {
  3644. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3645. Diag(OldLocation, PrevDiag);
  3646. } else {
  3647. // Do not allow redeclaration to change the variable between requiring
  3648. // static and dynamic initialization.
  3649. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3650. // declaration to determine the kind. Do we need to be compatible here?
  3651. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3652. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3653. Diag(OldLocation, PrevDiag);
  3654. }
  3655. }
  3656. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3657. if (getLangOpts().CPlusPlus &&
  3658. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3659. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3660. Old->getCanonicalDecl()->isConstexpr()) {
  3661. // This definition won't be a definition any more once it's been merged.
  3662. Diag(New->getLocation(),
  3663. diag::warn_deprecated_redundant_constexpr_static_def);
  3664. } else if (VarDecl *Def = Old->getDefinition()) {
  3665. if (checkVarDeclRedefinition(Def, New))
  3666. return;
  3667. }
  3668. }
  3669. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3670. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3671. Diag(OldLocation, PrevDiag);
  3672. New->setInvalidDecl();
  3673. return;
  3674. }
  3675. // Merge "used" flag.
  3676. if (Old->getMostRecentDecl()->isUsed(false))
  3677. New->setIsUsed();
  3678. // Keep a chain of previous declarations.
  3679. New->setPreviousDecl(Old);
  3680. if (NewTemplate)
  3681. NewTemplate->setPreviousDecl(OldTemplate);
  3682. adjustDeclContextForDeclaratorDecl(New, Old);
  3683. // Inherit access appropriately.
  3684. New->setAccess(Old->getAccess());
  3685. if (NewTemplate)
  3686. NewTemplate->setAccess(New->getAccess());
  3687. if (Old->isInline())
  3688. New->setImplicitlyInline();
  3689. }
  3690. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  3691. SourceManager &SrcMgr = getSourceManager();
  3692. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  3693. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  3694. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  3695. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  3696. auto &HSI = PP.getHeaderSearchInfo();
  3697. StringRef HdrFilename =
  3698. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  3699. auto noteFromModuleOrInclude = [&](Module *Mod,
  3700. SourceLocation IncLoc) -> bool {
  3701. // Redefinition errors with modules are common with non modular mapped
  3702. // headers, example: a non-modular header H in module A that also gets
  3703. // included directly in a TU. Pointing twice to the same header/definition
  3704. // is confusing, try to get better diagnostics when modules is on.
  3705. if (IncLoc.isValid()) {
  3706. if (Mod) {
  3707. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  3708. << HdrFilename.str() << Mod->getFullModuleName();
  3709. if (!Mod->DefinitionLoc.isInvalid())
  3710. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  3711. << Mod->getFullModuleName();
  3712. } else {
  3713. Diag(IncLoc, diag::note_redefinition_include_same_file)
  3714. << HdrFilename.str();
  3715. }
  3716. return true;
  3717. }
  3718. return false;
  3719. };
  3720. // Is it the same file and same offset? Provide more information on why
  3721. // this leads to a redefinition error.
  3722. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  3723. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  3724. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  3725. bool EmittedDiag =
  3726. noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  3727. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  3728. // If the header has no guards, emit a note suggesting one.
  3729. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  3730. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  3731. if (EmittedDiag)
  3732. return;
  3733. }
  3734. // Redefinition coming from different files or couldn't do better above.
  3735. if (Old->getLocation().isValid())
  3736. Diag(Old->getLocation(), diag::note_previous_definition);
  3737. }
  3738. /// We've just determined that \p Old and \p New both appear to be definitions
  3739. /// of the same variable. Either diagnose or fix the problem.
  3740. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3741. if (!hasVisibleDefinition(Old) &&
  3742. (New->getFormalLinkage() == InternalLinkage ||
  3743. New->isInline() ||
  3744. New->getDescribedVarTemplate() ||
  3745. New->getNumTemplateParameterLists() ||
  3746. New->getDeclContext()->isDependentContext())) {
  3747. // The previous definition is hidden, and multiple definitions are
  3748. // permitted (in separate TUs). Demote this to a declaration.
  3749. New->demoteThisDefinitionToDeclaration();
  3750. // Make the canonical definition visible.
  3751. if (auto *OldTD = Old->getDescribedVarTemplate())
  3752. makeMergedDefinitionVisible(OldTD);
  3753. makeMergedDefinitionVisible(Old);
  3754. return false;
  3755. } else {
  3756. Diag(New->getLocation(), diag::err_redefinition) << New;
  3757. notePreviousDefinition(Old, New->getLocation());
  3758. New->setInvalidDecl();
  3759. return true;
  3760. }
  3761. }
  3762. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3763. /// no declarator (e.g. "struct foo;") is parsed.
  3764. Decl *
  3765. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3766. RecordDecl *&AnonRecord) {
  3767. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3768. AnonRecord);
  3769. }
  3770. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3771. // disambiguate entities defined in different scopes.
  3772. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3773. // compatibility.
  3774. // We will pick our mangling number depending on which version of MSVC is being
  3775. // targeted.
  3776. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3777. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3778. ? S->getMSCurManglingNumber()
  3779. : S->getMSLastManglingNumber();
  3780. }
  3781. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3782. if (!Context.getLangOpts().CPlusPlus)
  3783. return;
  3784. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3785. // If this tag is the direct child of a class, number it if
  3786. // it is anonymous.
  3787. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3788. return;
  3789. MangleNumberingContext &MCtx =
  3790. Context.getManglingNumberContext(Tag->getParent());
  3791. Context.setManglingNumber(
  3792. Tag, MCtx.getManglingNumber(
  3793. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3794. return;
  3795. }
  3796. // If this tag isn't a direct child of a class, number it if it is local.
  3797. Decl *ManglingContextDecl;
  3798. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3799. Tag->getDeclContext(), ManglingContextDecl)) {
  3800. Context.setManglingNumber(
  3801. Tag, MCtx->getManglingNumber(
  3802. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3803. }
  3804. }
  3805. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3806. TypedefNameDecl *NewTD) {
  3807. if (TagFromDeclSpec->isInvalidDecl())
  3808. return;
  3809. // Do nothing if the tag already has a name for linkage purposes.
  3810. if (TagFromDeclSpec->hasNameForLinkage())
  3811. return;
  3812. // A well-formed anonymous tag must always be a TUK_Definition.
  3813. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3814. // The type must match the tag exactly; no qualifiers allowed.
  3815. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3816. Context.getTagDeclType(TagFromDeclSpec))) {
  3817. if (getLangOpts().CPlusPlus)
  3818. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3819. return;
  3820. }
  3821. // If we've already computed linkage for the anonymous tag, then
  3822. // adding a typedef name for the anonymous decl can change that
  3823. // linkage, which might be a serious problem. Diagnose this as
  3824. // unsupported and ignore the typedef name. TODO: we should
  3825. // pursue this as a language defect and establish a formal rule
  3826. // for how to handle it.
  3827. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3828. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3829. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3830. tagLoc = getLocForEndOfToken(tagLoc);
  3831. llvm::SmallString<40> textToInsert;
  3832. textToInsert += ' ';
  3833. textToInsert += NewTD->getIdentifier()->getName();
  3834. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3835. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3836. return;
  3837. }
  3838. // Otherwise, set this is the anon-decl typedef for the tag.
  3839. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3840. }
  3841. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3842. switch (T) {
  3843. case DeclSpec::TST_class:
  3844. return 0;
  3845. case DeclSpec::TST_struct:
  3846. return 1;
  3847. case DeclSpec::TST_interface:
  3848. return 2;
  3849. case DeclSpec::TST_union:
  3850. return 3;
  3851. case DeclSpec::TST_enum:
  3852. return 4;
  3853. default:
  3854. llvm_unreachable("unexpected type specifier");
  3855. }
  3856. }
  3857. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3858. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3859. /// parameters to cope with template friend declarations.
  3860. Decl *
  3861. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3862. MultiTemplateParamsArg TemplateParams,
  3863. bool IsExplicitInstantiation,
  3864. RecordDecl *&AnonRecord) {
  3865. Decl *TagD = nullptr;
  3866. TagDecl *Tag = nullptr;
  3867. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3868. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3869. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3870. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3871. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3872. TagD = DS.getRepAsDecl();
  3873. if (!TagD) // We probably had an error
  3874. return nullptr;
  3875. // Note that the above type specs guarantee that the
  3876. // type rep is a Decl, whereas in many of the others
  3877. // it's a Type.
  3878. if (isa<TagDecl>(TagD))
  3879. Tag = cast<TagDecl>(TagD);
  3880. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3881. Tag = CTD->getTemplatedDecl();
  3882. }
  3883. if (Tag) {
  3884. handleTagNumbering(Tag, S);
  3885. Tag->setFreeStanding();
  3886. if (Tag->isInvalidDecl())
  3887. return Tag;
  3888. }
  3889. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3890. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3891. // or incomplete types shall not be restrict-qualified."
  3892. if (TypeQuals & DeclSpec::TQ_restrict)
  3893. Diag(DS.getRestrictSpecLoc(),
  3894. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3895. << DS.getSourceRange();
  3896. }
  3897. if (DS.isInlineSpecified())
  3898. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3899. << getLangOpts().CPlusPlus17;
  3900. if (DS.hasConstexprSpecifier()) {
  3901. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3902. // and definitions of functions and variables.
  3903. // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
  3904. // the declaration of a function or function template
  3905. if (Tag)
  3906. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3907. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
  3908. << DS.getConstexprSpecifier();
  3909. else
  3910. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
  3911. << DS.getConstexprSpecifier();
  3912. // Don't emit warnings after this error.
  3913. return TagD;
  3914. }
  3915. DiagnoseFunctionSpecifiers(DS);
  3916. if (DS.isFriendSpecified()) {
  3917. // If we're dealing with a decl but not a TagDecl, assume that
  3918. // whatever routines created it handled the friendship aspect.
  3919. if (TagD && !Tag)
  3920. return nullptr;
  3921. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3922. }
  3923. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3924. bool IsExplicitSpecialization =
  3925. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3926. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3927. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3928. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3929. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3930. // nested-name-specifier unless it is an explicit instantiation
  3931. // or an explicit specialization.
  3932. //
  3933. // FIXME: We allow class template partial specializations here too, per the
  3934. // obvious intent of DR1819.
  3935. //
  3936. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3937. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3938. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3939. return nullptr;
  3940. }
  3941. // Track whether this decl-specifier declares anything.
  3942. bool DeclaresAnything = true;
  3943. // Handle anonymous struct definitions.
  3944. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3945. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3946. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3947. if (getLangOpts().CPlusPlus ||
  3948. Record->getDeclContext()->isRecord()) {
  3949. // If CurContext is a DeclContext that can contain statements,
  3950. // RecursiveASTVisitor won't visit the decls that
  3951. // BuildAnonymousStructOrUnion() will put into CurContext.
  3952. // Also store them here so that they can be part of the
  3953. // DeclStmt that gets created in this case.
  3954. // FIXME: Also return the IndirectFieldDecls created by
  3955. // BuildAnonymousStructOr union, for the same reason?
  3956. if (CurContext->isFunctionOrMethod())
  3957. AnonRecord = Record;
  3958. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3959. Context.getPrintingPolicy());
  3960. }
  3961. DeclaresAnything = false;
  3962. }
  3963. }
  3964. // C11 6.7.2.1p2:
  3965. // A struct-declaration that does not declare an anonymous structure or
  3966. // anonymous union shall contain a struct-declarator-list.
  3967. //
  3968. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3969. // did not permit a struct-declaration without a struct-declarator-list.
  3970. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3971. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3972. // Check for Microsoft C extension: anonymous struct/union member.
  3973. // Handle 2 kinds of anonymous struct/union:
  3974. // struct STRUCT;
  3975. // union UNION;
  3976. // and
  3977. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3978. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3979. if ((Tag && Tag->getDeclName()) ||
  3980. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3981. RecordDecl *Record = nullptr;
  3982. if (Tag)
  3983. Record = dyn_cast<RecordDecl>(Tag);
  3984. else if (const RecordType *RT =
  3985. DS.getRepAsType().get()->getAsStructureType())
  3986. Record = RT->getDecl();
  3987. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3988. Record = UT->getDecl();
  3989. if (Record && getLangOpts().MicrosoftExt) {
  3990. Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
  3991. << Record->isUnion() << DS.getSourceRange();
  3992. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3993. }
  3994. DeclaresAnything = false;
  3995. }
  3996. }
  3997. // Skip all the checks below if we have a type error.
  3998. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3999. (TagD && TagD->isInvalidDecl()))
  4000. return TagD;
  4001. if (getLangOpts().CPlusPlus &&
  4002. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  4003. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  4004. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  4005. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  4006. DeclaresAnything = false;
  4007. if (!DS.isMissingDeclaratorOk()) {
  4008. // Customize diagnostic for a typedef missing a name.
  4009. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  4010. Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
  4011. << DS.getSourceRange();
  4012. else
  4013. DeclaresAnything = false;
  4014. }
  4015. if (DS.isModulePrivateSpecified() &&
  4016. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  4017. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  4018. << Tag->getTagKind()
  4019. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  4020. ActOnDocumentableDecl(TagD);
  4021. // C 6.7/2:
  4022. // A declaration [...] shall declare at least a declarator [...], a tag,
  4023. // or the members of an enumeration.
  4024. // C++ [dcl.dcl]p3:
  4025. // [If there are no declarators], and except for the declaration of an
  4026. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4027. // names into the program, or shall redeclare a name introduced by a
  4028. // previous declaration.
  4029. if (!DeclaresAnything) {
  4030. // In C, we allow this as a (popular) extension / bug. Don't bother
  4031. // producing further diagnostics for redundant qualifiers after this.
  4032. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  4033. return TagD;
  4034. }
  4035. // C++ [dcl.stc]p1:
  4036. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  4037. // init-declarator-list of the declaration shall not be empty.
  4038. // C++ [dcl.fct.spec]p1:
  4039. // If a cv-qualifier appears in a decl-specifier-seq, the
  4040. // init-declarator-list of the declaration shall not be empty.
  4041. //
  4042. // Spurious qualifiers here appear to be valid in C.
  4043. unsigned DiagID = diag::warn_standalone_specifier;
  4044. if (getLangOpts().CPlusPlus)
  4045. DiagID = diag::ext_standalone_specifier;
  4046. // Note that a linkage-specification sets a storage class, but
  4047. // 'extern "C" struct foo;' is actually valid and not theoretically
  4048. // useless.
  4049. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  4050. if (SCS == DeclSpec::SCS_mutable)
  4051. // Since mutable is not a viable storage class specifier in C, there is
  4052. // no reason to treat it as an extension. Instead, diagnose as an error.
  4053. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  4054. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  4055. Diag(DS.getStorageClassSpecLoc(), DiagID)
  4056. << DeclSpec::getSpecifierName(SCS);
  4057. }
  4058. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  4059. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  4060. << DeclSpec::getSpecifierName(TSCS);
  4061. if (DS.getTypeQualifiers()) {
  4062. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4063. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  4064. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4065. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  4066. // Restrict is covered above.
  4067. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4068. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  4069. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4070. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  4071. }
  4072. // Warn about ignored type attributes, for example:
  4073. // __attribute__((aligned)) struct A;
  4074. // Attributes should be placed after tag to apply to type declaration.
  4075. if (!DS.getAttributes().empty()) {
  4076. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  4077. if (TypeSpecType == DeclSpec::TST_class ||
  4078. TypeSpecType == DeclSpec::TST_struct ||
  4079. TypeSpecType == DeclSpec::TST_interface ||
  4080. TypeSpecType == DeclSpec::TST_union ||
  4081. TypeSpecType == DeclSpec::TST_enum) {
  4082. for (const ParsedAttr &AL : DS.getAttributes())
  4083. Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
  4084. << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
  4085. }
  4086. }
  4087. return TagD;
  4088. }
  4089. /// We are trying to inject an anonymous member into the given scope;
  4090. /// check if there's an existing declaration that can't be overloaded.
  4091. ///
  4092. /// \return true if this is a forbidden redeclaration
  4093. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  4094. Scope *S,
  4095. DeclContext *Owner,
  4096. DeclarationName Name,
  4097. SourceLocation NameLoc,
  4098. bool IsUnion) {
  4099. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  4100. Sema::ForVisibleRedeclaration);
  4101. if (!SemaRef.LookupName(R, S)) return false;
  4102. // Pick a representative declaration.
  4103. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  4104. assert(PrevDecl && "Expected a non-null Decl");
  4105. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  4106. return false;
  4107. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  4108. << IsUnion << Name;
  4109. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  4110. return true;
  4111. }
  4112. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  4113. /// anonymous struct or union AnonRecord into the owning context Owner
  4114. /// and scope S. This routine will be invoked just after we realize
  4115. /// that an unnamed union or struct is actually an anonymous union or
  4116. /// struct, e.g.,
  4117. ///
  4118. /// @code
  4119. /// union {
  4120. /// int i;
  4121. /// float f;
  4122. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  4123. /// // f into the surrounding scope.x
  4124. /// @endcode
  4125. ///
  4126. /// This routine is recursive, injecting the names of nested anonymous
  4127. /// structs/unions into the owning context and scope as well.
  4128. static bool
  4129. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  4130. RecordDecl *AnonRecord, AccessSpecifier AS,
  4131. SmallVectorImpl<NamedDecl *> &Chaining) {
  4132. bool Invalid = false;
  4133. // Look every FieldDecl and IndirectFieldDecl with a name.
  4134. for (auto *D : AnonRecord->decls()) {
  4135. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  4136. cast<NamedDecl>(D)->getDeclName()) {
  4137. ValueDecl *VD = cast<ValueDecl>(D);
  4138. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  4139. VD->getLocation(),
  4140. AnonRecord->isUnion())) {
  4141. // C++ [class.union]p2:
  4142. // The names of the members of an anonymous union shall be
  4143. // distinct from the names of any other entity in the
  4144. // scope in which the anonymous union is declared.
  4145. Invalid = true;
  4146. } else {
  4147. // C++ [class.union]p2:
  4148. // For the purpose of name lookup, after the anonymous union
  4149. // definition, the members of the anonymous union are
  4150. // considered to have been defined in the scope in which the
  4151. // anonymous union is declared.
  4152. unsigned OldChainingSize = Chaining.size();
  4153. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  4154. Chaining.append(IF->chain_begin(), IF->chain_end());
  4155. else
  4156. Chaining.push_back(VD);
  4157. assert(Chaining.size() >= 2);
  4158. NamedDecl **NamedChain =
  4159. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  4160. for (unsigned i = 0; i < Chaining.size(); i++)
  4161. NamedChain[i] = Chaining[i];
  4162. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  4163. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  4164. VD->getType(), {NamedChain, Chaining.size()});
  4165. for (const auto *Attr : VD->attrs())
  4166. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  4167. IndirectField->setAccess(AS);
  4168. IndirectField->setImplicit();
  4169. SemaRef.PushOnScopeChains(IndirectField, S);
  4170. // That includes picking up the appropriate access specifier.
  4171. if (AS != AS_none) IndirectField->setAccess(AS);
  4172. Chaining.resize(OldChainingSize);
  4173. }
  4174. }
  4175. }
  4176. return Invalid;
  4177. }
  4178. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  4179. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  4180. /// illegal input values are mapped to SC_None.
  4181. static StorageClass
  4182. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  4183. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  4184. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  4185. "Parser allowed 'typedef' as storage class VarDecl.");
  4186. switch (StorageClassSpec) {
  4187. case DeclSpec::SCS_unspecified: return SC_None;
  4188. case DeclSpec::SCS_extern:
  4189. if (DS.isExternInLinkageSpec())
  4190. return SC_None;
  4191. return SC_Extern;
  4192. case DeclSpec::SCS_static: return SC_Static;
  4193. case DeclSpec::SCS_auto: return SC_Auto;
  4194. case DeclSpec::SCS_register: return SC_Register;
  4195. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4196. // Illegal SCSs map to None: error reporting is up to the caller.
  4197. case DeclSpec::SCS_mutable: // Fall through.
  4198. case DeclSpec::SCS_typedef: return SC_None;
  4199. }
  4200. llvm_unreachable("unknown storage class specifier");
  4201. }
  4202. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  4203. assert(Record->hasInClassInitializer());
  4204. for (const auto *I : Record->decls()) {
  4205. const auto *FD = dyn_cast<FieldDecl>(I);
  4206. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  4207. FD = IFD->getAnonField();
  4208. if (FD && FD->hasInClassInitializer())
  4209. return FD->getLocation();
  4210. }
  4211. llvm_unreachable("couldn't find in-class initializer");
  4212. }
  4213. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4214. SourceLocation DefaultInitLoc) {
  4215. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4216. return;
  4217. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  4218. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  4219. }
  4220. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4221. CXXRecordDecl *AnonUnion) {
  4222. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4223. return;
  4224. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  4225. }
  4226. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  4227. /// anonymous structure or union. Anonymous unions are a C++ feature
  4228. /// (C++ [class.union]) and a C11 feature; anonymous structures
  4229. /// are a C11 feature and GNU C++ extension.
  4230. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  4231. AccessSpecifier AS,
  4232. RecordDecl *Record,
  4233. const PrintingPolicy &Policy) {
  4234. DeclContext *Owner = Record->getDeclContext();
  4235. // Diagnose whether this anonymous struct/union is an extension.
  4236. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  4237. Diag(Record->getLocation(), diag::ext_anonymous_union);
  4238. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  4239. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  4240. else if (!Record->isUnion() && !getLangOpts().C11)
  4241. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4242. // C and C++ require different kinds of checks for anonymous
  4243. // structs/unions.
  4244. bool Invalid = false;
  4245. if (getLangOpts().CPlusPlus) {
  4246. const char *PrevSpec = nullptr;
  4247. if (Record->isUnion()) {
  4248. // C++ [class.union]p6:
  4249. // C++17 [class.union.anon]p2:
  4250. // Anonymous unions declared in a named namespace or in the
  4251. // global namespace shall be declared static.
  4252. unsigned DiagID;
  4253. DeclContext *OwnerScope = Owner->getRedeclContext();
  4254. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4255. (OwnerScope->isTranslationUnit() ||
  4256. (OwnerScope->isNamespace() &&
  4257. !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
  4258. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4259. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4260. // Recover by adding 'static'.
  4261. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4262. PrevSpec, DiagID, Policy);
  4263. }
  4264. // C++ [class.union]p6:
  4265. // A storage class is not allowed in a declaration of an
  4266. // anonymous union in a class scope.
  4267. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4268. isa<RecordDecl>(Owner)) {
  4269. Diag(DS.getStorageClassSpecLoc(),
  4270. diag::err_anonymous_union_with_storage_spec)
  4271. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4272. // Recover by removing the storage specifier.
  4273. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4274. SourceLocation(),
  4275. PrevSpec, DiagID, Context.getPrintingPolicy());
  4276. }
  4277. }
  4278. // Ignore const/volatile/restrict qualifiers.
  4279. if (DS.getTypeQualifiers()) {
  4280. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4281. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4282. << Record->isUnion() << "const"
  4283. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4284. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4285. Diag(DS.getVolatileSpecLoc(),
  4286. diag::ext_anonymous_struct_union_qualified)
  4287. << Record->isUnion() << "volatile"
  4288. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4289. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4290. Diag(DS.getRestrictSpecLoc(),
  4291. diag::ext_anonymous_struct_union_qualified)
  4292. << Record->isUnion() << "restrict"
  4293. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4294. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4295. Diag(DS.getAtomicSpecLoc(),
  4296. diag::ext_anonymous_struct_union_qualified)
  4297. << Record->isUnion() << "_Atomic"
  4298. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4299. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4300. Diag(DS.getUnalignedSpecLoc(),
  4301. diag::ext_anonymous_struct_union_qualified)
  4302. << Record->isUnion() << "__unaligned"
  4303. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4304. DS.ClearTypeQualifiers();
  4305. }
  4306. // C++ [class.union]p2:
  4307. // The member-specification of an anonymous union shall only
  4308. // define non-static data members. [Note: nested types and
  4309. // functions cannot be declared within an anonymous union. ]
  4310. for (auto *Mem : Record->decls()) {
  4311. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4312. // C++ [class.union]p3:
  4313. // An anonymous union shall not have private or protected
  4314. // members (clause 11).
  4315. assert(FD->getAccess() != AS_none);
  4316. if (FD->getAccess() != AS_public) {
  4317. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4318. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4319. Invalid = true;
  4320. }
  4321. // C++ [class.union]p1
  4322. // An object of a class with a non-trivial constructor, a non-trivial
  4323. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4324. // assignment operator cannot be a member of a union, nor can an
  4325. // array of such objects.
  4326. if (CheckNontrivialField(FD))
  4327. Invalid = true;
  4328. } else if (Mem->isImplicit()) {
  4329. // Any implicit members are fine.
  4330. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4331. // This is a type that showed up in an
  4332. // elaborated-type-specifier inside the anonymous struct or
  4333. // union, but which actually declares a type outside of the
  4334. // anonymous struct or union. It's okay.
  4335. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4336. if (!MemRecord->isAnonymousStructOrUnion() &&
  4337. MemRecord->getDeclName()) {
  4338. // Visual C++ allows type definition in anonymous struct or union.
  4339. if (getLangOpts().MicrosoftExt)
  4340. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4341. << Record->isUnion();
  4342. else {
  4343. // This is a nested type declaration.
  4344. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4345. << Record->isUnion();
  4346. Invalid = true;
  4347. }
  4348. } else {
  4349. // This is an anonymous type definition within another anonymous type.
  4350. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4351. // not part of standard C++.
  4352. Diag(MemRecord->getLocation(),
  4353. diag::ext_anonymous_record_with_anonymous_type)
  4354. << Record->isUnion();
  4355. }
  4356. } else if (isa<AccessSpecDecl>(Mem)) {
  4357. // Any access specifier is fine.
  4358. } else if (isa<StaticAssertDecl>(Mem)) {
  4359. // In C++1z, static_assert declarations are also fine.
  4360. } else {
  4361. // We have something that isn't a non-static data
  4362. // member. Complain about it.
  4363. unsigned DK = diag::err_anonymous_record_bad_member;
  4364. if (isa<TypeDecl>(Mem))
  4365. DK = diag::err_anonymous_record_with_type;
  4366. else if (isa<FunctionDecl>(Mem))
  4367. DK = diag::err_anonymous_record_with_function;
  4368. else if (isa<VarDecl>(Mem))
  4369. DK = diag::err_anonymous_record_with_static;
  4370. // Visual C++ allows type definition in anonymous struct or union.
  4371. if (getLangOpts().MicrosoftExt &&
  4372. DK == diag::err_anonymous_record_with_type)
  4373. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  4374. << Record->isUnion();
  4375. else {
  4376. Diag(Mem->getLocation(), DK) << Record->isUnion();
  4377. Invalid = true;
  4378. }
  4379. }
  4380. }
  4381. // C++11 [class.union]p8 (DR1460):
  4382. // At most one variant member of a union may have a
  4383. // brace-or-equal-initializer.
  4384. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  4385. Owner->isRecord())
  4386. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  4387. cast<CXXRecordDecl>(Record));
  4388. }
  4389. if (!Record->isUnion() && !Owner->isRecord()) {
  4390. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4391. << getLangOpts().CPlusPlus;
  4392. Invalid = true;
  4393. }
  4394. // C++ [dcl.dcl]p3:
  4395. // [If there are no declarators], and except for the declaration of an
  4396. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4397. // names into the program
  4398. // C++ [class.mem]p2:
  4399. // each such member-declaration shall either declare at least one member
  4400. // name of the class or declare at least one unnamed bit-field
  4401. //
  4402. // For C this is an error even for a named struct, and is diagnosed elsewhere.
  4403. if (getLangOpts().CPlusPlus && Record->field_empty())
  4404. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  4405. // Mock up a declarator.
  4406. Declarator Dc(DS, DeclaratorContext::MemberContext);
  4407. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4408. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4409. // Create a declaration for this anonymous struct/union.
  4410. NamedDecl *Anon = nullptr;
  4411. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4412. Anon = FieldDecl::Create(
  4413. Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
  4414. /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
  4415. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4416. /*InitStyle=*/ICIS_NoInit);
  4417. Anon->setAccess(AS);
  4418. if (getLangOpts().CPlusPlus)
  4419. FieldCollector->Add(cast<FieldDecl>(Anon));
  4420. } else {
  4421. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4422. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4423. if (SCSpec == DeclSpec::SCS_mutable) {
  4424. // mutable can only appear on non-static class members, so it's always
  4425. // an error here
  4426. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4427. Invalid = true;
  4428. SC = SC_None;
  4429. }
  4430. Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
  4431. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4432. Context.getTypeDeclType(Record), TInfo, SC);
  4433. // Default-initialize the implicit variable. This initialization will be
  4434. // trivial in almost all cases, except if a union member has an in-class
  4435. // initializer:
  4436. // union { int n = 0; };
  4437. ActOnUninitializedDecl(Anon);
  4438. }
  4439. Anon->setImplicit();
  4440. // Mark this as an anonymous struct/union type.
  4441. Record->setAnonymousStructOrUnion(true);
  4442. // Add the anonymous struct/union object to the current
  4443. // context. We'll be referencing this object when we refer to one of
  4444. // its members.
  4445. Owner->addDecl(Anon);
  4446. // Inject the members of the anonymous struct/union into the owning
  4447. // context and into the identifier resolver chain for name lookup
  4448. // purposes.
  4449. SmallVector<NamedDecl*, 2> Chain;
  4450. Chain.push_back(Anon);
  4451. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4452. Invalid = true;
  4453. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4454. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4455. Decl *ManglingContextDecl;
  4456. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  4457. NewVD->getDeclContext(), ManglingContextDecl)) {
  4458. Context.setManglingNumber(
  4459. NewVD, MCtx->getManglingNumber(
  4460. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4461. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4462. }
  4463. }
  4464. }
  4465. if (Invalid)
  4466. Anon->setInvalidDecl();
  4467. return Anon;
  4468. }
  4469. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4470. /// Microsoft C anonymous structure.
  4471. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4472. /// Example:
  4473. ///
  4474. /// struct A { int a; };
  4475. /// struct B { struct A; int b; };
  4476. ///
  4477. /// void foo() {
  4478. /// B var;
  4479. /// var.a = 3;
  4480. /// }
  4481. ///
  4482. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4483. RecordDecl *Record) {
  4484. assert(Record && "expected a record!");
  4485. // Mock up a declarator.
  4486. Declarator Dc(DS, DeclaratorContext::TypeNameContext);
  4487. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4488. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4489. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4490. QualType RecTy = Context.getTypeDeclType(Record);
  4491. // Create a declaration for this anonymous struct.
  4492. NamedDecl *Anon =
  4493. FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
  4494. /*IdentifierInfo=*/nullptr, RecTy, TInfo,
  4495. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4496. /*InitStyle=*/ICIS_NoInit);
  4497. Anon->setImplicit();
  4498. // Add the anonymous struct object to the current context.
  4499. CurContext->addDecl(Anon);
  4500. // Inject the members of the anonymous struct into the current
  4501. // context and into the identifier resolver chain for name lookup
  4502. // purposes.
  4503. SmallVector<NamedDecl*, 2> Chain;
  4504. Chain.push_back(Anon);
  4505. RecordDecl *RecordDef = Record->getDefinition();
  4506. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4507. diag::err_field_incomplete) ||
  4508. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4509. AS_none, Chain)) {
  4510. Anon->setInvalidDecl();
  4511. ParentDecl->setInvalidDecl();
  4512. }
  4513. return Anon;
  4514. }
  4515. /// GetNameForDeclarator - Determine the full declaration name for the
  4516. /// given Declarator.
  4517. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4518. return GetNameFromUnqualifiedId(D.getName());
  4519. }
  4520. /// Retrieves the declaration name from a parsed unqualified-id.
  4521. DeclarationNameInfo
  4522. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4523. DeclarationNameInfo NameInfo;
  4524. NameInfo.setLoc(Name.StartLocation);
  4525. switch (Name.getKind()) {
  4526. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  4527. case UnqualifiedIdKind::IK_Identifier:
  4528. NameInfo.setName(Name.Identifier);
  4529. return NameInfo;
  4530. case UnqualifiedIdKind::IK_DeductionGuideName: {
  4531. // C++ [temp.deduct.guide]p3:
  4532. // The simple-template-id shall name a class template specialization.
  4533. // The template-name shall be the same identifier as the template-name
  4534. // of the simple-template-id.
  4535. // These together intend to imply that the template-name shall name a
  4536. // class template.
  4537. // FIXME: template<typename T> struct X {};
  4538. // template<typename T> using Y = X<T>;
  4539. // Y(int) -> Y<int>;
  4540. // satisfies these rules but does not name a class template.
  4541. TemplateName TN = Name.TemplateName.get().get();
  4542. auto *Template = TN.getAsTemplateDecl();
  4543. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4544. Diag(Name.StartLocation,
  4545. diag::err_deduction_guide_name_not_class_template)
  4546. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4547. if (Template)
  4548. Diag(Template->getLocation(), diag::note_template_decl_here);
  4549. return DeclarationNameInfo();
  4550. }
  4551. NameInfo.setName(
  4552. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4553. return NameInfo;
  4554. }
  4555. case UnqualifiedIdKind::IK_OperatorFunctionId:
  4556. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4557. Name.OperatorFunctionId.Operator));
  4558. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4559. = Name.OperatorFunctionId.SymbolLocations[0];
  4560. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4561. = Name.EndLocation.getRawEncoding();
  4562. return NameInfo;
  4563. case UnqualifiedIdKind::IK_LiteralOperatorId:
  4564. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4565. Name.Identifier));
  4566. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4567. return NameInfo;
  4568. case UnqualifiedIdKind::IK_ConversionFunctionId: {
  4569. TypeSourceInfo *TInfo;
  4570. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4571. if (Ty.isNull())
  4572. return DeclarationNameInfo();
  4573. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4574. Context.getCanonicalType(Ty)));
  4575. NameInfo.setNamedTypeInfo(TInfo);
  4576. return NameInfo;
  4577. }
  4578. case UnqualifiedIdKind::IK_ConstructorName: {
  4579. TypeSourceInfo *TInfo;
  4580. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4581. if (Ty.isNull())
  4582. return DeclarationNameInfo();
  4583. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4584. Context.getCanonicalType(Ty)));
  4585. NameInfo.setNamedTypeInfo(TInfo);
  4586. return NameInfo;
  4587. }
  4588. case UnqualifiedIdKind::IK_ConstructorTemplateId: {
  4589. // In well-formed code, we can only have a constructor
  4590. // template-id that refers to the current context, so go there
  4591. // to find the actual type being constructed.
  4592. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4593. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4594. return DeclarationNameInfo();
  4595. // Determine the type of the class being constructed.
  4596. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4597. // FIXME: Check two things: that the template-id names the same type as
  4598. // CurClassType, and that the template-id does not occur when the name
  4599. // was qualified.
  4600. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4601. Context.getCanonicalType(CurClassType)));
  4602. // FIXME: should we retrieve TypeSourceInfo?
  4603. NameInfo.setNamedTypeInfo(nullptr);
  4604. return NameInfo;
  4605. }
  4606. case UnqualifiedIdKind::IK_DestructorName: {
  4607. TypeSourceInfo *TInfo;
  4608. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4609. if (Ty.isNull())
  4610. return DeclarationNameInfo();
  4611. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4612. Context.getCanonicalType(Ty)));
  4613. NameInfo.setNamedTypeInfo(TInfo);
  4614. return NameInfo;
  4615. }
  4616. case UnqualifiedIdKind::IK_TemplateId: {
  4617. TemplateName TName = Name.TemplateId->Template.get();
  4618. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4619. return Context.getNameForTemplate(TName, TNameLoc);
  4620. }
  4621. } // switch (Name.getKind())
  4622. llvm_unreachable("Unknown name kind");
  4623. }
  4624. static QualType getCoreType(QualType Ty) {
  4625. do {
  4626. if (Ty->isPointerType() || Ty->isReferenceType())
  4627. Ty = Ty->getPointeeType();
  4628. else if (Ty->isArrayType())
  4629. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4630. else
  4631. return Ty.withoutLocalFastQualifiers();
  4632. } while (true);
  4633. }
  4634. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4635. /// and Definition have "nearly" matching parameters. This heuristic is
  4636. /// used to improve diagnostics in the case where an out-of-line function
  4637. /// definition doesn't match any declaration within the class or namespace.
  4638. /// Also sets Params to the list of indices to the parameters that differ
  4639. /// between the declaration and the definition. If hasSimilarParameters
  4640. /// returns true and Params is empty, then all of the parameters match.
  4641. static bool hasSimilarParameters(ASTContext &Context,
  4642. FunctionDecl *Declaration,
  4643. FunctionDecl *Definition,
  4644. SmallVectorImpl<unsigned> &Params) {
  4645. Params.clear();
  4646. if (Declaration->param_size() != Definition->param_size())
  4647. return false;
  4648. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4649. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4650. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4651. // The parameter types are identical
  4652. if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
  4653. continue;
  4654. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4655. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4656. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4657. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4658. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4659. (DeclTyName && DeclTyName == DefTyName))
  4660. Params.push_back(Idx);
  4661. else // The two parameters aren't even close
  4662. return false;
  4663. }
  4664. return true;
  4665. }
  4666. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4667. /// declarator needs to be rebuilt in the current instantiation.
  4668. /// Any bits of declarator which appear before the name are valid for
  4669. /// consideration here. That's specifically the type in the decl spec
  4670. /// and the base type in any member-pointer chunks.
  4671. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4672. DeclarationName Name) {
  4673. // The types we specifically need to rebuild are:
  4674. // - typenames, typeofs, and decltypes
  4675. // - types which will become injected class names
  4676. // Of course, we also need to rebuild any type referencing such a
  4677. // type. It's safest to just say "dependent", but we call out a
  4678. // few cases here.
  4679. DeclSpec &DS = D.getMutableDeclSpec();
  4680. switch (DS.getTypeSpecType()) {
  4681. case DeclSpec::TST_typename:
  4682. case DeclSpec::TST_typeofType:
  4683. case DeclSpec::TST_underlyingType:
  4684. case DeclSpec::TST_atomic: {
  4685. // Grab the type from the parser.
  4686. TypeSourceInfo *TSI = nullptr;
  4687. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4688. if (T.isNull() || !T->isDependentType()) break;
  4689. // Make sure there's a type source info. This isn't really much
  4690. // of a waste; most dependent types should have type source info
  4691. // attached already.
  4692. if (!TSI)
  4693. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4694. // Rebuild the type in the current instantiation.
  4695. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4696. if (!TSI) return true;
  4697. // Store the new type back in the decl spec.
  4698. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4699. DS.UpdateTypeRep(LocType);
  4700. break;
  4701. }
  4702. case DeclSpec::TST_decltype:
  4703. case DeclSpec::TST_typeofExpr: {
  4704. Expr *E = DS.getRepAsExpr();
  4705. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4706. if (Result.isInvalid()) return true;
  4707. DS.UpdateExprRep(Result.get());
  4708. break;
  4709. }
  4710. default:
  4711. // Nothing to do for these decl specs.
  4712. break;
  4713. }
  4714. // It doesn't matter what order we do this in.
  4715. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4716. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4717. // The only type information in the declarator which can come
  4718. // before the declaration name is the base type of a member
  4719. // pointer.
  4720. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4721. continue;
  4722. // Rebuild the scope specifier in-place.
  4723. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4724. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4725. return true;
  4726. }
  4727. return false;
  4728. }
  4729. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4730. D.setFunctionDefinitionKind(FDK_Declaration);
  4731. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4732. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4733. Dcl && Dcl->getDeclContext()->isFileContext())
  4734. Dcl->setTopLevelDeclInObjCContainer();
  4735. if (getLangOpts().OpenCL)
  4736. setCurrentOpenCLExtensionForDecl(Dcl);
  4737. return Dcl;
  4738. }
  4739. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4740. /// If T is the name of a class, then each of the following shall have a
  4741. /// name different from T:
  4742. /// - every static data member of class T;
  4743. /// - every member function of class T
  4744. /// - every member of class T that is itself a type;
  4745. /// \returns true if the declaration name violates these rules.
  4746. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4747. DeclarationNameInfo NameInfo) {
  4748. DeclarationName Name = NameInfo.getName();
  4749. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4750. while (Record && Record->isAnonymousStructOrUnion())
  4751. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4752. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4753. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4754. return true;
  4755. }
  4756. return false;
  4757. }
  4758. /// Diagnose a declaration whose declarator-id has the given
  4759. /// nested-name-specifier.
  4760. ///
  4761. /// \param SS The nested-name-specifier of the declarator-id.
  4762. ///
  4763. /// \param DC The declaration context to which the nested-name-specifier
  4764. /// resolves.
  4765. ///
  4766. /// \param Name The name of the entity being declared.
  4767. ///
  4768. /// \param Loc The location of the name of the entity being declared.
  4769. ///
  4770. /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
  4771. /// we're declaring an explicit / partial specialization / instantiation.
  4772. ///
  4773. /// \returns true if we cannot safely recover from this error, false otherwise.
  4774. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4775. DeclarationName Name,
  4776. SourceLocation Loc, bool IsTemplateId) {
  4777. DeclContext *Cur = CurContext;
  4778. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4779. Cur = Cur->getParent();
  4780. // If the user provided a superfluous scope specifier that refers back to the
  4781. // class in which the entity is already declared, diagnose and ignore it.
  4782. //
  4783. // class X {
  4784. // void X::f();
  4785. // };
  4786. //
  4787. // Note, it was once ill-formed to give redundant qualification in all
  4788. // contexts, but that rule was removed by DR482.
  4789. if (Cur->Equals(DC)) {
  4790. if (Cur->isRecord()) {
  4791. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4792. : diag::err_member_extra_qualification)
  4793. << Name << FixItHint::CreateRemoval(SS.getRange());
  4794. SS.clear();
  4795. } else {
  4796. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4797. }
  4798. return false;
  4799. }
  4800. // Check whether the qualifying scope encloses the scope of the original
  4801. // declaration. For a template-id, we perform the checks in
  4802. // CheckTemplateSpecializationScope.
  4803. if (!Cur->Encloses(DC) && !IsTemplateId) {
  4804. if (Cur->isRecord())
  4805. Diag(Loc, diag::err_member_qualification)
  4806. << Name << SS.getRange();
  4807. else if (isa<TranslationUnitDecl>(DC))
  4808. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4809. << Name << SS.getRange();
  4810. else if (isa<FunctionDecl>(Cur))
  4811. Diag(Loc, diag::err_invalid_declarator_in_function)
  4812. << Name << SS.getRange();
  4813. else if (isa<BlockDecl>(Cur))
  4814. Diag(Loc, diag::err_invalid_declarator_in_block)
  4815. << Name << SS.getRange();
  4816. else
  4817. Diag(Loc, diag::err_invalid_declarator_scope)
  4818. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4819. return true;
  4820. }
  4821. if (Cur->isRecord()) {
  4822. // Cannot qualify members within a class.
  4823. Diag(Loc, diag::err_member_qualification)
  4824. << Name << SS.getRange();
  4825. SS.clear();
  4826. // C++ constructors and destructors with incorrect scopes can break
  4827. // our AST invariants by having the wrong underlying types. If
  4828. // that's the case, then drop this declaration entirely.
  4829. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4830. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4831. !Context.hasSameType(Name.getCXXNameType(),
  4832. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4833. return true;
  4834. return false;
  4835. }
  4836. // C++11 [dcl.meaning]p1:
  4837. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4838. // not begin with a decltype-specifer"
  4839. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4840. while (SpecLoc.getPrefix())
  4841. SpecLoc = SpecLoc.getPrefix();
  4842. if (dyn_cast_or_null<DecltypeType>(
  4843. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4844. Diag(Loc, diag::err_decltype_in_declarator)
  4845. << SpecLoc.getTypeLoc().getSourceRange();
  4846. return false;
  4847. }
  4848. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4849. MultiTemplateParamsArg TemplateParamLists) {
  4850. // TODO: consider using NameInfo for diagnostic.
  4851. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4852. DeclarationName Name = NameInfo.getName();
  4853. // All of these full declarators require an identifier. If it doesn't have
  4854. // one, the ParsedFreeStandingDeclSpec action should be used.
  4855. if (D.isDecompositionDeclarator()) {
  4856. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4857. } else if (!Name) {
  4858. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4859. Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
  4860. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4861. return nullptr;
  4862. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4863. return nullptr;
  4864. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4865. // we find one that is.
  4866. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4867. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4868. S = S->getParent();
  4869. DeclContext *DC = CurContext;
  4870. if (D.getCXXScopeSpec().isInvalid())
  4871. D.setInvalidType();
  4872. else if (D.getCXXScopeSpec().isSet()) {
  4873. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4874. UPPC_DeclarationQualifier))
  4875. return nullptr;
  4876. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4877. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4878. if (!DC || isa<EnumDecl>(DC)) {
  4879. // If we could not compute the declaration context, it's because the
  4880. // declaration context is dependent but does not refer to a class,
  4881. // class template, or class template partial specialization. Complain
  4882. // and return early, to avoid the coming semantic disaster.
  4883. Diag(D.getIdentifierLoc(),
  4884. diag::err_template_qualified_declarator_no_match)
  4885. << D.getCXXScopeSpec().getScopeRep()
  4886. << D.getCXXScopeSpec().getRange();
  4887. return nullptr;
  4888. }
  4889. bool IsDependentContext = DC->isDependentContext();
  4890. if (!IsDependentContext &&
  4891. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4892. return nullptr;
  4893. // If a class is incomplete, do not parse entities inside it.
  4894. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4895. Diag(D.getIdentifierLoc(),
  4896. diag::err_member_def_undefined_record)
  4897. << Name << DC << D.getCXXScopeSpec().getRange();
  4898. return nullptr;
  4899. }
  4900. if (!D.getDeclSpec().isFriendSpecified()) {
  4901. if (diagnoseQualifiedDeclaration(
  4902. D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
  4903. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
  4904. if (DC->isRecord())
  4905. return nullptr;
  4906. D.setInvalidType();
  4907. }
  4908. }
  4909. // Check whether we need to rebuild the type of the given
  4910. // declaration in the current instantiation.
  4911. if (EnteringContext && IsDependentContext &&
  4912. TemplateParamLists.size() != 0) {
  4913. ContextRAII SavedContext(*this, DC);
  4914. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4915. D.setInvalidType();
  4916. }
  4917. }
  4918. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4919. QualType R = TInfo->getType();
  4920. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4921. UPPC_DeclarationType))
  4922. D.setInvalidType();
  4923. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4924. forRedeclarationInCurContext());
  4925. // See if this is a redefinition of a variable in the same scope.
  4926. if (!D.getCXXScopeSpec().isSet()) {
  4927. bool IsLinkageLookup = false;
  4928. bool CreateBuiltins = false;
  4929. // If the declaration we're planning to build will be a function
  4930. // or object with linkage, then look for another declaration with
  4931. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4932. //
  4933. // If the declaration we're planning to build will be declared with
  4934. // external linkage in the translation unit, create any builtin with
  4935. // the same name.
  4936. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4937. /* Do nothing*/;
  4938. else if (CurContext->isFunctionOrMethod() &&
  4939. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4940. R->isFunctionType())) {
  4941. IsLinkageLookup = true;
  4942. CreateBuiltins =
  4943. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4944. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4945. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4946. CreateBuiltins = true;
  4947. if (IsLinkageLookup) {
  4948. Previous.clear(LookupRedeclarationWithLinkage);
  4949. Previous.setRedeclarationKind(ForExternalRedeclaration);
  4950. }
  4951. LookupName(Previous, S, CreateBuiltins);
  4952. } else { // Something like "int foo::x;"
  4953. LookupQualifiedName(Previous, DC);
  4954. // C++ [dcl.meaning]p1:
  4955. // When the declarator-id is qualified, the declaration shall refer to a
  4956. // previously declared member of the class or namespace to which the
  4957. // qualifier refers (or, in the case of a namespace, of an element of the
  4958. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4959. // thereof; [...]
  4960. //
  4961. // Note that we already checked the context above, and that we do not have
  4962. // enough information to make sure that Previous contains the declaration
  4963. // we want to match. For example, given:
  4964. //
  4965. // class X {
  4966. // void f();
  4967. // void f(float);
  4968. // };
  4969. //
  4970. // void X::f(int) { } // ill-formed
  4971. //
  4972. // In this case, Previous will point to the overload set
  4973. // containing the two f's declared in X, but neither of them
  4974. // matches.
  4975. // C++ [dcl.meaning]p1:
  4976. // [...] the member shall not merely have been introduced by a
  4977. // using-declaration in the scope of the class or namespace nominated by
  4978. // the nested-name-specifier of the declarator-id.
  4979. RemoveUsingDecls(Previous);
  4980. }
  4981. if (Previous.isSingleResult() &&
  4982. Previous.getFoundDecl()->isTemplateParameter()) {
  4983. // Maybe we will complain about the shadowed template parameter.
  4984. if (!D.isInvalidType())
  4985. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4986. Previous.getFoundDecl());
  4987. // Just pretend that we didn't see the previous declaration.
  4988. Previous.clear();
  4989. }
  4990. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4991. // Forget that the previous declaration is the injected-class-name.
  4992. Previous.clear();
  4993. // In C++, the previous declaration we find might be a tag type
  4994. // (class or enum). In this case, the new declaration will hide the
  4995. // tag type. Note that this applies to functions, function templates, and
  4996. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  4997. if (Previous.isSingleTagDecl() &&
  4998. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  4999. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  5000. Previous.clear();
  5001. // Check that there are no default arguments other than in the parameters
  5002. // of a function declaration (C++ only).
  5003. if (getLangOpts().CPlusPlus)
  5004. CheckExtraCXXDefaultArguments(D);
  5005. NamedDecl *New;
  5006. bool AddToScope = true;
  5007. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  5008. if (TemplateParamLists.size()) {
  5009. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  5010. return nullptr;
  5011. }
  5012. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  5013. } else if (R->isFunctionType()) {
  5014. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  5015. TemplateParamLists,
  5016. AddToScope);
  5017. } else {
  5018. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  5019. AddToScope);
  5020. }
  5021. if (!New)
  5022. return nullptr;
  5023. // If this has an identifier and is not a function template specialization,
  5024. // add it to the scope stack.
  5025. if (New->getDeclName() && AddToScope)
  5026. PushOnScopeChains(New, S);
  5027. if (isInOpenMPDeclareTargetContext())
  5028. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  5029. return New;
  5030. }
  5031. /// Helper method to turn variable array types into constant array
  5032. /// types in certain situations which would otherwise be errors (for
  5033. /// GCC compatibility).
  5034. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  5035. ASTContext &Context,
  5036. bool &SizeIsNegative,
  5037. llvm::APSInt &Oversized) {
  5038. // This method tries to turn a variable array into a constant
  5039. // array even when the size isn't an ICE. This is necessary
  5040. // for compatibility with code that depends on gcc's buggy
  5041. // constant expression folding, like struct {char x[(int)(char*)2];}
  5042. SizeIsNegative = false;
  5043. Oversized = 0;
  5044. if (T->isDependentType())
  5045. return QualType();
  5046. QualifierCollector Qs;
  5047. const Type *Ty = Qs.strip(T);
  5048. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  5049. QualType Pointee = PTy->getPointeeType();
  5050. QualType FixedType =
  5051. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  5052. Oversized);
  5053. if (FixedType.isNull()) return FixedType;
  5054. FixedType = Context.getPointerType(FixedType);
  5055. return Qs.apply(Context, FixedType);
  5056. }
  5057. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  5058. QualType Inner = PTy->getInnerType();
  5059. QualType FixedType =
  5060. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  5061. Oversized);
  5062. if (FixedType.isNull()) return FixedType;
  5063. FixedType = Context.getParenType(FixedType);
  5064. return Qs.apply(Context, FixedType);
  5065. }
  5066. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  5067. if (!VLATy)
  5068. return QualType();
  5069. // FIXME: We should probably handle this case
  5070. if (VLATy->getElementType()->isVariablyModifiedType())
  5071. return QualType();
  5072. Expr::EvalResult Result;
  5073. if (!VLATy->getSizeExpr() ||
  5074. !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
  5075. return QualType();
  5076. llvm::APSInt Res = Result.Val.getInt();
  5077. // Check whether the array size is negative.
  5078. if (Res.isSigned() && Res.isNegative()) {
  5079. SizeIsNegative = true;
  5080. return QualType();
  5081. }
  5082. // Check whether the array is too large to be addressed.
  5083. unsigned ActiveSizeBits
  5084. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  5085. Res);
  5086. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  5087. Oversized = Res;
  5088. return QualType();
  5089. }
  5090. return Context.getConstantArrayType(
  5091. VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
  5092. }
  5093. static void
  5094. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  5095. SrcTL = SrcTL.getUnqualifiedLoc();
  5096. DstTL = DstTL.getUnqualifiedLoc();
  5097. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  5098. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  5099. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  5100. DstPTL.getPointeeLoc());
  5101. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  5102. return;
  5103. }
  5104. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  5105. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  5106. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  5107. DstPTL.getInnerLoc());
  5108. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  5109. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  5110. return;
  5111. }
  5112. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  5113. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  5114. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  5115. TypeLoc DstElemTL = DstATL.getElementLoc();
  5116. DstElemTL.initializeFullCopy(SrcElemTL);
  5117. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  5118. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  5119. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  5120. }
  5121. /// Helper method to turn variable array types into constant array
  5122. /// types in certain situations which would otherwise be errors (for
  5123. /// GCC compatibility).
  5124. static TypeSourceInfo*
  5125. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  5126. ASTContext &Context,
  5127. bool &SizeIsNegative,
  5128. llvm::APSInt &Oversized) {
  5129. QualType FixedTy
  5130. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  5131. SizeIsNegative, Oversized);
  5132. if (FixedTy.isNull())
  5133. return nullptr;
  5134. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  5135. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  5136. FixedTInfo->getTypeLoc());
  5137. return FixedTInfo;
  5138. }
  5139. /// Register the given locally-scoped extern "C" declaration so
  5140. /// that it can be found later for redeclarations. We include any extern "C"
  5141. /// declaration that is not visible in the translation unit here, not just
  5142. /// function-scope declarations.
  5143. void
  5144. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  5145. if (!getLangOpts().CPlusPlus &&
  5146. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  5147. // Don't need to track declarations in the TU in C.
  5148. return;
  5149. // Note that we have a locally-scoped external with this name.
  5150. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  5151. }
  5152. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  5153. // FIXME: We can have multiple results via __attribute__((overloadable)).
  5154. auto Result = Context.getExternCContextDecl()->lookup(Name);
  5155. return Result.empty() ? nullptr : *Result.begin();
  5156. }
  5157. /// Diagnose function specifiers on a declaration of an identifier that
  5158. /// does not identify a function.
  5159. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  5160. // FIXME: We should probably indicate the identifier in question to avoid
  5161. // confusion for constructs like "virtual int a(), b;"
  5162. if (DS.isVirtualSpecified())
  5163. Diag(DS.getVirtualSpecLoc(),
  5164. diag::err_virtual_non_function);
  5165. if (DS.hasExplicitSpecifier())
  5166. Diag(DS.getExplicitSpecLoc(),
  5167. diag::err_explicit_non_function);
  5168. if (DS.isNoreturnSpecified())
  5169. Diag(DS.getNoreturnSpecLoc(),
  5170. diag::err_noreturn_non_function);
  5171. }
  5172. NamedDecl*
  5173. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  5174. TypeSourceInfo *TInfo, LookupResult &Previous) {
  5175. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  5176. if (D.getCXXScopeSpec().isSet()) {
  5177. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  5178. << D.getCXXScopeSpec().getRange();
  5179. D.setInvalidType();
  5180. // Pretend we didn't see the scope specifier.
  5181. DC = CurContext;
  5182. Previous.clear();
  5183. }
  5184. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5185. if (D.getDeclSpec().isInlineSpecified())
  5186. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5187. << getLangOpts().CPlusPlus17;
  5188. if (D.getDeclSpec().hasConstexprSpecifier())
  5189. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5190. << 1 << D.getDeclSpec().getConstexprSpecifier();
  5191. if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
  5192. if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
  5193. Diag(D.getName().StartLocation,
  5194. diag::err_deduction_guide_invalid_specifier)
  5195. << "typedef";
  5196. else
  5197. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  5198. << D.getName().getSourceRange();
  5199. return nullptr;
  5200. }
  5201. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  5202. if (!NewTD) return nullptr;
  5203. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5204. ProcessDeclAttributes(S, NewTD, D);
  5205. CheckTypedefForVariablyModifiedType(S, NewTD);
  5206. bool Redeclaration = D.isRedeclaration();
  5207. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  5208. D.setRedeclaration(Redeclaration);
  5209. return ND;
  5210. }
  5211. void
  5212. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  5213. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  5214. // then it shall have block scope.
  5215. // Note that variably modified types must be fixed before merging the decl so
  5216. // that redeclarations will match.
  5217. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  5218. QualType T = TInfo->getType();
  5219. if (T->isVariablyModifiedType()) {
  5220. setFunctionHasBranchProtectedScope();
  5221. if (S->getFnParent() == nullptr) {
  5222. bool SizeIsNegative;
  5223. llvm::APSInt Oversized;
  5224. TypeSourceInfo *FixedTInfo =
  5225. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5226. SizeIsNegative,
  5227. Oversized);
  5228. if (FixedTInfo) {
  5229. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  5230. NewTD->setTypeSourceInfo(FixedTInfo);
  5231. } else {
  5232. if (SizeIsNegative)
  5233. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5234. else if (T->isVariableArrayType())
  5235. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5236. else if (Oversized.getBoolValue())
  5237. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5238. << Oversized.toString(10);
  5239. else
  5240. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5241. NewTD->setInvalidDecl();
  5242. }
  5243. }
  5244. }
  5245. }
  5246. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5247. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5248. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5249. NamedDecl*
  5250. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5251. LookupResult &Previous, bool &Redeclaration) {
  5252. // Find the shadowed declaration before filtering for scope.
  5253. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5254. // Merge the decl with the existing one if appropriate. If the decl is
  5255. // in an outer scope, it isn't the same thing.
  5256. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5257. /*AllowInlineNamespace*/false);
  5258. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5259. if (!Previous.empty()) {
  5260. Redeclaration = true;
  5261. MergeTypedefNameDecl(S, NewTD, Previous);
  5262. } else {
  5263. inferGslPointerAttribute(NewTD);
  5264. }
  5265. if (ShadowedDecl && !Redeclaration)
  5266. CheckShadow(NewTD, ShadowedDecl, Previous);
  5267. // If this is the C FILE type, notify the AST context.
  5268. if (IdentifierInfo *II = NewTD->getIdentifier())
  5269. if (!NewTD->isInvalidDecl() &&
  5270. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5271. if (II->isStr("FILE"))
  5272. Context.setFILEDecl(NewTD);
  5273. else if (II->isStr("jmp_buf"))
  5274. Context.setjmp_bufDecl(NewTD);
  5275. else if (II->isStr("sigjmp_buf"))
  5276. Context.setsigjmp_bufDecl(NewTD);
  5277. else if (II->isStr("ucontext_t"))
  5278. Context.setucontext_tDecl(NewTD);
  5279. }
  5280. return NewTD;
  5281. }
  5282. /// Determines whether the given declaration is an out-of-scope
  5283. /// previous declaration.
  5284. ///
  5285. /// This routine should be invoked when name lookup has found a
  5286. /// previous declaration (PrevDecl) that is not in the scope where a
  5287. /// new declaration by the same name is being introduced. If the new
  5288. /// declaration occurs in a local scope, previous declarations with
  5289. /// linkage may still be considered previous declarations (C99
  5290. /// 6.2.2p4-5, C++ [basic.link]p6).
  5291. ///
  5292. /// \param PrevDecl the previous declaration found by name
  5293. /// lookup
  5294. ///
  5295. /// \param DC the context in which the new declaration is being
  5296. /// declared.
  5297. ///
  5298. /// \returns true if PrevDecl is an out-of-scope previous declaration
  5299. /// for a new delcaration with the same name.
  5300. static bool
  5301. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  5302. ASTContext &Context) {
  5303. if (!PrevDecl)
  5304. return false;
  5305. if (!PrevDecl->hasLinkage())
  5306. return false;
  5307. if (Context.getLangOpts().CPlusPlus) {
  5308. // C++ [basic.link]p6:
  5309. // If there is a visible declaration of an entity with linkage
  5310. // having the same name and type, ignoring entities declared
  5311. // outside the innermost enclosing namespace scope, the block
  5312. // scope declaration declares that same entity and receives the
  5313. // linkage of the previous declaration.
  5314. DeclContext *OuterContext = DC->getRedeclContext();
  5315. if (!OuterContext->isFunctionOrMethod())
  5316. // This rule only applies to block-scope declarations.
  5317. return false;
  5318. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  5319. if (PrevOuterContext->isRecord())
  5320. // We found a member function: ignore it.
  5321. return false;
  5322. // Find the innermost enclosing namespace for the new and
  5323. // previous declarations.
  5324. OuterContext = OuterContext->getEnclosingNamespaceContext();
  5325. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  5326. // The previous declaration is in a different namespace, so it
  5327. // isn't the same function.
  5328. if (!OuterContext->Equals(PrevOuterContext))
  5329. return false;
  5330. }
  5331. return true;
  5332. }
  5333. static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
  5334. CXXScopeSpec &SS = D.getCXXScopeSpec();
  5335. if (!SS.isSet()) return;
  5336. DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
  5337. }
  5338. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  5339. QualType type = decl->getType();
  5340. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  5341. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  5342. // Various kinds of declaration aren't allowed to be __autoreleasing.
  5343. unsigned kind = -1U;
  5344. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5345. if (var->hasAttr<BlocksAttr>())
  5346. kind = 0; // __block
  5347. else if (!var->hasLocalStorage())
  5348. kind = 1; // global
  5349. } else if (isa<ObjCIvarDecl>(decl)) {
  5350. kind = 3; // ivar
  5351. } else if (isa<FieldDecl>(decl)) {
  5352. kind = 2; // field
  5353. }
  5354. if (kind != -1U) {
  5355. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  5356. << kind;
  5357. }
  5358. } else if (lifetime == Qualifiers::OCL_None) {
  5359. // Try to infer lifetime.
  5360. if (!type->isObjCLifetimeType())
  5361. return false;
  5362. lifetime = type->getObjCARCImplicitLifetime();
  5363. type = Context.getLifetimeQualifiedType(type, lifetime);
  5364. decl->setType(type);
  5365. }
  5366. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5367. // Thread-local variables cannot have lifetime.
  5368. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5369. var->getTLSKind()) {
  5370. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5371. << var->getType();
  5372. return true;
  5373. }
  5374. }
  5375. return false;
  5376. }
  5377. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5378. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5379. // the wrong linkage.
  5380. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5381. // 'weak' only applies to declarations with external linkage.
  5382. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5383. if (!ND.isExternallyVisible()) {
  5384. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5385. ND.dropAttr<WeakAttr>();
  5386. }
  5387. }
  5388. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5389. if (ND.isExternallyVisible()) {
  5390. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5391. ND.dropAttr<WeakRefAttr>();
  5392. ND.dropAttr<AliasAttr>();
  5393. }
  5394. }
  5395. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5396. if (VD->hasInit()) {
  5397. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5398. assert(VD->isThisDeclarationADefinition() &&
  5399. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5400. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5401. VD->dropAttr<AliasAttr>();
  5402. }
  5403. }
  5404. }
  5405. // 'selectany' only applies to externally visible variable declarations.
  5406. // It does not apply to functions.
  5407. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5408. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5409. S.Diag(Attr->getLocation(),
  5410. diag::err_attribute_selectany_non_extern_data);
  5411. ND.dropAttr<SelectAnyAttr>();
  5412. }
  5413. }
  5414. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5415. auto *VD = dyn_cast<VarDecl>(&ND);
  5416. bool IsAnonymousNS = false;
  5417. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5418. if (VD) {
  5419. const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
  5420. while (NS && !IsAnonymousNS) {
  5421. IsAnonymousNS = NS->isAnonymousNamespace();
  5422. NS = dyn_cast<NamespaceDecl>(NS->getParent());
  5423. }
  5424. }
  5425. // dll attributes require external linkage. Static locals may have external
  5426. // linkage but still cannot be explicitly imported or exported.
  5427. // In Microsoft mode, a variable defined in anonymous namespace must have
  5428. // external linkage in order to be exported.
  5429. bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
  5430. if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
  5431. (!AnonNSInMicrosoftMode &&
  5432. (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
  5433. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5434. << &ND << Attr;
  5435. ND.setInvalidDecl();
  5436. }
  5437. }
  5438. // Virtual functions cannot be marked as 'notail'.
  5439. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  5440. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  5441. if (MD->isVirtual()) {
  5442. S.Diag(ND.getLocation(),
  5443. diag::err_invalid_attribute_on_virtual_function)
  5444. << Attr;
  5445. ND.dropAttr<NotTailCalledAttr>();
  5446. }
  5447. // Check the attributes on the function type, if any.
  5448. if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
  5449. // Don't declare this variable in the second operand of the for-statement;
  5450. // GCC miscompiles that by ending its lifetime before evaluating the
  5451. // third operand. See gcc.gnu.org/PR86769.
  5452. AttributedTypeLoc ATL;
  5453. for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
  5454. (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
  5455. TL = ATL.getModifiedLoc()) {
  5456. // The [[lifetimebound]] attribute can be applied to the implicit object
  5457. // parameter of a non-static member function (other than a ctor or dtor)
  5458. // by applying it to the function type.
  5459. if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
  5460. const auto *MD = dyn_cast<CXXMethodDecl>(FD);
  5461. if (!MD || MD->isStatic()) {
  5462. S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
  5463. << !MD << A->getRange();
  5464. } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
  5465. S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
  5466. << isa<CXXDestructorDecl>(MD) << A->getRange();
  5467. }
  5468. }
  5469. }
  5470. }
  5471. }
  5472. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5473. NamedDecl *NewDecl,
  5474. bool IsSpecialization,
  5475. bool IsDefinition) {
  5476. if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
  5477. return;
  5478. bool IsTemplate = false;
  5479. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5480. OldDecl = OldTD->getTemplatedDecl();
  5481. IsTemplate = true;
  5482. if (!IsSpecialization)
  5483. IsDefinition = false;
  5484. }
  5485. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5486. NewDecl = NewTD->getTemplatedDecl();
  5487. IsTemplate = true;
  5488. }
  5489. if (!OldDecl || !NewDecl)
  5490. return;
  5491. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5492. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5493. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5494. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5495. // dllimport and dllexport are inheritable attributes so we have to exclude
  5496. // inherited attribute instances.
  5497. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5498. (NewExportAttr && !NewExportAttr->isInherited());
  5499. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5500. // the only exception being explicit specializations.
  5501. // Implicitly generated declarations are also excluded for now because there
  5502. // is no other way to switch these to use dllimport or dllexport.
  5503. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5504. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5505. // Allow with a warning for free functions and global variables.
  5506. bool JustWarn = false;
  5507. if (!OldDecl->isCXXClassMember()) {
  5508. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5509. if (VD && !VD->getDescribedVarTemplate())
  5510. JustWarn = true;
  5511. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5512. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5513. JustWarn = true;
  5514. }
  5515. // We cannot change a declaration that's been used because IR has already
  5516. // been emitted. Dllimported functions will still work though (modulo
  5517. // address equality) as they can use the thunk.
  5518. if (OldDecl->isUsed())
  5519. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5520. JustWarn = false;
  5521. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5522. : diag::err_attribute_dll_redeclaration;
  5523. S.Diag(NewDecl->getLocation(), DiagID)
  5524. << NewDecl
  5525. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5526. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5527. if (!JustWarn) {
  5528. NewDecl->setInvalidDecl();
  5529. return;
  5530. }
  5531. }
  5532. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5533. // exceptions being inline function definitions (except for function
  5534. // templates), local extern declarations, qualified friend declarations or
  5535. // special MSVC extension: in the last case, the declaration is treated as if
  5536. // it were marked dllexport.
  5537. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5538. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5539. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5540. // Ignore static data because out-of-line definitions are diagnosed
  5541. // separately.
  5542. IsStaticDataMember = VD->isStaticDataMember();
  5543. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5544. VarDecl::DeclarationOnly;
  5545. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5546. IsInline = FD->isInlined();
  5547. IsQualifiedFriend = FD->getQualifier() &&
  5548. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5549. }
  5550. if (OldImportAttr && !HasNewAttr &&
  5551. (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
  5552. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5553. if (IsMicrosoft && IsDefinition) {
  5554. S.Diag(NewDecl->getLocation(),
  5555. diag::warn_redeclaration_without_import_attribute)
  5556. << NewDecl;
  5557. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5558. NewDecl->dropAttr<DLLImportAttr>();
  5559. NewDecl->addAttr(
  5560. DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
  5561. } else {
  5562. S.Diag(NewDecl->getLocation(),
  5563. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5564. << NewDecl << OldImportAttr;
  5565. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5566. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5567. OldDecl->dropAttr<DLLImportAttr>();
  5568. NewDecl->dropAttr<DLLImportAttr>();
  5569. }
  5570. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5571. // In MinGW, seeing a function declared inline drops the dllimport
  5572. // attribute.
  5573. OldDecl->dropAttr<DLLImportAttr>();
  5574. NewDecl->dropAttr<DLLImportAttr>();
  5575. S.Diag(NewDecl->getLocation(),
  5576. diag::warn_dllimport_dropped_from_inline_function)
  5577. << NewDecl << OldImportAttr;
  5578. }
  5579. // A specialization of a class template member function is processed here
  5580. // since it's a redeclaration. If the parent class is dllexport, the
  5581. // specialization inherits that attribute. This doesn't happen automatically
  5582. // since the parent class isn't instantiated until later.
  5583. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
  5584. if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
  5585. !NewImportAttr && !NewExportAttr) {
  5586. if (const DLLExportAttr *ParentExportAttr =
  5587. MD->getParent()->getAttr<DLLExportAttr>()) {
  5588. DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
  5589. NewAttr->setInherited(true);
  5590. NewDecl->addAttr(NewAttr);
  5591. }
  5592. }
  5593. }
  5594. }
  5595. /// Given that we are within the definition of the given function,
  5596. /// will that definition behave like C99's 'inline', where the
  5597. /// definition is discarded except for optimization purposes?
  5598. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5599. // Try to avoid calling GetGVALinkageForFunction.
  5600. // All cases of this require the 'inline' keyword.
  5601. if (!FD->isInlined()) return false;
  5602. // This is only possible in C++ with the gnu_inline attribute.
  5603. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5604. return false;
  5605. // Okay, go ahead and call the relatively-more-expensive function.
  5606. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5607. }
  5608. /// Determine whether a variable is extern "C" prior to attaching
  5609. /// an initializer. We can't just call isExternC() here, because that
  5610. /// will also compute and cache whether the declaration is externally
  5611. /// visible, which might change when we attach the initializer.
  5612. ///
  5613. /// This can only be used if the declaration is known to not be a
  5614. /// redeclaration of an internal linkage declaration.
  5615. ///
  5616. /// For instance:
  5617. ///
  5618. /// auto x = []{};
  5619. ///
  5620. /// Attaching the initializer here makes this declaration not externally
  5621. /// visible, because its type has internal linkage.
  5622. ///
  5623. /// FIXME: This is a hack.
  5624. template<typename T>
  5625. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5626. if (S.getLangOpts().CPlusPlus) {
  5627. // In C++, the overloadable attribute negates the effects of extern "C".
  5628. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5629. return false;
  5630. // So do CUDA's host/device attributes.
  5631. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5632. D->template hasAttr<CUDAHostAttr>()))
  5633. return false;
  5634. }
  5635. return D->isExternC();
  5636. }
  5637. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5638. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5639. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
  5640. isa<OMPDeclareMapperDecl>(DC))
  5641. return VD->hasExternalStorage();
  5642. if (DC->isFileContext())
  5643. return true;
  5644. if (DC->isRecord())
  5645. return false;
  5646. llvm_unreachable("Unexpected context");
  5647. }
  5648. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5649. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5650. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5651. isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
  5652. return true;
  5653. if (DC->isRecord())
  5654. return false;
  5655. llvm_unreachable("Unexpected context");
  5656. }
  5657. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5658. ParsedAttr::Kind Kind) {
  5659. // Check decl attributes on the DeclSpec.
  5660. if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
  5661. return true;
  5662. // Walk the declarator structure, checking decl attributes that were in a type
  5663. // position to the decl itself.
  5664. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  5665. if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
  5666. return true;
  5667. }
  5668. // Finally, check attributes on the decl itself.
  5669. return PD.getAttributes().hasAttribute(Kind);
  5670. }
  5671. /// Adjust the \c DeclContext for a function or variable that might be a
  5672. /// function-local external declaration.
  5673. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  5674. if (!DC->isFunctionOrMethod())
  5675. return false;
  5676. // If this is a local extern function or variable declared within a function
  5677. // template, don't add it into the enclosing namespace scope until it is
  5678. // instantiated; it might have a dependent type right now.
  5679. if (DC->isDependentContext())
  5680. return true;
  5681. // C++11 [basic.link]p7:
  5682. // When a block scope declaration of an entity with linkage is not found to
  5683. // refer to some other declaration, then that entity is a member of the
  5684. // innermost enclosing namespace.
  5685. //
  5686. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  5687. // semantically-enclosing namespace, not a lexically-enclosing one.
  5688. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  5689. DC = DC->getParent();
  5690. return true;
  5691. }
  5692. /// Returns true if given declaration has external C language linkage.
  5693. static bool isDeclExternC(const Decl *D) {
  5694. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  5695. return FD->isExternC();
  5696. if (const auto *VD = dyn_cast<VarDecl>(D))
  5697. return VD->isExternC();
  5698. llvm_unreachable("Unknown type of decl!");
  5699. }
  5700. NamedDecl *Sema::ActOnVariableDeclarator(
  5701. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  5702. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  5703. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  5704. QualType R = TInfo->getType();
  5705. DeclarationName Name = GetNameForDeclarator(D).getName();
  5706. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5707. if (D.isDecompositionDeclarator()) {
  5708. // Take the name of the first declarator as our name for diagnostic
  5709. // purposes.
  5710. auto &Decomp = D.getDecompositionDeclarator();
  5711. if (!Decomp.bindings().empty()) {
  5712. II = Decomp.bindings()[0].Name;
  5713. Name = II;
  5714. }
  5715. } else if (!II) {
  5716. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  5717. return nullptr;
  5718. }
  5719. if (getLangOpts().OpenCL) {
  5720. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  5721. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  5722. // argument.
  5723. if (R->isImageType() || R->isPipeType()) {
  5724. Diag(D.getIdentifierLoc(),
  5725. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  5726. << R;
  5727. D.setInvalidType();
  5728. return nullptr;
  5729. }
  5730. // OpenCL v1.2 s6.9.r:
  5731. // The event type cannot be used to declare a program scope variable.
  5732. // OpenCL v2.0 s6.9.q:
  5733. // The clk_event_t and reserve_id_t types cannot be declared in program scope.
  5734. if (NULL == S->getParent()) {
  5735. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  5736. Diag(D.getIdentifierLoc(),
  5737. diag::err_invalid_type_for_program_scope_var) << R;
  5738. D.setInvalidType();
  5739. return nullptr;
  5740. }
  5741. }
  5742. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  5743. QualType NR = R;
  5744. while (NR->isPointerType()) {
  5745. if (NR->isFunctionPointerType()) {
  5746. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
  5747. D.setInvalidType();
  5748. break;
  5749. }
  5750. NR = NR->getPointeeType();
  5751. }
  5752. if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  5753. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5754. // half array type (unless the cl_khr_fp16 extension is enabled).
  5755. if (Context.getBaseElementType(R)->isHalfType()) {
  5756. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5757. D.setInvalidType();
  5758. }
  5759. }
  5760. if (R->isSamplerT()) {
  5761. // OpenCL v1.2 s6.9.b p4:
  5762. // The sampler type cannot be used with the __local and __global address
  5763. // space qualifiers.
  5764. if (R.getAddressSpace() == LangAS::opencl_local ||
  5765. R.getAddressSpace() == LangAS::opencl_global) {
  5766. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5767. }
  5768. // OpenCL v1.2 s6.12.14.1:
  5769. // A global sampler must be declared with either the constant address
  5770. // space qualifier or with the const qualifier.
  5771. if (DC->isTranslationUnit() &&
  5772. !(R.getAddressSpace() == LangAS::opencl_constant ||
  5773. R.isConstQualified())) {
  5774. Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
  5775. D.setInvalidType();
  5776. }
  5777. }
  5778. // OpenCL v1.2 s6.9.r:
  5779. // The event type cannot be used with the __local, __constant and __global
  5780. // address space qualifiers.
  5781. if (R->isEventT()) {
  5782. if (R.getAddressSpace() != LangAS::opencl_private) {
  5783. Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
  5784. D.setInvalidType();
  5785. }
  5786. }
  5787. // C++ for OpenCL does not allow the thread_local storage qualifier.
  5788. // OpenCL C does not support thread_local either, and
  5789. // also reject all other thread storage class specifiers.
  5790. DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
  5791. if (TSC != TSCS_unspecified) {
  5792. bool IsCXX = getLangOpts().OpenCLCPlusPlus;
  5793. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5794. diag::err_opencl_unknown_type_specifier)
  5795. << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
  5796. << DeclSpec::getSpecifierName(TSC) << 1;
  5797. D.setInvalidType();
  5798. return nullptr;
  5799. }
  5800. }
  5801. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  5802. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  5803. // dllimport globals without explicit storage class are treated as extern. We
  5804. // have to change the storage class this early to get the right DeclContext.
  5805. if (SC == SC_None && !DC->isRecord() &&
  5806. hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
  5807. !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
  5808. SC = SC_Extern;
  5809. DeclContext *OriginalDC = DC;
  5810. bool IsLocalExternDecl = SC == SC_Extern &&
  5811. adjustContextForLocalExternDecl(DC);
  5812. if (SCSpec == DeclSpec::SCS_mutable) {
  5813. // mutable can only appear on non-static class members, so it's always
  5814. // an error here
  5815. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5816. D.setInvalidType();
  5817. SC = SC_None;
  5818. }
  5819. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5820. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5821. D.getDeclSpec().getStorageClassSpecLoc())) {
  5822. // In C++11, the 'register' storage class specifier is deprecated.
  5823. // Suppress the warning in system macros, it's used in macros in some
  5824. // popular C system headers, such as in glibc's htonl() macro.
  5825. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5826. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  5827. : diag::warn_deprecated_register)
  5828. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5829. }
  5830. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5831. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5832. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5833. // appear in the declaration specifiers in an external declaration.
  5834. // Global Register+Asm is a GNU extension we support.
  5835. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5836. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5837. D.setInvalidType();
  5838. }
  5839. }
  5840. bool IsMemberSpecialization = false;
  5841. bool IsVariableTemplateSpecialization = false;
  5842. bool IsPartialSpecialization = false;
  5843. bool IsVariableTemplate = false;
  5844. VarDecl *NewVD = nullptr;
  5845. VarTemplateDecl *NewTemplate = nullptr;
  5846. TemplateParameterList *TemplateParams = nullptr;
  5847. if (!getLangOpts().CPlusPlus) {
  5848. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
  5849. II, R, TInfo, SC);
  5850. if (R->getContainedDeducedType())
  5851. ParsingInitForAutoVars.insert(NewVD);
  5852. if (D.isInvalidType())
  5853. NewVD->setInvalidDecl();
  5854. if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
  5855. NewVD->hasLocalStorage())
  5856. checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
  5857. NTCUC_AutoVar, NTCUK_Destruct);
  5858. } else {
  5859. bool Invalid = false;
  5860. if (DC->isRecord() && !CurContext->isRecord()) {
  5861. // This is an out-of-line definition of a static data member.
  5862. switch (SC) {
  5863. case SC_None:
  5864. break;
  5865. case SC_Static:
  5866. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5867. diag::err_static_out_of_line)
  5868. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5869. break;
  5870. case SC_Auto:
  5871. case SC_Register:
  5872. case SC_Extern:
  5873. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5874. // to names of variables declared in a block or to function parameters.
  5875. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5876. // of class members
  5877. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5878. diag::err_storage_class_for_static_member)
  5879. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5880. break;
  5881. case SC_PrivateExtern:
  5882. llvm_unreachable("C storage class in c++!");
  5883. }
  5884. }
  5885. if (SC == SC_Static && CurContext->isRecord()) {
  5886. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5887. if (RD->isLocalClass())
  5888. Diag(D.getIdentifierLoc(),
  5889. diag::err_static_data_member_not_allowed_in_local_class)
  5890. << Name << RD->getDeclName();
  5891. // C++98 [class.union]p1: If a union contains a static data member,
  5892. // the program is ill-formed. C++11 drops this restriction.
  5893. if (RD->isUnion())
  5894. Diag(D.getIdentifierLoc(),
  5895. getLangOpts().CPlusPlus11
  5896. ? diag::warn_cxx98_compat_static_data_member_in_union
  5897. : diag::ext_static_data_member_in_union) << Name;
  5898. // We conservatively disallow static data members in anonymous structs.
  5899. else if (!RD->getDeclName())
  5900. Diag(D.getIdentifierLoc(),
  5901. diag::err_static_data_member_not_allowed_in_anon_struct)
  5902. << Name << RD->isUnion();
  5903. }
  5904. }
  5905. // Match up the template parameter lists with the scope specifier, then
  5906. // determine whether we have a template or a template specialization.
  5907. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5908. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  5909. D.getCXXScopeSpec(),
  5910. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  5911. ? D.getName().TemplateId
  5912. : nullptr,
  5913. TemplateParamLists,
  5914. /*never a friend*/ false, IsMemberSpecialization, Invalid);
  5915. if (TemplateParams) {
  5916. if (!TemplateParams->size() &&
  5917. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  5918. // There is an extraneous 'template<>' for this variable. Complain
  5919. // about it, but allow the declaration of the variable.
  5920. Diag(TemplateParams->getTemplateLoc(),
  5921. diag::err_template_variable_noparams)
  5922. << II
  5923. << SourceRange(TemplateParams->getTemplateLoc(),
  5924. TemplateParams->getRAngleLoc());
  5925. TemplateParams = nullptr;
  5926. } else {
  5927. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  5928. // This is an explicit specialization or a partial specialization.
  5929. // FIXME: Check that we can declare a specialization here.
  5930. IsVariableTemplateSpecialization = true;
  5931. IsPartialSpecialization = TemplateParams->size() > 0;
  5932. } else { // if (TemplateParams->size() > 0)
  5933. // This is a template declaration.
  5934. IsVariableTemplate = true;
  5935. // Check that we can declare a template here.
  5936. if (CheckTemplateDeclScope(S, TemplateParams))
  5937. return nullptr;
  5938. // Only C++1y supports variable templates (N3651).
  5939. Diag(D.getIdentifierLoc(),
  5940. getLangOpts().CPlusPlus14
  5941. ? diag::warn_cxx11_compat_variable_template
  5942. : diag::ext_variable_template);
  5943. }
  5944. }
  5945. } else {
  5946. assert((Invalid ||
  5947. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
  5948. "should have a 'template<>' for this decl");
  5949. }
  5950. if (IsVariableTemplateSpecialization) {
  5951. SourceLocation TemplateKWLoc =
  5952. TemplateParamLists.size() > 0
  5953. ? TemplateParamLists[0]->getTemplateLoc()
  5954. : SourceLocation();
  5955. DeclResult Res = ActOnVarTemplateSpecialization(
  5956. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5957. IsPartialSpecialization);
  5958. if (Res.isInvalid())
  5959. return nullptr;
  5960. NewVD = cast<VarDecl>(Res.get());
  5961. AddToScope = false;
  5962. } else if (D.isDecompositionDeclarator()) {
  5963. NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
  5964. D.getIdentifierLoc(), R, TInfo, SC,
  5965. Bindings);
  5966. } else
  5967. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
  5968. D.getIdentifierLoc(), II, R, TInfo, SC);
  5969. // If this is supposed to be a variable template, create it as such.
  5970. if (IsVariableTemplate) {
  5971. NewTemplate =
  5972. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5973. TemplateParams, NewVD);
  5974. NewVD->setDescribedVarTemplate(NewTemplate);
  5975. }
  5976. // If this decl has an auto type in need of deduction, make a note of the
  5977. // Decl so we can diagnose uses of it in its own initializer.
  5978. if (R->getContainedDeducedType())
  5979. ParsingInitForAutoVars.insert(NewVD);
  5980. if (D.isInvalidType() || Invalid) {
  5981. NewVD->setInvalidDecl();
  5982. if (NewTemplate)
  5983. NewTemplate->setInvalidDecl();
  5984. }
  5985. SetNestedNameSpecifier(*this, NewVD, D);
  5986. // If we have any template parameter lists that don't directly belong to
  5987. // the variable (matching the scope specifier), store them.
  5988. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5989. if (TemplateParamLists.size() > VDTemplateParamLists)
  5990. NewVD->setTemplateParameterListsInfo(
  5991. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5992. }
  5993. if (D.getDeclSpec().isInlineSpecified()) {
  5994. if (!getLangOpts().CPlusPlus) {
  5995. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5996. << 0;
  5997. } else if (CurContext->isFunctionOrMethod()) {
  5998. // 'inline' is not allowed on block scope variable declaration.
  5999. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6000. diag::err_inline_declaration_block_scope) << Name
  6001. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  6002. } else {
  6003. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6004. getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
  6005. : diag::ext_inline_variable);
  6006. NewVD->setInlineSpecified();
  6007. }
  6008. }
  6009. // Set the lexical context. If the declarator has a C++ scope specifier, the
  6010. // lexical context will be different from the semantic context.
  6011. NewVD->setLexicalDeclContext(CurContext);
  6012. if (NewTemplate)
  6013. NewTemplate->setLexicalDeclContext(CurContext);
  6014. if (IsLocalExternDecl) {
  6015. if (D.isDecompositionDeclarator())
  6016. for (auto *B : Bindings)
  6017. B->setLocalExternDecl();
  6018. else
  6019. NewVD->setLocalExternDecl();
  6020. }
  6021. bool EmitTLSUnsupportedError = false;
  6022. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  6023. // C++11 [dcl.stc]p4:
  6024. // When thread_local is applied to a variable of block scope the
  6025. // storage-class-specifier static is implied if it does not appear
  6026. // explicitly.
  6027. // Core issue: 'static' is not implied if the variable is declared
  6028. // 'extern'.
  6029. if (NewVD->hasLocalStorage() &&
  6030. (SCSpec != DeclSpec::SCS_unspecified ||
  6031. TSCS != DeclSpec::TSCS_thread_local ||
  6032. !DC->isFunctionOrMethod()))
  6033. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6034. diag::err_thread_non_global)
  6035. << DeclSpec::getSpecifierName(TSCS);
  6036. else if (!Context.getTargetInfo().isTLSSupported()) {
  6037. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  6038. // Postpone error emission until we've collected attributes required to
  6039. // figure out whether it's a host or device variable and whether the
  6040. // error should be ignored.
  6041. EmitTLSUnsupportedError = true;
  6042. // We still need to mark the variable as TLS so it shows up in AST with
  6043. // proper storage class for other tools to use even if we're not going
  6044. // to emit any code for it.
  6045. NewVD->setTSCSpec(TSCS);
  6046. } else
  6047. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6048. diag::err_thread_unsupported);
  6049. } else
  6050. NewVD->setTSCSpec(TSCS);
  6051. }
  6052. switch (D.getDeclSpec().getConstexprSpecifier()) {
  6053. case CSK_unspecified:
  6054. break;
  6055. case CSK_consteval:
  6056. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  6057. diag::err_constexpr_wrong_decl_kind)
  6058. << D.getDeclSpec().getConstexprSpecifier();
  6059. LLVM_FALLTHROUGH;
  6060. case CSK_constexpr:
  6061. NewVD->setConstexpr(true);
  6062. // C++1z [dcl.spec.constexpr]p1:
  6063. // A static data member declared with the constexpr specifier is
  6064. // implicitly an inline variable.
  6065. if (NewVD->isStaticDataMember() &&
  6066. (getLangOpts().CPlusPlus17 ||
  6067. Context.getTargetInfo().getCXXABI().isMicrosoft()))
  6068. NewVD->setImplicitlyInline();
  6069. break;
  6070. case CSK_constinit:
  6071. if (!NewVD->hasGlobalStorage())
  6072. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  6073. diag::err_constinit_local_variable);
  6074. else
  6075. NewVD->addAttr(ConstInitAttr::Create(
  6076. Context, D.getDeclSpec().getConstexprSpecLoc(),
  6077. AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
  6078. break;
  6079. }
  6080. // C99 6.7.4p3
  6081. // An inline definition of a function with external linkage shall
  6082. // not contain a definition of a modifiable object with static or
  6083. // thread storage duration...
  6084. // We only apply this when the function is required to be defined
  6085. // elsewhere, i.e. when the function is not 'extern inline'. Note
  6086. // that a local variable with thread storage duration still has to
  6087. // be marked 'static'. Also note that it's possible to get these
  6088. // semantics in C++ using __attribute__((gnu_inline)).
  6089. if (SC == SC_Static && S->getFnParent() != nullptr &&
  6090. !NewVD->getType().isConstQualified()) {
  6091. FunctionDecl *CurFD = getCurFunctionDecl();
  6092. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  6093. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6094. diag::warn_static_local_in_extern_inline);
  6095. MaybeSuggestAddingStaticToDecl(CurFD);
  6096. }
  6097. }
  6098. if (D.getDeclSpec().isModulePrivateSpecified()) {
  6099. if (IsVariableTemplateSpecialization)
  6100. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  6101. << (IsPartialSpecialization ? 1 : 0)
  6102. << FixItHint::CreateRemoval(
  6103. D.getDeclSpec().getModulePrivateSpecLoc());
  6104. else if (IsMemberSpecialization)
  6105. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  6106. << 2
  6107. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6108. else if (NewVD->hasLocalStorage())
  6109. Diag(NewVD->getLocation(), diag::err_module_private_local)
  6110. << 0 << NewVD->getDeclName()
  6111. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  6112. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6113. else {
  6114. NewVD->setModulePrivate();
  6115. if (NewTemplate)
  6116. NewTemplate->setModulePrivate();
  6117. for (auto *B : Bindings)
  6118. B->setModulePrivate();
  6119. }
  6120. }
  6121. // Handle attributes prior to checking for duplicates in MergeVarDecl
  6122. ProcessDeclAttributes(S, NewVD, D);
  6123. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  6124. if (EmitTLSUnsupportedError &&
  6125. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  6126. (getLangOpts().OpenMPIsDevice &&
  6127. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
  6128. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6129. diag::err_thread_unsupported);
  6130. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  6131. // storage [duration]."
  6132. if (SC == SC_None && S->getFnParent() != nullptr &&
  6133. (NewVD->hasAttr<CUDASharedAttr>() ||
  6134. NewVD->hasAttr<CUDAConstantAttr>())) {
  6135. NewVD->setStorageClass(SC_Static);
  6136. }
  6137. }
  6138. // Ensure that dllimport globals without explicit storage class are treated as
  6139. // extern. The storage class is set above using parsed attributes. Now we can
  6140. // check the VarDecl itself.
  6141. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  6142. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  6143. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  6144. // In auto-retain/release, infer strong retension for variables of
  6145. // retainable type.
  6146. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  6147. NewVD->setInvalidDecl();
  6148. // Handle GNU asm-label extension (encoded as an attribute).
  6149. if (Expr *E = (Expr*)D.getAsmLabel()) {
  6150. // The parser guarantees this is a string.
  6151. StringLiteral *SE = cast<StringLiteral>(E);
  6152. StringRef Label = SE->getString();
  6153. if (S->getFnParent() != nullptr) {
  6154. switch (SC) {
  6155. case SC_None:
  6156. case SC_Auto:
  6157. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  6158. break;
  6159. case SC_Register:
  6160. // Local Named register
  6161. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  6162. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  6163. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6164. break;
  6165. case SC_Static:
  6166. case SC_Extern:
  6167. case SC_PrivateExtern:
  6168. break;
  6169. }
  6170. } else if (SC == SC_Register) {
  6171. // Global Named register
  6172. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  6173. const auto &TI = Context.getTargetInfo();
  6174. bool HasSizeMismatch;
  6175. if (!TI.isValidGCCRegisterName(Label))
  6176. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6177. else if (!TI.validateGlobalRegisterVariable(Label,
  6178. Context.getTypeSize(R),
  6179. HasSizeMismatch))
  6180. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  6181. else if (HasSizeMismatch)
  6182. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  6183. }
  6184. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  6185. Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
  6186. NewVD->setInvalidDecl(true);
  6187. }
  6188. }
  6189. NewVD->addAttr(::new (Context) AsmLabelAttr(
  6190. Context, SE->getStrTokenLoc(0), Label, /*IsLiteralLabel=*/true));
  6191. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  6192. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6193. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  6194. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6195. if (isDeclExternC(NewVD)) {
  6196. NewVD->addAttr(I->second);
  6197. ExtnameUndeclaredIdentifiers.erase(I);
  6198. } else
  6199. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  6200. << /*Variable*/1 << NewVD;
  6201. }
  6202. }
  6203. // Find the shadowed declaration before filtering for scope.
  6204. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  6205. ? getShadowedDeclaration(NewVD, Previous)
  6206. : nullptr;
  6207. // Don't consider existing declarations that are in a different
  6208. // scope and are out-of-semantic-context declarations (if the new
  6209. // declaration has linkage).
  6210. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  6211. D.getCXXScopeSpec().isNotEmpty() ||
  6212. IsMemberSpecialization ||
  6213. IsVariableTemplateSpecialization);
  6214. // Check whether the previous declaration is in the same block scope. This
  6215. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  6216. if (getLangOpts().CPlusPlus &&
  6217. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  6218. NewVD->setPreviousDeclInSameBlockScope(
  6219. Previous.isSingleResult() && !Previous.isShadowed() &&
  6220. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  6221. if (!getLangOpts().CPlusPlus) {
  6222. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6223. } else {
  6224. // If this is an explicit specialization of a static data member, check it.
  6225. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  6226. CheckMemberSpecialization(NewVD, Previous))
  6227. NewVD->setInvalidDecl();
  6228. // Merge the decl with the existing one if appropriate.
  6229. if (!Previous.empty()) {
  6230. if (Previous.isSingleResult() &&
  6231. isa<FieldDecl>(Previous.getFoundDecl()) &&
  6232. D.getCXXScopeSpec().isSet()) {
  6233. // The user tried to define a non-static data member
  6234. // out-of-line (C++ [dcl.meaning]p1).
  6235. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  6236. << D.getCXXScopeSpec().getRange();
  6237. Previous.clear();
  6238. NewVD->setInvalidDecl();
  6239. }
  6240. } else if (D.getCXXScopeSpec().isSet()) {
  6241. // No previous declaration in the qualifying scope.
  6242. Diag(D.getIdentifierLoc(), diag::err_no_member)
  6243. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  6244. << D.getCXXScopeSpec().getRange();
  6245. NewVD->setInvalidDecl();
  6246. }
  6247. if (!IsVariableTemplateSpecialization)
  6248. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6249. if (NewTemplate) {
  6250. VarTemplateDecl *PrevVarTemplate =
  6251. NewVD->getPreviousDecl()
  6252. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  6253. : nullptr;
  6254. // Check the template parameter list of this declaration, possibly
  6255. // merging in the template parameter list from the previous variable
  6256. // template declaration.
  6257. if (CheckTemplateParameterList(
  6258. TemplateParams,
  6259. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  6260. : nullptr,
  6261. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  6262. DC->isDependentContext())
  6263. ? TPC_ClassTemplateMember
  6264. : TPC_VarTemplate))
  6265. NewVD->setInvalidDecl();
  6266. // If we are providing an explicit specialization of a static variable
  6267. // template, make a note of that.
  6268. if (PrevVarTemplate &&
  6269. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  6270. PrevVarTemplate->setMemberSpecialization();
  6271. }
  6272. }
  6273. // Diagnose shadowed variables iff this isn't a redeclaration.
  6274. if (ShadowedDecl && !D.isRedeclaration())
  6275. CheckShadow(NewVD, ShadowedDecl, Previous);
  6276. ProcessPragmaWeak(S, NewVD);
  6277. // If this is the first declaration of an extern C variable, update
  6278. // the map of such variables.
  6279. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  6280. isIncompleteDeclExternC(*this, NewVD))
  6281. RegisterLocallyScopedExternCDecl(NewVD, S);
  6282. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  6283. Decl *ManglingContextDecl;
  6284. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  6285. NewVD->getDeclContext(), ManglingContextDecl)) {
  6286. Context.setManglingNumber(
  6287. NewVD, MCtx->getManglingNumber(
  6288. NewVD, getMSManglingNumber(getLangOpts(), S)));
  6289. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  6290. }
  6291. }
  6292. // Special handling of variable named 'main'.
  6293. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  6294. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  6295. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  6296. // C++ [basic.start.main]p3
  6297. // A program that declares a variable main at global scope is ill-formed.
  6298. if (getLangOpts().CPlusPlus)
  6299. Diag(D.getBeginLoc(), diag::err_main_global_variable);
  6300. // In C, and external-linkage variable named main results in undefined
  6301. // behavior.
  6302. else if (NewVD->hasExternalFormalLinkage())
  6303. Diag(D.getBeginLoc(), diag::warn_main_redefined);
  6304. }
  6305. if (D.isRedeclaration() && !Previous.empty()) {
  6306. NamedDecl *Prev = Previous.getRepresentativeDecl();
  6307. checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
  6308. D.isFunctionDefinition());
  6309. }
  6310. if (NewTemplate) {
  6311. if (NewVD->isInvalidDecl())
  6312. NewTemplate->setInvalidDecl();
  6313. ActOnDocumentableDecl(NewTemplate);
  6314. return NewTemplate;
  6315. }
  6316. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  6317. CompleteMemberSpecialization(NewVD, Previous);
  6318. return NewVD;
  6319. }
  6320. /// Enum describing the %select options in diag::warn_decl_shadow.
  6321. enum ShadowedDeclKind {
  6322. SDK_Local,
  6323. SDK_Global,
  6324. SDK_StaticMember,
  6325. SDK_Field,
  6326. SDK_Typedef,
  6327. SDK_Using
  6328. };
  6329. /// Determine what kind of declaration we're shadowing.
  6330. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  6331. const DeclContext *OldDC) {
  6332. if (isa<TypeAliasDecl>(ShadowedDecl))
  6333. return SDK_Using;
  6334. else if (isa<TypedefDecl>(ShadowedDecl))
  6335. return SDK_Typedef;
  6336. else if (isa<RecordDecl>(OldDC))
  6337. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  6338. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  6339. }
  6340. /// Return the location of the capture if the given lambda captures the given
  6341. /// variable \p VD, or an invalid source location otherwise.
  6342. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  6343. const VarDecl *VD) {
  6344. for (const Capture &Capture : LSI->Captures) {
  6345. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  6346. return Capture.getLocation();
  6347. }
  6348. return SourceLocation();
  6349. }
  6350. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  6351. const LookupResult &R) {
  6352. // Only diagnose if we're shadowing an unambiguous field or variable.
  6353. if (R.getResultKind() != LookupResult::Found)
  6354. return false;
  6355. // Return false if warning is ignored.
  6356. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  6357. }
  6358. /// Return the declaration shadowed by the given variable \p D, or null
  6359. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6360. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  6361. const LookupResult &R) {
  6362. if (!shouldWarnIfShadowedDecl(Diags, R))
  6363. return nullptr;
  6364. // Don't diagnose declarations at file scope.
  6365. if (D->hasGlobalStorage())
  6366. return nullptr;
  6367. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6368. return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
  6369. ? ShadowedDecl
  6370. : nullptr;
  6371. }
  6372. /// Return the declaration shadowed by the given typedef \p D, or null
  6373. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6374. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  6375. const LookupResult &R) {
  6376. // Don't warn if typedef declaration is part of a class
  6377. if (D->getDeclContext()->isRecord())
  6378. return nullptr;
  6379. if (!shouldWarnIfShadowedDecl(Diags, R))
  6380. return nullptr;
  6381. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6382. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  6383. }
  6384. /// Diagnose variable or built-in function shadowing. Implements
  6385. /// -Wshadow.
  6386. ///
  6387. /// This method is called whenever a VarDecl is added to a "useful"
  6388. /// scope.
  6389. ///
  6390. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  6391. /// \param R the lookup of the name
  6392. ///
  6393. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  6394. const LookupResult &R) {
  6395. DeclContext *NewDC = D->getDeclContext();
  6396. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  6397. // Fields are not shadowed by variables in C++ static methods.
  6398. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  6399. if (MD->isStatic())
  6400. return;
  6401. // Fields shadowed by constructor parameters are a special case. Usually
  6402. // the constructor initializes the field with the parameter.
  6403. if (isa<CXXConstructorDecl>(NewDC))
  6404. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  6405. // Remember that this was shadowed so we can either warn about its
  6406. // modification or its existence depending on warning settings.
  6407. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  6408. return;
  6409. }
  6410. }
  6411. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  6412. if (shadowedVar->isExternC()) {
  6413. // For shadowing external vars, make sure that we point to the global
  6414. // declaration, not a locally scoped extern declaration.
  6415. for (auto I : shadowedVar->redecls())
  6416. if (I->isFileVarDecl()) {
  6417. ShadowedDecl = I;
  6418. break;
  6419. }
  6420. }
  6421. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  6422. unsigned WarningDiag = diag::warn_decl_shadow;
  6423. SourceLocation CaptureLoc;
  6424. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  6425. isa<CXXMethodDecl>(NewDC)) {
  6426. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  6427. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  6428. if (RD->getLambdaCaptureDefault() == LCD_None) {
  6429. // Try to avoid warnings for lambdas with an explicit capture list.
  6430. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  6431. // Warn only when the lambda captures the shadowed decl explicitly.
  6432. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  6433. if (CaptureLoc.isInvalid())
  6434. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  6435. } else {
  6436. // Remember that this was shadowed so we can avoid the warning if the
  6437. // shadowed decl isn't captured and the warning settings allow it.
  6438. cast<LambdaScopeInfo>(getCurFunction())
  6439. ->ShadowingDecls.push_back(
  6440. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  6441. return;
  6442. }
  6443. }
  6444. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  6445. // A variable can't shadow a local variable in an enclosing scope, if
  6446. // they are separated by a non-capturing declaration context.
  6447. for (DeclContext *ParentDC = NewDC;
  6448. ParentDC && !ParentDC->Equals(OldDC);
  6449. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  6450. // Only block literals, captured statements, and lambda expressions
  6451. // can capture; other scopes don't.
  6452. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  6453. !isLambdaCallOperator(ParentDC)) {
  6454. return;
  6455. }
  6456. }
  6457. }
  6458. }
  6459. }
  6460. // Only warn about certain kinds of shadowing for class members.
  6461. if (NewDC && NewDC->isRecord()) {
  6462. // In particular, don't warn about shadowing non-class members.
  6463. if (!OldDC->isRecord())
  6464. return;
  6465. // TODO: should we warn about static data members shadowing
  6466. // static data members from base classes?
  6467. // TODO: don't diagnose for inaccessible shadowed members.
  6468. // This is hard to do perfectly because we might friend the
  6469. // shadowing context, but that's just a false negative.
  6470. }
  6471. DeclarationName Name = R.getLookupName();
  6472. // Emit warning and note.
  6473. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  6474. return;
  6475. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6476. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6477. if (!CaptureLoc.isInvalid())
  6478. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6479. << Name << /*explicitly*/ 1;
  6480. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6481. }
  6482. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6483. /// when these variables are captured by the lambda.
  6484. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6485. for (const auto &Shadow : LSI->ShadowingDecls) {
  6486. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6487. // Try to avoid the warning when the shadowed decl isn't captured.
  6488. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6489. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6490. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6491. ? diag::warn_decl_shadow_uncaptured_local
  6492. : diag::warn_decl_shadow)
  6493. << Shadow.VD->getDeclName()
  6494. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6495. if (!CaptureLoc.isInvalid())
  6496. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6497. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6498. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6499. }
  6500. }
  6501. /// Check -Wshadow without the advantage of a previous lookup.
  6502. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6503. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6504. return;
  6505. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  6506. Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  6507. LookupName(R, S);
  6508. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  6509. CheckShadow(D, ShadowedDecl, R);
  6510. }
  6511. /// Check if 'E', which is an expression that is about to be modified, refers
  6512. /// to a constructor parameter that shadows a field.
  6513. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  6514. // Quickly ignore expressions that can't be shadowing ctor parameters.
  6515. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  6516. return;
  6517. E = E->IgnoreParenImpCasts();
  6518. auto *DRE = dyn_cast<DeclRefExpr>(E);
  6519. if (!DRE)
  6520. return;
  6521. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  6522. auto I = ShadowingDecls.find(D);
  6523. if (I == ShadowingDecls.end())
  6524. return;
  6525. const NamedDecl *ShadowedDecl = I->second;
  6526. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6527. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  6528. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  6529. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6530. // Avoid issuing multiple warnings about the same decl.
  6531. ShadowingDecls.erase(I);
  6532. }
  6533. /// Check for conflict between this global or extern "C" declaration and
  6534. /// previous global or extern "C" declarations. This is only used in C++.
  6535. template<typename T>
  6536. static bool checkGlobalOrExternCConflict(
  6537. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  6538. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  6539. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  6540. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  6541. // The common case: this global doesn't conflict with any extern "C"
  6542. // declaration.
  6543. return false;
  6544. }
  6545. if (Prev) {
  6546. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  6547. // Both the old and new declarations have C language linkage. This is a
  6548. // redeclaration.
  6549. Previous.clear();
  6550. Previous.addDecl(Prev);
  6551. return true;
  6552. }
  6553. // This is a global, non-extern "C" declaration, and there is a previous
  6554. // non-global extern "C" declaration. Diagnose if this is a variable
  6555. // declaration.
  6556. if (!isa<VarDecl>(ND))
  6557. return false;
  6558. } else {
  6559. // The declaration is extern "C". Check for any declaration in the
  6560. // translation unit which might conflict.
  6561. if (IsGlobal) {
  6562. // We have already performed the lookup into the translation unit.
  6563. IsGlobal = false;
  6564. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6565. I != E; ++I) {
  6566. if (isa<VarDecl>(*I)) {
  6567. Prev = *I;
  6568. break;
  6569. }
  6570. }
  6571. } else {
  6572. DeclContext::lookup_result R =
  6573. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6574. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6575. I != E; ++I) {
  6576. if (isa<VarDecl>(*I)) {
  6577. Prev = *I;
  6578. break;
  6579. }
  6580. // FIXME: If we have any other entity with this name in global scope,
  6581. // the declaration is ill-formed, but that is a defect: it breaks the
  6582. // 'stat' hack, for instance. Only variables can have mangled name
  6583. // clashes with extern "C" declarations, so only they deserve a
  6584. // diagnostic.
  6585. }
  6586. }
  6587. if (!Prev)
  6588. return false;
  6589. }
  6590. // Use the first declaration's location to ensure we point at something which
  6591. // is lexically inside an extern "C" linkage-spec.
  6592. assert(Prev && "should have found a previous declaration to diagnose");
  6593. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6594. Prev = FD->getFirstDecl();
  6595. else
  6596. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6597. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6598. << IsGlobal << ND;
  6599. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6600. << IsGlobal;
  6601. return false;
  6602. }
  6603. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6604. /// if we have found that this is a redeclaration of some prior entity.
  6605. ///
  6606. /// Per C++ [dcl.link]p6:
  6607. /// Two declarations [for a function or variable] with C language linkage
  6608. /// with the same name that appear in different scopes refer to the same
  6609. /// [entity]. An entity with C language linkage shall not be declared with
  6610. /// the same name as an entity in global scope.
  6611. template<typename T>
  6612. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6613. LookupResult &Previous) {
  6614. if (!S.getLangOpts().CPlusPlus) {
  6615. // In C, when declaring a global variable, look for a corresponding 'extern'
  6616. // variable declared in function scope. We don't need this in C++, because
  6617. // we find local extern decls in the surrounding file-scope DeclContext.
  6618. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6619. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6620. Previous.clear();
  6621. Previous.addDecl(Prev);
  6622. return true;
  6623. }
  6624. }
  6625. return false;
  6626. }
  6627. // A declaration in the translation unit can conflict with an extern "C"
  6628. // declaration.
  6629. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6630. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6631. // An extern "C" declaration can conflict with a declaration in the
  6632. // translation unit or can be a redeclaration of an extern "C" declaration
  6633. // in another scope.
  6634. if (isIncompleteDeclExternC(S,ND))
  6635. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6636. // Neither global nor extern "C": nothing to do.
  6637. return false;
  6638. }
  6639. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6640. // If the decl is already known invalid, don't check it.
  6641. if (NewVD->isInvalidDecl())
  6642. return;
  6643. QualType T = NewVD->getType();
  6644. // Defer checking an 'auto' type until its initializer is attached.
  6645. if (T->isUndeducedType())
  6646. return;
  6647. if (NewVD->hasAttrs())
  6648. CheckAlignasUnderalignment(NewVD);
  6649. if (T->isObjCObjectType()) {
  6650. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6651. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6652. T = Context.getObjCObjectPointerType(T);
  6653. NewVD->setType(T);
  6654. }
  6655. // Emit an error if an address space was applied to decl with local storage.
  6656. // This includes arrays of objects with address space qualifiers, but not
  6657. // automatic variables that point to other address spaces.
  6658. // ISO/IEC TR 18037 S5.1.2
  6659. if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
  6660. T.getAddressSpace() != LangAS::Default) {
  6661. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  6662. NewVD->setInvalidDecl();
  6663. return;
  6664. }
  6665. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6666. // scope.
  6667. if (getLangOpts().OpenCLVersion == 120 &&
  6668. !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
  6669. NewVD->isStaticLocal()) {
  6670. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6671. NewVD->setInvalidDecl();
  6672. return;
  6673. }
  6674. if (getLangOpts().OpenCL) {
  6675. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6676. if (NewVD->hasAttr<BlocksAttr>()) {
  6677. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6678. return;
  6679. }
  6680. if (T->isBlockPointerType()) {
  6681. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6682. // can't use 'extern' storage class.
  6683. if (!T.isConstQualified()) {
  6684. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6685. << 0 /*const*/;
  6686. NewVD->setInvalidDecl();
  6687. return;
  6688. }
  6689. if (NewVD->hasExternalStorage()) {
  6690. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6691. NewVD->setInvalidDecl();
  6692. return;
  6693. }
  6694. }
  6695. // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
  6696. // __constant address space.
  6697. // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
  6698. // variables inside a function can also be declared in the global
  6699. // address space.
  6700. // C++ for OpenCL inherits rule from OpenCL C v2.0.
  6701. // FIXME: Adding local AS in C++ for OpenCL might make sense.
  6702. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6703. NewVD->hasExternalStorage()) {
  6704. if (!T->isSamplerT() &&
  6705. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6706. (T.getAddressSpace() == LangAS::opencl_global &&
  6707. (getLangOpts().OpenCLVersion == 200 ||
  6708. getLangOpts().OpenCLCPlusPlus)))) {
  6709. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6710. if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
  6711. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6712. << Scope << "global or constant";
  6713. else
  6714. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6715. << Scope << "constant";
  6716. NewVD->setInvalidDecl();
  6717. return;
  6718. }
  6719. } else {
  6720. if (T.getAddressSpace() == LangAS::opencl_global) {
  6721. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6722. << 1 /*is any function*/ << "global";
  6723. NewVD->setInvalidDecl();
  6724. return;
  6725. }
  6726. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6727. T.getAddressSpace() == LangAS::opencl_local) {
  6728. FunctionDecl *FD = getCurFunctionDecl();
  6729. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  6730. // in functions.
  6731. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6732. if (T.getAddressSpace() == LangAS::opencl_constant)
  6733. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6734. << 0 /*non-kernel only*/ << "constant";
  6735. else
  6736. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6737. << 0 /*non-kernel only*/ << "local";
  6738. NewVD->setInvalidDecl();
  6739. return;
  6740. }
  6741. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  6742. // in the outermost scope of a kernel function.
  6743. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  6744. if (!getCurScope()->isFunctionScope()) {
  6745. if (T.getAddressSpace() == LangAS::opencl_constant)
  6746. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6747. << "constant";
  6748. else
  6749. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6750. << "local";
  6751. NewVD->setInvalidDecl();
  6752. return;
  6753. }
  6754. }
  6755. } else if (T.getAddressSpace() != LangAS::opencl_private &&
  6756. // If we are parsing a template we didn't deduce an addr
  6757. // space yet.
  6758. T.getAddressSpace() != LangAS::Default) {
  6759. // Do not allow other address spaces on automatic variable.
  6760. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  6761. NewVD->setInvalidDecl();
  6762. return;
  6763. }
  6764. }
  6765. }
  6766. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6767. && !NewVD->hasAttr<BlocksAttr>()) {
  6768. if (getLangOpts().getGC() != LangOptions::NonGC)
  6769. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6770. else {
  6771. assert(!getLangOpts().ObjCAutoRefCount);
  6772. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6773. }
  6774. }
  6775. bool isVM = T->isVariablyModifiedType();
  6776. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6777. NewVD->hasAttr<BlocksAttr>())
  6778. setFunctionHasBranchProtectedScope();
  6779. if ((isVM && NewVD->hasLinkage()) ||
  6780. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6781. bool SizeIsNegative;
  6782. llvm::APSInt Oversized;
  6783. TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
  6784. NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
  6785. QualType FixedT;
  6786. if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
  6787. FixedT = FixedTInfo->getType();
  6788. else if (FixedTInfo) {
  6789. // Type and type-as-written are canonically different. We need to fix up
  6790. // both types separately.
  6791. FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  6792. Oversized);
  6793. }
  6794. if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
  6795. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6796. // FIXME: This won't give the correct result for
  6797. // int a[10][n];
  6798. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6799. if (NewVD->isFileVarDecl())
  6800. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6801. << SizeRange;
  6802. else if (NewVD->isStaticLocal())
  6803. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6804. << SizeRange;
  6805. else
  6806. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6807. << SizeRange;
  6808. NewVD->setInvalidDecl();
  6809. return;
  6810. }
  6811. if (!FixedTInfo) {
  6812. if (NewVD->isFileVarDecl())
  6813. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6814. else
  6815. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6816. NewVD->setInvalidDecl();
  6817. return;
  6818. }
  6819. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6820. NewVD->setType(FixedT);
  6821. NewVD->setTypeSourceInfo(FixedTInfo);
  6822. }
  6823. if (T->isVoidType()) {
  6824. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6825. // of objects and functions.
  6826. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6827. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6828. << T;
  6829. NewVD->setInvalidDecl();
  6830. return;
  6831. }
  6832. }
  6833. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6834. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6835. NewVD->setInvalidDecl();
  6836. return;
  6837. }
  6838. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6839. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6840. NewVD->setInvalidDecl();
  6841. return;
  6842. }
  6843. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6844. RequireLiteralType(NewVD->getLocation(), T,
  6845. diag::err_constexpr_var_non_literal)) {
  6846. NewVD->setInvalidDecl();
  6847. return;
  6848. }
  6849. }
  6850. /// Perform semantic checking on a newly-created variable
  6851. /// declaration.
  6852. ///
  6853. /// This routine performs all of the type-checking required for a
  6854. /// variable declaration once it has been built. It is used both to
  6855. /// check variables after they have been parsed and their declarators
  6856. /// have been translated into a declaration, and to check variables
  6857. /// that have been instantiated from a template.
  6858. ///
  6859. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6860. ///
  6861. /// Returns true if the variable declaration is a redeclaration.
  6862. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6863. CheckVariableDeclarationType(NewVD);
  6864. // If the decl is already known invalid, don't check it.
  6865. if (NewVD->isInvalidDecl())
  6866. return false;
  6867. // If we did not find anything by this name, look for a non-visible
  6868. // extern "C" declaration with the same name.
  6869. if (Previous.empty() &&
  6870. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6871. Previous.setShadowed();
  6872. if (!Previous.empty()) {
  6873. MergeVarDecl(NewVD, Previous);
  6874. return true;
  6875. }
  6876. return false;
  6877. }
  6878. namespace {
  6879. struct FindOverriddenMethod {
  6880. Sema *S;
  6881. CXXMethodDecl *Method;
  6882. /// Member lookup function that determines whether a given C++
  6883. /// method overrides a method in a base class, to be used with
  6884. /// CXXRecordDecl::lookupInBases().
  6885. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6886. RecordDecl *BaseRecord =
  6887. Specifier->getType()->castAs<RecordType>()->getDecl();
  6888. DeclarationName Name = Method->getDeclName();
  6889. // FIXME: Do we care about other names here too?
  6890. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6891. // We really want to find the base class destructor here.
  6892. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6893. CanQualType CT = S->Context.getCanonicalType(T);
  6894. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6895. }
  6896. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6897. Path.Decls = Path.Decls.slice(1)) {
  6898. NamedDecl *D = Path.Decls.front();
  6899. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6900. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6901. return true;
  6902. }
  6903. }
  6904. return false;
  6905. }
  6906. };
  6907. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6908. } // end anonymous namespace
  6909. /// Report an error regarding overriding, along with any relevant
  6910. /// overridden methods.
  6911. ///
  6912. /// \param DiagID the primary error to report.
  6913. /// \param MD the overriding method.
  6914. /// \param OEK which overrides to include as notes.
  6915. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6916. OverrideErrorKind OEK = OEK_All) {
  6917. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6918. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  6919. // This check (& the OEK parameter) could be replaced by a predicate, but
  6920. // without lambdas that would be overkill. This is still nicer than writing
  6921. // out the diag loop 3 times.
  6922. if ((OEK == OEK_All) ||
  6923. (OEK == OEK_NonDeleted && !O->isDeleted()) ||
  6924. (OEK == OEK_Deleted && O->isDeleted()))
  6925. S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
  6926. }
  6927. }
  6928. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6929. /// and if so, check that it's a valid override and remember it.
  6930. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6931. // Look for methods in base classes that this method might override.
  6932. CXXBasePaths Paths;
  6933. FindOverriddenMethod FOM;
  6934. FOM.Method = MD;
  6935. FOM.S = this;
  6936. bool hasDeletedOverridenMethods = false;
  6937. bool hasNonDeletedOverridenMethods = false;
  6938. bool AddedAny = false;
  6939. if (DC->lookupInBases(FOM, Paths)) {
  6940. for (auto *I : Paths.found_decls()) {
  6941. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6942. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6943. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6944. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6945. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6946. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6947. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6948. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  6949. AddedAny = true;
  6950. }
  6951. }
  6952. }
  6953. }
  6954. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  6955. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  6956. }
  6957. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  6958. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  6959. }
  6960. return AddedAny;
  6961. }
  6962. namespace {
  6963. // Struct for holding all of the extra arguments needed by
  6964. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  6965. struct ActOnFDArgs {
  6966. Scope *S;
  6967. Declarator &D;
  6968. MultiTemplateParamsArg TemplateParamLists;
  6969. bool AddToScope;
  6970. };
  6971. } // end anonymous namespace
  6972. namespace {
  6973. // Callback to only accept typo corrections that have a non-zero edit distance.
  6974. // Also only accept corrections that have the same parent decl.
  6975. class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
  6976. public:
  6977. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  6978. CXXRecordDecl *Parent)
  6979. : Context(Context), OriginalFD(TypoFD),
  6980. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  6981. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6982. if (candidate.getEditDistance() == 0)
  6983. return false;
  6984. SmallVector<unsigned, 1> MismatchedParams;
  6985. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  6986. CDeclEnd = candidate.end();
  6987. CDecl != CDeclEnd; ++CDecl) {
  6988. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6989. if (FD && !FD->hasBody() &&
  6990. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  6991. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  6992. CXXRecordDecl *Parent = MD->getParent();
  6993. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  6994. return true;
  6995. } else if (!ExpectedParent) {
  6996. return true;
  6997. }
  6998. }
  6999. }
  7000. return false;
  7001. }
  7002. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  7003. return std::make_unique<DifferentNameValidatorCCC>(*this);
  7004. }
  7005. private:
  7006. ASTContext &Context;
  7007. FunctionDecl *OriginalFD;
  7008. CXXRecordDecl *ExpectedParent;
  7009. };
  7010. } // end anonymous namespace
  7011. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  7012. TypoCorrectedFunctionDefinitions.insert(F);
  7013. }
  7014. /// Generate diagnostics for an invalid function redeclaration.
  7015. ///
  7016. /// This routine handles generating the diagnostic messages for an invalid
  7017. /// function redeclaration, including finding possible similar declarations
  7018. /// or performing typo correction if there are no previous declarations with
  7019. /// the same name.
  7020. ///
  7021. /// Returns a NamedDecl iff typo correction was performed and substituting in
  7022. /// the new declaration name does not cause new errors.
  7023. static NamedDecl *DiagnoseInvalidRedeclaration(
  7024. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  7025. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  7026. DeclarationName Name = NewFD->getDeclName();
  7027. DeclContext *NewDC = NewFD->getDeclContext();
  7028. SmallVector<unsigned, 1> MismatchedParams;
  7029. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  7030. TypoCorrection Correction;
  7031. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  7032. unsigned DiagMsg =
  7033. IsLocalFriend ? diag::err_no_matching_local_friend :
  7034. NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
  7035. diag::err_member_decl_does_not_match;
  7036. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  7037. IsLocalFriend ? Sema::LookupLocalFriendName
  7038. : Sema::LookupOrdinaryName,
  7039. Sema::ForVisibleRedeclaration);
  7040. NewFD->setInvalidDecl();
  7041. if (IsLocalFriend)
  7042. SemaRef.LookupName(Prev, S);
  7043. else
  7044. SemaRef.LookupQualifiedName(Prev, NewDC);
  7045. assert(!Prev.isAmbiguous() &&
  7046. "Cannot have an ambiguity in previous-declaration lookup");
  7047. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  7048. DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
  7049. MD ? MD->getParent() : nullptr);
  7050. if (!Prev.empty()) {
  7051. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  7052. Func != FuncEnd; ++Func) {
  7053. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  7054. if (FD &&
  7055. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  7056. // Add 1 to the index so that 0 can mean the mismatch didn't
  7057. // involve a parameter
  7058. unsigned ParamNum =
  7059. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  7060. NearMatches.push_back(std::make_pair(FD, ParamNum));
  7061. }
  7062. }
  7063. // If the qualified name lookup yielded nothing, try typo correction
  7064. } else if ((Correction = SemaRef.CorrectTypo(
  7065. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  7066. &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
  7067. IsLocalFriend ? nullptr : NewDC))) {
  7068. // Set up everything for the call to ActOnFunctionDeclarator
  7069. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  7070. ExtraArgs.D.getIdentifierLoc());
  7071. Previous.clear();
  7072. Previous.setLookupName(Correction.getCorrection());
  7073. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  7074. CDeclEnd = Correction.end();
  7075. CDecl != CDeclEnd; ++CDecl) {
  7076. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  7077. if (FD && !FD->hasBody() &&
  7078. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  7079. Previous.addDecl(FD);
  7080. }
  7081. }
  7082. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  7083. NamedDecl *Result;
  7084. // Retry building the function declaration with the new previous
  7085. // declarations, and with errors suppressed.
  7086. {
  7087. // Trap errors.
  7088. Sema::SFINAETrap Trap(SemaRef);
  7089. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  7090. // pieces need to verify the typo-corrected C++ declaration and hopefully
  7091. // eliminate the need for the parameter pack ExtraArgs.
  7092. Result = SemaRef.ActOnFunctionDeclarator(
  7093. ExtraArgs.S, ExtraArgs.D,
  7094. Correction.getCorrectionDecl()->getDeclContext(),
  7095. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  7096. ExtraArgs.AddToScope);
  7097. if (Trap.hasErrorOccurred())
  7098. Result = nullptr;
  7099. }
  7100. if (Result) {
  7101. // Determine which correction we picked.
  7102. Decl *Canonical = Result->getCanonicalDecl();
  7103. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  7104. I != E; ++I)
  7105. if ((*I)->getCanonicalDecl() == Canonical)
  7106. Correction.setCorrectionDecl(*I);
  7107. // Let Sema know about the correction.
  7108. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  7109. SemaRef.diagnoseTypo(
  7110. Correction,
  7111. SemaRef.PDiag(IsLocalFriend
  7112. ? diag::err_no_matching_local_friend_suggest
  7113. : diag::err_member_decl_does_not_match_suggest)
  7114. << Name << NewDC << IsDefinition);
  7115. return Result;
  7116. }
  7117. // Pretend the typo correction never occurred
  7118. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  7119. ExtraArgs.D.getIdentifierLoc());
  7120. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  7121. Previous.clear();
  7122. Previous.setLookupName(Name);
  7123. }
  7124. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  7125. << Name << NewDC << IsDefinition << NewFD->getLocation();
  7126. bool NewFDisConst = false;
  7127. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  7128. NewFDisConst = NewMD->isConst();
  7129. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  7130. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  7131. NearMatch != NearMatchEnd; ++NearMatch) {
  7132. FunctionDecl *FD = NearMatch->first;
  7133. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  7134. bool FDisConst = MD && MD->isConst();
  7135. bool IsMember = MD || !IsLocalFriend;
  7136. // FIXME: These notes are poorly worded for the local friend case.
  7137. if (unsigned Idx = NearMatch->second) {
  7138. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  7139. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  7140. if (Loc.isInvalid()) Loc = FD->getLocation();
  7141. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  7142. : diag::note_local_decl_close_param_match)
  7143. << Idx << FDParam->getType()
  7144. << NewFD->getParamDecl(Idx - 1)->getType();
  7145. } else if (FDisConst != NewFDisConst) {
  7146. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  7147. << NewFDisConst << FD->getSourceRange().getEnd();
  7148. } else
  7149. SemaRef.Diag(FD->getLocation(),
  7150. IsMember ? diag::note_member_def_close_match
  7151. : diag::note_local_decl_close_match);
  7152. }
  7153. return nullptr;
  7154. }
  7155. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  7156. switch (D.getDeclSpec().getStorageClassSpec()) {
  7157. default: llvm_unreachable("Unknown storage class!");
  7158. case DeclSpec::SCS_auto:
  7159. case DeclSpec::SCS_register:
  7160. case DeclSpec::SCS_mutable:
  7161. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7162. diag::err_typecheck_sclass_func);
  7163. D.getMutableDeclSpec().ClearStorageClassSpecs();
  7164. D.setInvalidType();
  7165. break;
  7166. case DeclSpec::SCS_unspecified: break;
  7167. case DeclSpec::SCS_extern:
  7168. if (D.getDeclSpec().isExternInLinkageSpec())
  7169. return SC_None;
  7170. return SC_Extern;
  7171. case DeclSpec::SCS_static: {
  7172. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  7173. // C99 6.7.1p5:
  7174. // The declaration of an identifier for a function that has
  7175. // block scope shall have no explicit storage-class specifier
  7176. // other than extern
  7177. // See also (C++ [dcl.stc]p4).
  7178. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7179. diag::err_static_block_func);
  7180. break;
  7181. } else
  7182. return SC_Static;
  7183. }
  7184. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  7185. }
  7186. // No explicit storage class has already been returned
  7187. return SC_None;
  7188. }
  7189. static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  7190. DeclContext *DC, QualType &R,
  7191. TypeSourceInfo *TInfo,
  7192. StorageClass SC,
  7193. bool &IsVirtualOkay) {
  7194. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  7195. DeclarationName Name = NameInfo.getName();
  7196. FunctionDecl *NewFD = nullptr;
  7197. bool isInline = D.getDeclSpec().isInlineSpecified();
  7198. if (!SemaRef.getLangOpts().CPlusPlus) {
  7199. // Determine whether the function was written with a
  7200. // prototype. This true when:
  7201. // - there is a prototype in the declarator, or
  7202. // - the type R of the function is some kind of typedef or other non-
  7203. // attributed reference to a type name (which eventually refers to a
  7204. // function type).
  7205. bool HasPrototype =
  7206. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  7207. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  7208. NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7209. R, TInfo, SC, isInline, HasPrototype,
  7210. CSK_unspecified);
  7211. if (D.isInvalidType())
  7212. NewFD->setInvalidDecl();
  7213. return NewFD;
  7214. }
  7215. ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
  7216. ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
  7217. if (ConstexprKind == CSK_constinit) {
  7218. SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
  7219. diag::err_constexpr_wrong_decl_kind)
  7220. << ConstexprKind;
  7221. ConstexprKind = CSK_unspecified;
  7222. D.getMutableDeclSpec().ClearConstexprSpec();
  7223. }
  7224. // Check that the return type is not an abstract class type.
  7225. // For record types, this is done by the AbstractClassUsageDiagnoser once
  7226. // the class has been completely parsed.
  7227. if (!DC->isRecord() &&
  7228. SemaRef.RequireNonAbstractType(
  7229. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  7230. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  7231. D.setInvalidType();
  7232. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  7233. // This is a C++ constructor declaration.
  7234. assert(DC->isRecord() &&
  7235. "Constructors can only be declared in a member context");
  7236. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  7237. return CXXConstructorDecl::Create(
  7238. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7239. TInfo, ExplicitSpecifier, isInline,
  7240. /*isImplicitlyDeclared=*/false, ConstexprKind);
  7241. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7242. // This is a C++ destructor declaration.
  7243. if (DC->isRecord()) {
  7244. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  7245. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  7246. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  7247. SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
  7248. isInline,
  7249. /*isImplicitlyDeclared=*/false, ConstexprKind);
  7250. // If the destructor needs an implicit exception specification, set it
  7251. // now. FIXME: It'd be nice to be able to create the right type to start
  7252. // with, but the type needs to reference the destructor declaration.
  7253. if (SemaRef.getLangOpts().CPlusPlus11)
  7254. SemaRef.AdjustDestructorExceptionSpec(NewDD);
  7255. IsVirtualOkay = true;
  7256. return NewDD;
  7257. } else {
  7258. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  7259. D.setInvalidType();
  7260. // Create a FunctionDecl to satisfy the function definition parsing
  7261. // code path.
  7262. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7263. D.getIdentifierLoc(), Name, R, TInfo, SC,
  7264. isInline,
  7265. /*hasPrototype=*/true, ConstexprKind);
  7266. }
  7267. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  7268. if (!DC->isRecord()) {
  7269. SemaRef.Diag(D.getIdentifierLoc(),
  7270. diag::err_conv_function_not_member);
  7271. return nullptr;
  7272. }
  7273. SemaRef.CheckConversionDeclarator(D, R, SC);
  7274. IsVirtualOkay = true;
  7275. return CXXConversionDecl::Create(
  7276. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7277. TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
  7278. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7279. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  7280. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7281. ExplicitSpecifier, NameInfo, R, TInfo,
  7282. D.getEndLoc());
  7283. } else if (DC->isRecord()) {
  7284. // If the name of the function is the same as the name of the record,
  7285. // then this must be an invalid constructor that has a return type.
  7286. // (The parser checks for a return type and makes the declarator a
  7287. // constructor if it has no return type).
  7288. if (Name.getAsIdentifierInfo() &&
  7289. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  7290. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  7291. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7292. << SourceRange(D.getIdentifierLoc());
  7293. return nullptr;
  7294. }
  7295. // This is a C++ method declaration.
  7296. CXXMethodDecl *Ret = CXXMethodDecl::Create(
  7297. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7298. TInfo, SC, isInline, ConstexprKind, SourceLocation());
  7299. IsVirtualOkay = !Ret->isStatic();
  7300. return Ret;
  7301. } else {
  7302. bool isFriend =
  7303. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  7304. if (!isFriend && SemaRef.CurContext->isRecord())
  7305. return nullptr;
  7306. // Determine whether the function was written with a
  7307. // prototype. This true when:
  7308. // - we're in C++ (where every function has a prototype),
  7309. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7310. R, TInfo, SC, isInline, true /*HasPrototype*/,
  7311. ConstexprKind);
  7312. }
  7313. }
  7314. enum OpenCLParamType {
  7315. ValidKernelParam,
  7316. PtrPtrKernelParam,
  7317. PtrKernelParam,
  7318. InvalidAddrSpacePtrKernelParam,
  7319. InvalidKernelParam,
  7320. RecordKernelParam
  7321. };
  7322. static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
  7323. // Size dependent types are just typedefs to normal integer types
  7324. // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
  7325. // integers other than by their names.
  7326. StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
  7327. // Remove typedefs one by one until we reach a typedef
  7328. // for a size dependent type.
  7329. QualType DesugaredTy = Ty;
  7330. do {
  7331. ArrayRef<StringRef> Names(SizeTypeNames);
  7332. auto Match = llvm::find(Names, DesugaredTy.getAsString());
  7333. if (Names.end() != Match)
  7334. return true;
  7335. Ty = DesugaredTy;
  7336. DesugaredTy = Ty.getSingleStepDesugaredType(C);
  7337. } while (DesugaredTy != Ty);
  7338. return false;
  7339. }
  7340. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  7341. if (PT->isPointerType()) {
  7342. QualType PointeeType = PT->getPointeeType();
  7343. if (PointeeType->isPointerType())
  7344. return PtrPtrKernelParam;
  7345. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  7346. PointeeType.getAddressSpace() == LangAS::opencl_private ||
  7347. PointeeType.getAddressSpace() == LangAS::Default)
  7348. return InvalidAddrSpacePtrKernelParam;
  7349. return PtrKernelParam;
  7350. }
  7351. // OpenCL v1.2 s6.9.k:
  7352. // Arguments to kernel functions in a program cannot be declared with the
  7353. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7354. // uintptr_t or a struct and/or union that contain fields declared to be one
  7355. // of these built-in scalar types.
  7356. if (isOpenCLSizeDependentType(S.getASTContext(), PT))
  7357. return InvalidKernelParam;
  7358. if (PT->isImageType())
  7359. return PtrKernelParam;
  7360. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  7361. return InvalidKernelParam;
  7362. // OpenCL extension spec v1.2 s9.5:
  7363. // This extension adds support for half scalar and vector types as built-in
  7364. // types that can be used for arithmetic operations, conversions etc.
  7365. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
  7366. return InvalidKernelParam;
  7367. if (PT->isRecordType())
  7368. return RecordKernelParam;
  7369. // Look into an array argument to check if it has a forbidden type.
  7370. if (PT->isArrayType()) {
  7371. const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
  7372. // Call ourself to check an underlying type of an array. Since the
  7373. // getPointeeOrArrayElementType returns an innermost type which is not an
  7374. // array, this recursive call only happens once.
  7375. return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
  7376. }
  7377. return ValidKernelParam;
  7378. }
  7379. static void checkIsValidOpenCLKernelParameter(
  7380. Sema &S,
  7381. Declarator &D,
  7382. ParmVarDecl *Param,
  7383. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  7384. QualType PT = Param->getType();
  7385. // Cache the valid types we encounter to avoid rechecking structs that are
  7386. // used again
  7387. if (ValidTypes.count(PT.getTypePtr()))
  7388. return;
  7389. switch (getOpenCLKernelParameterType(S, PT)) {
  7390. case PtrPtrKernelParam:
  7391. // OpenCL v1.2 s6.9.a:
  7392. // A kernel function argument cannot be declared as a
  7393. // pointer to a pointer type.
  7394. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  7395. D.setInvalidType();
  7396. return;
  7397. case InvalidAddrSpacePtrKernelParam:
  7398. // OpenCL v1.0 s6.5:
  7399. // __kernel function arguments declared to be a pointer of a type can point
  7400. // to one of the following address spaces only : __global, __local or
  7401. // __constant.
  7402. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  7403. D.setInvalidType();
  7404. return;
  7405. // OpenCL v1.2 s6.9.k:
  7406. // Arguments to kernel functions in a program cannot be declared with the
  7407. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7408. // uintptr_t or a struct and/or union that contain fields declared to be
  7409. // one of these built-in scalar types.
  7410. case InvalidKernelParam:
  7411. // OpenCL v1.2 s6.8 n:
  7412. // A kernel function argument cannot be declared
  7413. // of event_t type.
  7414. // Do not diagnose half type since it is diagnosed as invalid argument
  7415. // type for any function elsewhere.
  7416. if (!PT->isHalfType()) {
  7417. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7418. // Explain what typedefs are involved.
  7419. const TypedefType *Typedef = nullptr;
  7420. while ((Typedef = PT->getAs<TypedefType>())) {
  7421. SourceLocation Loc = Typedef->getDecl()->getLocation();
  7422. // SourceLocation may be invalid for a built-in type.
  7423. if (Loc.isValid())
  7424. S.Diag(Loc, diag::note_entity_declared_at) << PT;
  7425. PT = Typedef->desugar();
  7426. }
  7427. }
  7428. D.setInvalidType();
  7429. return;
  7430. case PtrKernelParam:
  7431. case ValidKernelParam:
  7432. ValidTypes.insert(PT.getTypePtr());
  7433. return;
  7434. case RecordKernelParam:
  7435. break;
  7436. }
  7437. // Track nested structs we will inspect
  7438. SmallVector<const Decl *, 4> VisitStack;
  7439. // Track where we are in the nested structs. Items will migrate from
  7440. // VisitStack to HistoryStack as we do the DFS for bad field.
  7441. SmallVector<const FieldDecl *, 4> HistoryStack;
  7442. HistoryStack.push_back(nullptr);
  7443. // At this point we already handled everything except of a RecordType or
  7444. // an ArrayType of a RecordType.
  7445. assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
  7446. const RecordType *RecTy =
  7447. PT->getPointeeOrArrayElementType()->getAs<RecordType>();
  7448. const RecordDecl *OrigRecDecl = RecTy->getDecl();
  7449. VisitStack.push_back(RecTy->getDecl());
  7450. assert(VisitStack.back() && "First decl null?");
  7451. do {
  7452. const Decl *Next = VisitStack.pop_back_val();
  7453. if (!Next) {
  7454. assert(!HistoryStack.empty());
  7455. // Found a marker, we have gone up a level
  7456. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  7457. ValidTypes.insert(Hist->getType().getTypePtr());
  7458. continue;
  7459. }
  7460. // Adds everything except the original parameter declaration (which is not a
  7461. // field itself) to the history stack.
  7462. const RecordDecl *RD;
  7463. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  7464. HistoryStack.push_back(Field);
  7465. QualType FieldTy = Field->getType();
  7466. // Other field types (known to be valid or invalid) are handled while we
  7467. // walk around RecordDecl::fields().
  7468. assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
  7469. "Unexpected type.");
  7470. const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
  7471. RD = FieldRecTy->castAs<RecordType>()->getDecl();
  7472. } else {
  7473. RD = cast<RecordDecl>(Next);
  7474. }
  7475. // Add a null marker so we know when we've gone back up a level
  7476. VisitStack.push_back(nullptr);
  7477. for (const auto *FD : RD->fields()) {
  7478. QualType QT = FD->getType();
  7479. if (ValidTypes.count(QT.getTypePtr()))
  7480. continue;
  7481. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  7482. if (ParamType == ValidKernelParam)
  7483. continue;
  7484. if (ParamType == RecordKernelParam) {
  7485. VisitStack.push_back(FD);
  7486. continue;
  7487. }
  7488. // OpenCL v1.2 s6.9.p:
  7489. // Arguments to kernel functions that are declared to be a struct or union
  7490. // do not allow OpenCL objects to be passed as elements of the struct or
  7491. // union.
  7492. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  7493. ParamType == InvalidAddrSpacePtrKernelParam) {
  7494. S.Diag(Param->getLocation(),
  7495. diag::err_record_with_pointers_kernel_param)
  7496. << PT->isUnionType()
  7497. << PT;
  7498. } else {
  7499. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7500. }
  7501. S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
  7502. << OrigRecDecl->getDeclName();
  7503. // We have an error, now let's go back up through history and show where
  7504. // the offending field came from
  7505. for (ArrayRef<const FieldDecl *>::const_iterator
  7506. I = HistoryStack.begin() + 1,
  7507. E = HistoryStack.end();
  7508. I != E; ++I) {
  7509. const FieldDecl *OuterField = *I;
  7510. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  7511. << OuterField->getType();
  7512. }
  7513. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  7514. << QT->isPointerType()
  7515. << QT;
  7516. D.setInvalidType();
  7517. return;
  7518. }
  7519. } while (!VisitStack.empty());
  7520. }
  7521. /// Find the DeclContext in which a tag is implicitly declared if we see an
  7522. /// elaborated type specifier in the specified context, and lookup finds
  7523. /// nothing.
  7524. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  7525. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  7526. DC = DC->getParent();
  7527. return DC;
  7528. }
  7529. /// Find the Scope in which a tag is implicitly declared if we see an
  7530. /// elaborated type specifier in the specified context, and lookup finds
  7531. /// nothing.
  7532. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  7533. while (S->isClassScope() ||
  7534. (LangOpts.CPlusPlus &&
  7535. S->isFunctionPrototypeScope()) ||
  7536. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7537. (S->getEntity() && S->getEntity()->isTransparentContext()))
  7538. S = S->getParent();
  7539. return S;
  7540. }
  7541. NamedDecl*
  7542. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  7543. TypeSourceInfo *TInfo, LookupResult &Previous,
  7544. MultiTemplateParamsArg TemplateParamLists,
  7545. bool &AddToScope) {
  7546. QualType R = TInfo->getType();
  7547. assert(R->isFunctionType());
  7548. // TODO: consider using NameInfo for diagnostic.
  7549. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7550. DeclarationName Name = NameInfo.getName();
  7551. StorageClass SC = getFunctionStorageClass(*this, D);
  7552. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  7553. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  7554. diag::err_invalid_thread)
  7555. << DeclSpec::getSpecifierName(TSCS);
  7556. if (D.isFirstDeclarationOfMember())
  7557. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  7558. D.getIdentifierLoc());
  7559. bool isFriend = false;
  7560. FunctionTemplateDecl *FunctionTemplate = nullptr;
  7561. bool isMemberSpecialization = false;
  7562. bool isFunctionTemplateSpecialization = false;
  7563. bool isDependentClassScopeExplicitSpecialization = false;
  7564. bool HasExplicitTemplateArgs = false;
  7565. TemplateArgumentListInfo TemplateArgs;
  7566. bool isVirtualOkay = false;
  7567. DeclContext *OriginalDC = DC;
  7568. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  7569. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  7570. isVirtualOkay);
  7571. if (!NewFD) return nullptr;
  7572. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  7573. NewFD->setTopLevelDeclInObjCContainer();
  7574. // Set the lexical context. If this is a function-scope declaration, or has a
  7575. // C++ scope specifier, or is the object of a friend declaration, the lexical
  7576. // context will be different from the semantic context.
  7577. NewFD->setLexicalDeclContext(CurContext);
  7578. if (IsLocalExternDecl)
  7579. NewFD->setLocalExternDecl();
  7580. if (getLangOpts().CPlusPlus) {
  7581. bool isInline = D.getDeclSpec().isInlineSpecified();
  7582. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7583. bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
  7584. isFriend = D.getDeclSpec().isFriendSpecified();
  7585. if (isFriend && !isInline && D.isFunctionDefinition()) {
  7586. // C++ [class.friend]p5
  7587. // A function can be defined in a friend declaration of a
  7588. // class . . . . Such a function is implicitly inline.
  7589. NewFD->setImplicitlyInline();
  7590. }
  7591. // If this is a method defined in an __interface, and is not a constructor
  7592. // or an overloaded operator, then set the pure flag (isVirtual will already
  7593. // return true).
  7594. if (const CXXRecordDecl *Parent =
  7595. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  7596. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  7597. NewFD->setPure(true);
  7598. // C++ [class.union]p2
  7599. // A union can have member functions, but not virtual functions.
  7600. if (isVirtual && Parent->isUnion())
  7601. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  7602. }
  7603. SetNestedNameSpecifier(*this, NewFD, D);
  7604. isMemberSpecialization = false;
  7605. isFunctionTemplateSpecialization = false;
  7606. if (D.isInvalidType())
  7607. NewFD->setInvalidDecl();
  7608. // Match up the template parameter lists with the scope specifier, then
  7609. // determine whether we have a template or a template specialization.
  7610. bool Invalid = false;
  7611. if (TemplateParameterList *TemplateParams =
  7612. MatchTemplateParametersToScopeSpecifier(
  7613. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  7614. D.getCXXScopeSpec(),
  7615. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  7616. ? D.getName().TemplateId
  7617. : nullptr,
  7618. TemplateParamLists, isFriend, isMemberSpecialization,
  7619. Invalid)) {
  7620. if (TemplateParams->size() > 0) {
  7621. // This is a function template
  7622. // Check that we can declare a template here.
  7623. if (CheckTemplateDeclScope(S, TemplateParams))
  7624. NewFD->setInvalidDecl();
  7625. // A destructor cannot be a template.
  7626. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7627. Diag(NewFD->getLocation(), diag::err_destructor_template);
  7628. NewFD->setInvalidDecl();
  7629. }
  7630. // If we're adding a template to a dependent context, we may need to
  7631. // rebuilding some of the types used within the template parameter list,
  7632. // now that we know what the current instantiation is.
  7633. if (DC->isDependentContext()) {
  7634. ContextRAII SavedContext(*this, DC);
  7635. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  7636. Invalid = true;
  7637. }
  7638. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  7639. NewFD->getLocation(),
  7640. Name, TemplateParams,
  7641. NewFD);
  7642. FunctionTemplate->setLexicalDeclContext(CurContext);
  7643. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  7644. // For source fidelity, store the other template param lists.
  7645. if (TemplateParamLists.size() > 1) {
  7646. NewFD->setTemplateParameterListsInfo(Context,
  7647. TemplateParamLists.drop_back(1));
  7648. }
  7649. } else {
  7650. // This is a function template specialization.
  7651. isFunctionTemplateSpecialization = true;
  7652. // For source fidelity, store all the template param lists.
  7653. if (TemplateParamLists.size() > 0)
  7654. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7655. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  7656. if (isFriend) {
  7657. // We want to remove the "template<>", found here.
  7658. SourceRange RemoveRange = TemplateParams->getSourceRange();
  7659. // If we remove the template<> and the name is not a
  7660. // template-id, we're actually silently creating a problem:
  7661. // the friend declaration will refer to an untemplated decl,
  7662. // and clearly the user wants a template specialization. So
  7663. // we need to insert '<>' after the name.
  7664. SourceLocation InsertLoc;
  7665. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  7666. InsertLoc = D.getName().getSourceRange().getEnd();
  7667. InsertLoc = getLocForEndOfToken(InsertLoc);
  7668. }
  7669. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  7670. << Name << RemoveRange
  7671. << FixItHint::CreateRemoval(RemoveRange)
  7672. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7673. }
  7674. }
  7675. } else {
  7676. // All template param lists were matched against the scope specifier:
  7677. // this is NOT (an explicit specialization of) a template.
  7678. if (TemplateParamLists.size() > 0)
  7679. // For source fidelity, store all the template param lists.
  7680. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7681. }
  7682. if (Invalid) {
  7683. NewFD->setInvalidDecl();
  7684. if (FunctionTemplate)
  7685. FunctionTemplate->setInvalidDecl();
  7686. }
  7687. // C++ [dcl.fct.spec]p5:
  7688. // The virtual specifier shall only be used in declarations of
  7689. // nonstatic class member functions that appear within a
  7690. // member-specification of a class declaration; see 10.3.
  7691. //
  7692. if (isVirtual && !NewFD->isInvalidDecl()) {
  7693. if (!isVirtualOkay) {
  7694. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7695. diag::err_virtual_non_function);
  7696. } else if (!CurContext->isRecord()) {
  7697. // 'virtual' was specified outside of the class.
  7698. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7699. diag::err_virtual_out_of_class)
  7700. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7701. } else if (NewFD->getDescribedFunctionTemplate()) {
  7702. // C++ [temp.mem]p3:
  7703. // A member function template shall not be virtual.
  7704. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7705. diag::err_virtual_member_function_template)
  7706. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7707. } else {
  7708. // Okay: Add virtual to the method.
  7709. NewFD->setVirtualAsWritten(true);
  7710. }
  7711. if (getLangOpts().CPlusPlus14 &&
  7712. NewFD->getReturnType()->isUndeducedType())
  7713. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7714. }
  7715. if (getLangOpts().CPlusPlus14 &&
  7716. (NewFD->isDependentContext() ||
  7717. (isFriend && CurContext->isDependentContext())) &&
  7718. NewFD->getReturnType()->isUndeducedType()) {
  7719. // If the function template is referenced directly (for instance, as a
  7720. // member of the current instantiation), pretend it has a dependent type.
  7721. // This is not really justified by the standard, but is the only sane
  7722. // thing to do.
  7723. // FIXME: For a friend function, we have not marked the function as being
  7724. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7725. const FunctionProtoType *FPT =
  7726. NewFD->getType()->castAs<FunctionProtoType>();
  7727. QualType Result =
  7728. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7729. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7730. FPT->getExtProtoInfo()));
  7731. }
  7732. // C++ [dcl.fct.spec]p3:
  7733. // The inline specifier shall not appear on a block scope function
  7734. // declaration.
  7735. if (isInline && !NewFD->isInvalidDecl()) {
  7736. if (CurContext->isFunctionOrMethod()) {
  7737. // 'inline' is not allowed on block scope function declaration.
  7738. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7739. diag::err_inline_declaration_block_scope) << Name
  7740. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7741. }
  7742. }
  7743. // C++ [dcl.fct.spec]p6:
  7744. // The explicit specifier shall be used only in the declaration of a
  7745. // constructor or conversion function within its class definition;
  7746. // see 12.3.1 and 12.3.2.
  7747. if (hasExplicit && !NewFD->isInvalidDecl() &&
  7748. !isa<CXXDeductionGuideDecl>(NewFD)) {
  7749. if (!CurContext->isRecord()) {
  7750. // 'explicit' was specified outside of the class.
  7751. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7752. diag::err_explicit_out_of_class)
  7753. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7754. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7755. !isa<CXXConversionDecl>(NewFD)) {
  7756. // 'explicit' was specified on a function that wasn't a constructor
  7757. // or conversion function.
  7758. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7759. diag::err_explicit_non_ctor_or_conv_function)
  7760. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7761. }
  7762. }
  7763. if (ConstexprSpecKind ConstexprKind =
  7764. D.getDeclSpec().getConstexprSpecifier()) {
  7765. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7766. // are implicitly inline.
  7767. NewFD->setImplicitlyInline();
  7768. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7769. // be either constructors or to return a literal type. Therefore,
  7770. // destructors cannot be declared constexpr.
  7771. if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
  7772. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
  7773. << ConstexprKind;
  7774. }
  7775. }
  7776. // If __module_private__ was specified, mark the function accordingly.
  7777. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7778. if (isFunctionTemplateSpecialization) {
  7779. SourceLocation ModulePrivateLoc
  7780. = D.getDeclSpec().getModulePrivateSpecLoc();
  7781. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7782. << 0
  7783. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7784. } else {
  7785. NewFD->setModulePrivate();
  7786. if (FunctionTemplate)
  7787. FunctionTemplate->setModulePrivate();
  7788. }
  7789. }
  7790. if (isFriend) {
  7791. if (FunctionTemplate) {
  7792. FunctionTemplate->setObjectOfFriendDecl();
  7793. FunctionTemplate->setAccess(AS_public);
  7794. }
  7795. NewFD->setObjectOfFriendDecl();
  7796. NewFD->setAccess(AS_public);
  7797. }
  7798. // If a function is defined as defaulted or deleted, mark it as such now.
  7799. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7800. // definition kind to FDK_Definition.
  7801. switch (D.getFunctionDefinitionKind()) {
  7802. case FDK_Declaration:
  7803. case FDK_Definition:
  7804. break;
  7805. case FDK_Defaulted:
  7806. NewFD->setDefaulted();
  7807. break;
  7808. case FDK_Deleted:
  7809. NewFD->setDeletedAsWritten();
  7810. break;
  7811. }
  7812. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7813. D.isFunctionDefinition()) {
  7814. // C++ [class.mfct]p2:
  7815. // A member function may be defined (8.4) in its class definition, in
  7816. // which case it is an inline member function (7.1.2)
  7817. NewFD->setImplicitlyInline();
  7818. }
  7819. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7820. !CurContext->isRecord()) {
  7821. // C++ [class.static]p1:
  7822. // A data or function member of a class may be declared static
  7823. // in a class definition, in which case it is a static member of
  7824. // the class.
  7825. // Complain about the 'static' specifier if it's on an out-of-line
  7826. // member function definition.
  7827. // MSVC permits the use of a 'static' storage specifier on an out-of-line
  7828. // member function template declaration and class member template
  7829. // declaration (MSVC versions before 2015), warn about this.
  7830. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7831. ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  7832. cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
  7833. (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
  7834. ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
  7835. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7836. }
  7837. // C++11 [except.spec]p15:
  7838. // A deallocation function with no exception-specification is treated
  7839. // as if it were specified with noexcept(true).
  7840. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7841. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7842. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7843. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7844. NewFD->setType(Context.getFunctionType(
  7845. FPT->getReturnType(), FPT->getParamTypes(),
  7846. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7847. }
  7848. // Filter out previous declarations that don't match the scope.
  7849. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7850. D.getCXXScopeSpec().isNotEmpty() ||
  7851. isMemberSpecialization ||
  7852. isFunctionTemplateSpecialization);
  7853. // Handle GNU asm-label extension (encoded as an attribute).
  7854. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7855. // The parser guarantees this is a string.
  7856. StringLiteral *SE = cast<StringLiteral>(E);
  7857. NewFD->addAttr(::new (Context)
  7858. AsmLabelAttr(Context, SE->getStrTokenLoc(0),
  7859. SE->getString(), /*IsLiteralLabel=*/true));
  7860. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7861. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7862. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7863. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7864. if (isDeclExternC(NewFD)) {
  7865. NewFD->addAttr(I->second);
  7866. ExtnameUndeclaredIdentifiers.erase(I);
  7867. } else
  7868. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7869. << /*Variable*/0 << NewFD;
  7870. }
  7871. }
  7872. // Copy the parameter declarations from the declarator D to the function
  7873. // declaration NewFD, if they are available. First scavenge them into Params.
  7874. SmallVector<ParmVarDecl*, 16> Params;
  7875. unsigned FTIIdx;
  7876. if (D.isFunctionDeclarator(FTIIdx)) {
  7877. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  7878. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7879. // function that takes no arguments, not a function that takes a
  7880. // single void argument.
  7881. // We let through "const void" here because Sema::GetTypeForDeclarator
  7882. // already checks for that case.
  7883. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7884. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7885. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7886. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7887. Param->setDeclContext(NewFD);
  7888. Params.push_back(Param);
  7889. if (Param->isInvalidDecl())
  7890. NewFD->setInvalidDecl();
  7891. }
  7892. }
  7893. if (!getLangOpts().CPlusPlus) {
  7894. // In C, find all the tag declarations from the prototype and move them
  7895. // into the function DeclContext. Remove them from the surrounding tag
  7896. // injection context of the function, which is typically but not always
  7897. // the TU.
  7898. DeclContext *PrototypeTagContext =
  7899. getTagInjectionContext(NewFD->getLexicalDeclContext());
  7900. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  7901. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  7902. // We don't want to reparent enumerators. Look at their parent enum
  7903. // instead.
  7904. if (!TD) {
  7905. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  7906. TD = cast<EnumDecl>(ECD->getDeclContext());
  7907. }
  7908. if (!TD)
  7909. continue;
  7910. DeclContext *TagDC = TD->getLexicalDeclContext();
  7911. if (!TagDC->containsDecl(TD))
  7912. continue;
  7913. TagDC->removeDecl(TD);
  7914. TD->setDeclContext(NewFD);
  7915. NewFD->addDecl(TD);
  7916. // Preserve the lexical DeclContext if it is not the surrounding tag
  7917. // injection context of the FD. In this example, the semantic context of
  7918. // E will be f and the lexical context will be S, while both the
  7919. // semantic and lexical contexts of S will be f:
  7920. // void f(struct S { enum E { a } f; } s);
  7921. if (TagDC != PrototypeTagContext)
  7922. TD->setLexicalDeclContext(TagDC);
  7923. }
  7924. }
  7925. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7926. // When we're declaring a function with a typedef, typeof, etc as in the
  7927. // following example, we'll need to synthesize (unnamed)
  7928. // parameters for use in the declaration.
  7929. //
  7930. // @code
  7931. // typedef void fn(int);
  7932. // fn f;
  7933. // @endcode
  7934. // Synthesize a parameter for each argument type.
  7935. for (const auto &AI : FT->param_types()) {
  7936. ParmVarDecl *Param =
  7937. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7938. Param->setScopeInfo(0, Params.size());
  7939. Params.push_back(Param);
  7940. }
  7941. } else {
  7942. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7943. "Should not need args for typedef of non-prototype fn");
  7944. }
  7945. // Finally, we know we have the right number of parameters, install them.
  7946. NewFD->setParams(Params);
  7947. if (D.getDeclSpec().isNoreturnSpecified())
  7948. NewFD->addAttr(C11NoReturnAttr::Create(Context,
  7949. D.getDeclSpec().getNoreturnSpecLoc(),
  7950. AttributeCommonInfo::AS_Keyword));
  7951. // Functions returning a variably modified type violate C99 6.7.5.2p2
  7952. // because all functions have linkage.
  7953. if (!NewFD->isInvalidDecl() &&
  7954. NewFD->getReturnType()->isVariablyModifiedType()) {
  7955. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  7956. NewFD->setInvalidDecl();
  7957. }
  7958. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  7959. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  7960. !NewFD->hasAttr<SectionAttr>())
  7961. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
  7962. Context, PragmaClangTextSection.SectionName,
  7963. PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
  7964. // Apply an implicit SectionAttr if #pragma code_seg is active.
  7965. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  7966. !NewFD->hasAttr<SectionAttr>()) {
  7967. NewFD->addAttr(SectionAttr::CreateImplicit(
  7968. Context, CodeSegStack.CurrentValue->getString(),
  7969. CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
  7970. SectionAttr::Declspec_allocate));
  7971. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  7972. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  7973. ASTContext::PSF_Read,
  7974. NewFD))
  7975. NewFD->dropAttr<SectionAttr>();
  7976. }
  7977. // Apply an implicit CodeSegAttr from class declspec or
  7978. // apply an implicit SectionAttr from #pragma code_seg if active.
  7979. if (!NewFD->hasAttr<CodeSegAttr>()) {
  7980. if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
  7981. D.isFunctionDefinition())) {
  7982. NewFD->addAttr(SAttr);
  7983. }
  7984. }
  7985. // Handle attributes.
  7986. ProcessDeclAttributes(S, NewFD, D);
  7987. if (getLangOpts().OpenCL) {
  7988. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  7989. // type declaration will generate a compilation error.
  7990. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  7991. if (AddressSpace != LangAS::Default) {
  7992. Diag(NewFD->getLocation(),
  7993. diag::err_opencl_return_value_with_address_space);
  7994. NewFD->setInvalidDecl();
  7995. }
  7996. }
  7997. if (!getLangOpts().CPlusPlus) {
  7998. // Perform semantic checking on the function declaration.
  7999. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  8000. CheckMain(NewFD, D.getDeclSpec());
  8001. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  8002. CheckMSVCRTEntryPoint(NewFD);
  8003. if (!NewFD->isInvalidDecl())
  8004. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  8005. isMemberSpecialization));
  8006. else if (!Previous.empty())
  8007. // Recover gracefully from an invalid redeclaration.
  8008. D.setRedeclaration(true);
  8009. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  8010. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  8011. "previous declaration set still overloaded");
  8012. // Diagnose no-prototype function declarations with calling conventions that
  8013. // don't support variadic calls. Only do this in C and do it after merging
  8014. // possibly prototyped redeclarations.
  8015. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  8016. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  8017. CallingConv CC = FT->getExtInfo().getCC();
  8018. if (!supportsVariadicCall(CC)) {
  8019. // Windows system headers sometimes accidentally use stdcall without
  8020. // (void) parameters, so we relax this to a warning.
  8021. int DiagID =
  8022. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  8023. Diag(NewFD->getLocation(), DiagID)
  8024. << FunctionType::getNameForCallConv(CC);
  8025. }
  8026. }
  8027. if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
  8028. NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
  8029. checkNonTrivialCUnion(NewFD->getReturnType(),
  8030. NewFD->getReturnTypeSourceRange().getBegin(),
  8031. NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
  8032. } else {
  8033. // C++11 [replacement.functions]p3:
  8034. // The program's definitions shall not be specified as inline.
  8035. //
  8036. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  8037. //
  8038. // Suppress the diagnostic if the function is __attribute__((used)), since
  8039. // that forces an external definition to be emitted.
  8040. if (D.getDeclSpec().isInlineSpecified() &&
  8041. NewFD->isReplaceableGlobalAllocationFunction() &&
  8042. !NewFD->hasAttr<UsedAttr>())
  8043. Diag(D.getDeclSpec().getInlineSpecLoc(),
  8044. diag::ext_operator_new_delete_declared_inline)
  8045. << NewFD->getDeclName();
  8046. // If the declarator is a template-id, translate the parser's template
  8047. // argument list into our AST format.
  8048. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  8049. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  8050. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  8051. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  8052. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  8053. TemplateId->NumArgs);
  8054. translateTemplateArguments(TemplateArgsPtr,
  8055. TemplateArgs);
  8056. HasExplicitTemplateArgs = true;
  8057. if (NewFD->isInvalidDecl()) {
  8058. HasExplicitTemplateArgs = false;
  8059. } else if (FunctionTemplate) {
  8060. // Function template with explicit template arguments.
  8061. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  8062. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  8063. HasExplicitTemplateArgs = false;
  8064. } else {
  8065. assert((isFunctionTemplateSpecialization ||
  8066. D.getDeclSpec().isFriendSpecified()) &&
  8067. "should have a 'template<>' for this decl");
  8068. // "friend void foo<>(int);" is an implicit specialization decl.
  8069. isFunctionTemplateSpecialization = true;
  8070. }
  8071. } else if (isFriend && isFunctionTemplateSpecialization) {
  8072. // This combination is only possible in a recovery case; the user
  8073. // wrote something like:
  8074. // template <> friend void foo(int);
  8075. // which we're recovering from as if the user had written:
  8076. // friend void foo<>(int);
  8077. // Go ahead and fake up a template id.
  8078. HasExplicitTemplateArgs = true;
  8079. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  8080. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  8081. }
  8082. // We do not add HD attributes to specializations here because
  8083. // they may have different constexpr-ness compared to their
  8084. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  8085. // may end up with different effective targets. Instead, a
  8086. // specialization inherits its target attributes from its template
  8087. // in the CheckFunctionTemplateSpecialization() call below.
  8088. if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
  8089. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  8090. // If it's a friend (and only if it's a friend), it's possible
  8091. // that either the specialized function type or the specialized
  8092. // template is dependent, and therefore matching will fail. In
  8093. // this case, don't check the specialization yet.
  8094. bool InstantiationDependent = false;
  8095. if (isFunctionTemplateSpecialization && isFriend &&
  8096. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  8097. TemplateSpecializationType::anyDependentTemplateArguments(
  8098. TemplateArgs,
  8099. InstantiationDependent))) {
  8100. assert(HasExplicitTemplateArgs &&
  8101. "friend function specialization without template args");
  8102. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  8103. Previous))
  8104. NewFD->setInvalidDecl();
  8105. } else if (isFunctionTemplateSpecialization) {
  8106. if (CurContext->isDependentContext() && CurContext->isRecord()
  8107. && !isFriend) {
  8108. isDependentClassScopeExplicitSpecialization = true;
  8109. } else if (!NewFD->isInvalidDecl() &&
  8110. CheckFunctionTemplateSpecialization(
  8111. NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
  8112. Previous))
  8113. NewFD->setInvalidDecl();
  8114. // C++ [dcl.stc]p1:
  8115. // A storage-class-specifier shall not be specified in an explicit
  8116. // specialization (14.7.3)
  8117. FunctionTemplateSpecializationInfo *Info =
  8118. NewFD->getTemplateSpecializationInfo();
  8119. if (Info && SC != SC_None) {
  8120. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  8121. Diag(NewFD->getLocation(),
  8122. diag::err_explicit_specialization_inconsistent_storage_class)
  8123. << SC
  8124. << FixItHint::CreateRemoval(
  8125. D.getDeclSpec().getStorageClassSpecLoc());
  8126. else
  8127. Diag(NewFD->getLocation(),
  8128. diag::ext_explicit_specialization_storage_class)
  8129. << FixItHint::CreateRemoval(
  8130. D.getDeclSpec().getStorageClassSpecLoc());
  8131. }
  8132. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  8133. if (CheckMemberSpecialization(NewFD, Previous))
  8134. NewFD->setInvalidDecl();
  8135. }
  8136. // Perform semantic checking on the function declaration.
  8137. if (!isDependentClassScopeExplicitSpecialization) {
  8138. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  8139. CheckMain(NewFD, D.getDeclSpec());
  8140. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  8141. CheckMSVCRTEntryPoint(NewFD);
  8142. if (!NewFD->isInvalidDecl())
  8143. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  8144. isMemberSpecialization));
  8145. else if (!Previous.empty())
  8146. // Recover gracefully from an invalid redeclaration.
  8147. D.setRedeclaration(true);
  8148. }
  8149. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  8150. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  8151. "previous declaration set still overloaded");
  8152. NamedDecl *PrincipalDecl = (FunctionTemplate
  8153. ? cast<NamedDecl>(FunctionTemplate)
  8154. : NewFD);
  8155. if (isFriend && NewFD->getPreviousDecl()) {
  8156. AccessSpecifier Access = AS_public;
  8157. if (!NewFD->isInvalidDecl())
  8158. Access = NewFD->getPreviousDecl()->getAccess();
  8159. NewFD->setAccess(Access);
  8160. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  8161. }
  8162. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  8163. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  8164. PrincipalDecl->setNonMemberOperator();
  8165. // If we have a function template, check the template parameter
  8166. // list. This will check and merge default template arguments.
  8167. if (FunctionTemplate) {
  8168. FunctionTemplateDecl *PrevTemplate =
  8169. FunctionTemplate->getPreviousDecl();
  8170. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  8171. PrevTemplate ? PrevTemplate->getTemplateParameters()
  8172. : nullptr,
  8173. D.getDeclSpec().isFriendSpecified()
  8174. ? (D.isFunctionDefinition()
  8175. ? TPC_FriendFunctionTemplateDefinition
  8176. : TPC_FriendFunctionTemplate)
  8177. : (D.getCXXScopeSpec().isSet() &&
  8178. DC && DC->isRecord() &&
  8179. DC->isDependentContext())
  8180. ? TPC_ClassTemplateMember
  8181. : TPC_FunctionTemplate);
  8182. }
  8183. if (NewFD->isInvalidDecl()) {
  8184. // Ignore all the rest of this.
  8185. } else if (!D.isRedeclaration()) {
  8186. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  8187. AddToScope };
  8188. // Fake up an access specifier if it's supposed to be a class member.
  8189. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  8190. NewFD->setAccess(AS_public);
  8191. // Qualified decls generally require a previous declaration.
  8192. if (D.getCXXScopeSpec().isSet()) {
  8193. // ...with the major exception of templated-scope or
  8194. // dependent-scope friend declarations.
  8195. // TODO: we currently also suppress this check in dependent
  8196. // contexts because (1) the parameter depth will be off when
  8197. // matching friend templates and (2) we might actually be
  8198. // selecting a friend based on a dependent factor. But there
  8199. // are situations where these conditions don't apply and we
  8200. // can actually do this check immediately.
  8201. //
  8202. // Unless the scope is dependent, it's always an error if qualified
  8203. // redeclaration lookup found nothing at all. Diagnose that now;
  8204. // nothing will diagnose that error later.
  8205. if (isFriend &&
  8206. (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  8207. (!Previous.empty() && CurContext->isDependentContext()))) {
  8208. // ignore these
  8209. } else {
  8210. // The user tried to provide an out-of-line definition for a
  8211. // function that is a member of a class or namespace, but there
  8212. // was no such member function declared (C++ [class.mfct]p2,
  8213. // C++ [namespace.memdef]p2). For example:
  8214. //
  8215. // class X {
  8216. // void f() const;
  8217. // };
  8218. //
  8219. // void X::f() { } // ill-formed
  8220. //
  8221. // Complain about this problem, and attempt to suggest close
  8222. // matches (e.g., those that differ only in cv-qualifiers and
  8223. // whether the parameter types are references).
  8224. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8225. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  8226. AddToScope = ExtraArgs.AddToScope;
  8227. return Result;
  8228. }
  8229. }
  8230. // Unqualified local friend declarations are required to resolve
  8231. // to something.
  8232. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  8233. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8234. *this, Previous, NewFD, ExtraArgs, true, S)) {
  8235. AddToScope = ExtraArgs.AddToScope;
  8236. return Result;
  8237. }
  8238. }
  8239. } else if (!D.isFunctionDefinition() &&
  8240. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  8241. !isFriend && !isFunctionTemplateSpecialization &&
  8242. !isMemberSpecialization) {
  8243. // An out-of-line member function declaration must also be a
  8244. // definition (C++ [class.mfct]p2).
  8245. // Note that this is not the case for explicit specializations of
  8246. // function templates or member functions of class templates, per
  8247. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  8248. // extension for compatibility with old SWIG code which likes to
  8249. // generate them.
  8250. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  8251. << D.getCXXScopeSpec().getRange();
  8252. }
  8253. }
  8254. ProcessPragmaWeak(S, NewFD);
  8255. checkAttributesAfterMerging(*this, *NewFD);
  8256. AddKnownFunctionAttributes(NewFD);
  8257. if (NewFD->hasAttr<OverloadableAttr>() &&
  8258. !NewFD->getType()->getAs<FunctionProtoType>()) {
  8259. Diag(NewFD->getLocation(),
  8260. diag::err_attribute_overloadable_no_prototype)
  8261. << NewFD;
  8262. // Turn this into a variadic function with no parameters.
  8263. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  8264. FunctionProtoType::ExtProtoInfo EPI(
  8265. Context.getDefaultCallingConvention(true, false));
  8266. EPI.Variadic = true;
  8267. EPI.ExtInfo = FT->getExtInfo();
  8268. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  8269. NewFD->setType(R);
  8270. }
  8271. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8272. // member, set the visibility of this function.
  8273. if (!DC->isRecord() && NewFD->isExternallyVisible())
  8274. AddPushedVisibilityAttribute(NewFD);
  8275. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  8276. // marking the function.
  8277. AddCFAuditedAttribute(NewFD);
  8278. // If this is a function definition, check if we have to apply optnone due to
  8279. // a pragma.
  8280. if(D.isFunctionDefinition())
  8281. AddRangeBasedOptnone(NewFD);
  8282. // If this is the first declaration of an extern C variable, update
  8283. // the map of such variables.
  8284. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  8285. isIncompleteDeclExternC(*this, NewFD))
  8286. RegisterLocallyScopedExternCDecl(NewFD, S);
  8287. // Set this FunctionDecl's range up to the right paren.
  8288. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  8289. if (D.isRedeclaration() && !Previous.empty()) {
  8290. NamedDecl *Prev = Previous.getRepresentativeDecl();
  8291. checkDLLAttributeRedeclaration(*this, Prev, NewFD,
  8292. isMemberSpecialization ||
  8293. isFunctionTemplateSpecialization,
  8294. D.isFunctionDefinition());
  8295. }
  8296. if (getLangOpts().CUDA) {
  8297. IdentifierInfo *II = NewFD->getIdentifier();
  8298. if (II && II->isStr(getCudaConfigureFuncName()) &&
  8299. !NewFD->isInvalidDecl() &&
  8300. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  8301. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  8302. Diag(NewFD->getLocation(), diag::err_config_scalar_return)
  8303. << getCudaConfigureFuncName();
  8304. Context.setcudaConfigureCallDecl(NewFD);
  8305. }
  8306. // Variadic functions, other than a *declaration* of printf, are not allowed
  8307. // in device-side CUDA code, unless someone passed
  8308. // -fcuda-allow-variadic-functions.
  8309. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  8310. (NewFD->hasAttr<CUDADeviceAttr>() ||
  8311. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  8312. !(II && II->isStr("printf") && NewFD->isExternC() &&
  8313. !D.isFunctionDefinition())) {
  8314. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  8315. }
  8316. }
  8317. MarkUnusedFileScopedDecl(NewFD);
  8318. if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
  8319. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  8320. if ((getLangOpts().OpenCLVersion >= 120)
  8321. && (SC == SC_Static)) {
  8322. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  8323. D.setInvalidType();
  8324. }
  8325. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  8326. if (!NewFD->getReturnType()->isVoidType()) {
  8327. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  8328. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  8329. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  8330. : FixItHint());
  8331. D.setInvalidType();
  8332. }
  8333. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  8334. for (auto Param : NewFD->parameters())
  8335. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  8336. if (getLangOpts().OpenCLCPlusPlus) {
  8337. if (DC->isRecord()) {
  8338. Diag(D.getIdentifierLoc(), diag::err_method_kernel);
  8339. D.setInvalidType();
  8340. }
  8341. if (FunctionTemplate) {
  8342. Diag(D.getIdentifierLoc(), diag::err_template_kernel);
  8343. D.setInvalidType();
  8344. }
  8345. }
  8346. }
  8347. if (getLangOpts().CPlusPlus) {
  8348. if (FunctionTemplate) {
  8349. if (NewFD->isInvalidDecl())
  8350. FunctionTemplate->setInvalidDecl();
  8351. return FunctionTemplate;
  8352. }
  8353. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  8354. CompleteMemberSpecialization(NewFD, Previous);
  8355. }
  8356. for (const ParmVarDecl *Param : NewFD->parameters()) {
  8357. QualType PT = Param->getType();
  8358. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  8359. // types.
  8360. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
  8361. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  8362. QualType ElemTy = PipeTy->getElementType();
  8363. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  8364. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  8365. D.setInvalidType();
  8366. }
  8367. }
  8368. }
  8369. }
  8370. // Here we have an function template explicit specialization at class scope.
  8371. // The actual specialization will be postponed to template instatiation
  8372. // time via the ClassScopeFunctionSpecializationDecl node.
  8373. if (isDependentClassScopeExplicitSpecialization) {
  8374. ClassScopeFunctionSpecializationDecl *NewSpec =
  8375. ClassScopeFunctionSpecializationDecl::Create(
  8376. Context, CurContext, NewFD->getLocation(),
  8377. cast<CXXMethodDecl>(NewFD),
  8378. HasExplicitTemplateArgs, TemplateArgs);
  8379. CurContext->addDecl(NewSpec);
  8380. AddToScope = false;
  8381. }
  8382. // Diagnose availability attributes. Availability cannot be used on functions
  8383. // that are run during load/unload.
  8384. if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
  8385. if (NewFD->hasAttr<ConstructorAttr>()) {
  8386. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8387. << 1;
  8388. NewFD->dropAttr<AvailabilityAttr>();
  8389. }
  8390. if (NewFD->hasAttr<DestructorAttr>()) {
  8391. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8392. << 2;
  8393. NewFD->dropAttr<AvailabilityAttr>();
  8394. }
  8395. }
  8396. return NewFD;
  8397. }
  8398. /// Return a CodeSegAttr from a containing class. The Microsoft docs say
  8399. /// when __declspec(code_seg) "is applied to a class, all member functions of
  8400. /// the class and nested classes -- this includes compiler-generated special
  8401. /// member functions -- are put in the specified segment."
  8402. /// The actual behavior is a little more complicated. The Microsoft compiler
  8403. /// won't check outer classes if there is an active value from #pragma code_seg.
  8404. /// The CodeSeg is always applied from the direct parent but only from outer
  8405. /// classes when the #pragma code_seg stack is empty. See:
  8406. /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
  8407. /// available since MS has removed the page.
  8408. static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
  8409. const auto *Method = dyn_cast<CXXMethodDecl>(FD);
  8410. if (!Method)
  8411. return nullptr;
  8412. const CXXRecordDecl *Parent = Method->getParent();
  8413. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8414. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8415. NewAttr->setImplicit(true);
  8416. return NewAttr;
  8417. }
  8418. // The Microsoft compiler won't check outer classes for the CodeSeg
  8419. // when the #pragma code_seg stack is active.
  8420. if (S.CodeSegStack.CurrentValue)
  8421. return nullptr;
  8422. while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
  8423. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8424. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8425. NewAttr->setImplicit(true);
  8426. return NewAttr;
  8427. }
  8428. }
  8429. return nullptr;
  8430. }
  8431. /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
  8432. /// containing class. Otherwise it will return implicit SectionAttr if the
  8433. /// function is a definition and there is an active value on CodeSegStack
  8434. /// (from the current #pragma code-seg value).
  8435. ///
  8436. /// \param FD Function being declared.
  8437. /// \param IsDefinition Whether it is a definition or just a declarartion.
  8438. /// \returns A CodeSegAttr or SectionAttr to apply to the function or
  8439. /// nullptr if no attribute should be added.
  8440. Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
  8441. bool IsDefinition) {
  8442. if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
  8443. return A;
  8444. if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
  8445. CodeSegStack.CurrentValue)
  8446. return SectionAttr::CreateImplicit(
  8447. getASTContext(), CodeSegStack.CurrentValue->getString(),
  8448. CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
  8449. SectionAttr::Declspec_allocate);
  8450. return nullptr;
  8451. }
  8452. /// Determines if we can perform a correct type check for \p D as a
  8453. /// redeclaration of \p PrevDecl. If not, we can generally still perform a
  8454. /// best-effort check.
  8455. ///
  8456. /// \param NewD The new declaration.
  8457. /// \param OldD The old declaration.
  8458. /// \param NewT The portion of the type of the new declaration to check.
  8459. /// \param OldT The portion of the type of the old declaration to check.
  8460. bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
  8461. QualType NewT, QualType OldT) {
  8462. if (!NewD->getLexicalDeclContext()->isDependentContext())
  8463. return true;
  8464. // For dependently-typed local extern declarations and friends, we can't
  8465. // perform a correct type check in general until instantiation:
  8466. //
  8467. // int f();
  8468. // template<typename T> void g() { T f(); }
  8469. //
  8470. // (valid if g() is only instantiated with T = int).
  8471. if (NewT->isDependentType() &&
  8472. (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
  8473. return false;
  8474. // Similarly, if the previous declaration was a dependent local extern
  8475. // declaration, we don't really know its type yet.
  8476. if (OldT->isDependentType() && OldD->isLocalExternDecl())
  8477. return false;
  8478. return true;
  8479. }
  8480. /// Checks if the new declaration declared in dependent context must be
  8481. /// put in the same redeclaration chain as the specified declaration.
  8482. ///
  8483. /// \param D Declaration that is checked.
  8484. /// \param PrevDecl Previous declaration found with proper lookup method for the
  8485. /// same declaration name.
  8486. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  8487. /// belongs to.
  8488. ///
  8489. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  8490. if (!D->getLexicalDeclContext()->isDependentContext())
  8491. return true;
  8492. // Don't chain dependent friend function definitions until instantiation, to
  8493. // permit cases like
  8494. //
  8495. // void func();
  8496. // template<typename T> class C1 { friend void func() {} };
  8497. // template<typename T> class C2 { friend void func() {} };
  8498. //
  8499. // ... which is valid if only one of C1 and C2 is ever instantiated.
  8500. //
  8501. // FIXME: This need only apply to function definitions. For now, we proxy
  8502. // this by checking for a file-scope function. We do not want this to apply
  8503. // to friend declarations nominating member functions, because that gets in
  8504. // the way of access checks.
  8505. if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
  8506. return false;
  8507. auto *VD = dyn_cast<ValueDecl>(D);
  8508. auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
  8509. return !VD || !PrevVD ||
  8510. canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
  8511. PrevVD->getType());
  8512. }
  8513. /// Check the target attribute of the function for MultiVersion
  8514. /// validity.
  8515. ///
  8516. /// Returns true if there was an error, false otherwise.
  8517. static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
  8518. const auto *TA = FD->getAttr<TargetAttr>();
  8519. assert(TA && "MultiVersion Candidate requires a target attribute");
  8520. TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
  8521. const TargetInfo &TargetInfo = S.Context.getTargetInfo();
  8522. enum ErrType { Feature = 0, Architecture = 1 };
  8523. if (!ParseInfo.Architecture.empty() &&
  8524. !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
  8525. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8526. << Architecture << ParseInfo.Architecture;
  8527. return true;
  8528. }
  8529. for (const auto &Feat : ParseInfo.Features) {
  8530. auto BareFeat = StringRef{Feat}.substr(1);
  8531. if (Feat[0] == '-') {
  8532. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8533. << Feature << ("no-" + BareFeat).str();
  8534. return true;
  8535. }
  8536. if (!TargetInfo.validateCpuSupports(BareFeat) ||
  8537. !TargetInfo.isValidFeatureName(BareFeat)) {
  8538. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8539. << Feature << BareFeat;
  8540. return true;
  8541. }
  8542. }
  8543. return false;
  8544. }
  8545. static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
  8546. MultiVersionKind MVType) {
  8547. for (const Attr *A : FD->attrs()) {
  8548. switch (A->getKind()) {
  8549. case attr::CPUDispatch:
  8550. case attr::CPUSpecific:
  8551. if (MVType != MultiVersionKind::CPUDispatch &&
  8552. MVType != MultiVersionKind::CPUSpecific)
  8553. return true;
  8554. break;
  8555. case attr::Target:
  8556. if (MVType != MultiVersionKind::Target)
  8557. return true;
  8558. break;
  8559. default:
  8560. return true;
  8561. }
  8562. }
  8563. return false;
  8564. }
  8565. bool Sema::areMultiversionVariantFunctionsCompatible(
  8566. const FunctionDecl *OldFD, const FunctionDecl *NewFD,
  8567. const PartialDiagnostic &NoProtoDiagID,
  8568. const PartialDiagnosticAt &NoteCausedDiagIDAt,
  8569. const PartialDiagnosticAt &NoSupportDiagIDAt,
  8570. const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
  8571. bool ConstexprSupported) {
  8572. enum DoesntSupport {
  8573. FuncTemplates = 0,
  8574. VirtFuncs = 1,
  8575. DeducedReturn = 2,
  8576. Constructors = 3,
  8577. Destructors = 4,
  8578. DeletedFuncs = 5,
  8579. DefaultedFuncs = 6,
  8580. ConstexprFuncs = 7,
  8581. ConstevalFuncs = 8,
  8582. };
  8583. enum Different {
  8584. CallingConv = 0,
  8585. ReturnType = 1,
  8586. ConstexprSpec = 2,
  8587. InlineSpec = 3,
  8588. StorageClass = 4,
  8589. Linkage = 5,
  8590. };
  8591. if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
  8592. Diag(OldFD->getLocation(), NoProtoDiagID);
  8593. Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
  8594. return true;
  8595. }
  8596. if (!NewFD->getType()->getAs<FunctionProtoType>())
  8597. return Diag(NewFD->getLocation(), NoProtoDiagID);
  8598. if (!TemplatesSupported &&
  8599. NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  8600. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8601. << FuncTemplates;
  8602. if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
  8603. if (NewCXXFD->isVirtual())
  8604. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8605. << VirtFuncs;
  8606. if (isa<CXXConstructorDecl>(NewCXXFD))
  8607. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8608. << Constructors;
  8609. if (isa<CXXDestructorDecl>(NewCXXFD))
  8610. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8611. << Destructors;
  8612. }
  8613. if (NewFD->isDeleted())
  8614. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8615. << DeletedFuncs;
  8616. if (NewFD->isDefaulted())
  8617. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8618. << DefaultedFuncs;
  8619. if (!ConstexprSupported && NewFD->isConstexpr())
  8620. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8621. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  8622. QualType NewQType = Context.getCanonicalType(NewFD->getType());
  8623. const auto *NewType = cast<FunctionType>(NewQType);
  8624. QualType NewReturnType = NewType->getReturnType();
  8625. if (NewReturnType->isUndeducedType())
  8626. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8627. << DeducedReturn;
  8628. // Ensure the return type is identical.
  8629. if (OldFD) {
  8630. QualType OldQType = Context.getCanonicalType(OldFD->getType());
  8631. const auto *OldType = cast<FunctionType>(OldQType);
  8632. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  8633. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  8634. if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
  8635. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
  8636. QualType OldReturnType = OldType->getReturnType();
  8637. if (OldReturnType != NewReturnType)
  8638. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
  8639. if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
  8640. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
  8641. if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
  8642. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
  8643. if (OldFD->getStorageClass() != NewFD->getStorageClass())
  8644. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
  8645. if (OldFD->isExternC() != NewFD->isExternC())
  8646. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
  8647. if (CheckEquivalentExceptionSpec(
  8648. OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
  8649. NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
  8650. return true;
  8651. }
  8652. return false;
  8653. }
  8654. static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
  8655. const FunctionDecl *NewFD,
  8656. bool CausesMV,
  8657. MultiVersionKind MVType) {
  8658. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8659. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8660. if (OldFD)
  8661. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8662. return true;
  8663. }
  8664. bool IsCPUSpecificCPUDispatchMVType =
  8665. MVType == MultiVersionKind::CPUDispatch ||
  8666. MVType == MultiVersionKind::CPUSpecific;
  8667. // For now, disallow all other attributes. These should be opt-in, but
  8668. // an analysis of all of them is a future FIXME.
  8669. if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
  8670. S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8671. << IsCPUSpecificCPUDispatchMVType;
  8672. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8673. return true;
  8674. }
  8675. if (HasNonMultiVersionAttributes(NewFD, MVType))
  8676. return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8677. << IsCPUSpecificCPUDispatchMVType;
  8678. // Only allow transition to MultiVersion if it hasn't been used.
  8679. if (OldFD && CausesMV && OldFD->isUsed(false))
  8680. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  8681. return S.areMultiversionVariantFunctionsCompatible(
  8682. OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
  8683. PartialDiagnosticAt(NewFD->getLocation(),
  8684. S.PDiag(diag::note_multiversioning_caused_here)),
  8685. PartialDiagnosticAt(NewFD->getLocation(),
  8686. S.PDiag(diag::err_multiversion_doesnt_support)
  8687. << IsCPUSpecificCPUDispatchMVType),
  8688. PartialDiagnosticAt(NewFD->getLocation(),
  8689. S.PDiag(diag::err_multiversion_diff)),
  8690. /*TemplatesSupported=*/false,
  8691. /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType);
  8692. }
  8693. /// Check the validity of a multiversion function declaration that is the
  8694. /// first of its kind. Also sets the multiversion'ness' of the function itself.
  8695. ///
  8696. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8697. ///
  8698. /// Returns true if there was an error, false otherwise.
  8699. static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
  8700. MultiVersionKind MVType,
  8701. const TargetAttr *TA) {
  8702. assert(MVType != MultiVersionKind::None &&
  8703. "Function lacks multiversion attribute");
  8704. // Target only causes MV if it is default, otherwise this is a normal
  8705. // function.
  8706. if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
  8707. return false;
  8708. if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
  8709. FD->setInvalidDecl();
  8710. return true;
  8711. }
  8712. if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
  8713. FD->setInvalidDecl();
  8714. return true;
  8715. }
  8716. FD->setIsMultiVersion();
  8717. return false;
  8718. }
  8719. static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
  8720. for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
  8721. if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
  8722. return true;
  8723. }
  8724. return false;
  8725. }
  8726. static bool CheckTargetCausesMultiVersioning(
  8727. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
  8728. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8729. LookupResult &Previous) {
  8730. const auto *OldTA = OldFD->getAttr<TargetAttr>();
  8731. TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
  8732. // Sort order doesn't matter, it just needs to be consistent.
  8733. llvm::sort(NewParsed.Features);
  8734. // If the old decl is NOT MultiVersioned yet, and we don't cause that
  8735. // to change, this is a simple redeclaration.
  8736. if (!NewTA->isDefaultVersion() &&
  8737. (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
  8738. return false;
  8739. // Otherwise, this decl causes MultiVersioning.
  8740. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8741. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8742. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8743. NewFD->setInvalidDecl();
  8744. return true;
  8745. }
  8746. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
  8747. MultiVersionKind::Target)) {
  8748. NewFD->setInvalidDecl();
  8749. return true;
  8750. }
  8751. if (CheckMultiVersionValue(S, NewFD)) {
  8752. NewFD->setInvalidDecl();
  8753. return true;
  8754. }
  8755. // If this is 'default', permit the forward declaration.
  8756. if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
  8757. Redeclaration = true;
  8758. OldDecl = OldFD;
  8759. OldFD->setIsMultiVersion();
  8760. NewFD->setIsMultiVersion();
  8761. return false;
  8762. }
  8763. if (CheckMultiVersionValue(S, OldFD)) {
  8764. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8765. NewFD->setInvalidDecl();
  8766. return true;
  8767. }
  8768. TargetAttr::ParsedTargetAttr OldParsed =
  8769. OldTA->parse(std::less<std::string>());
  8770. if (OldParsed == NewParsed) {
  8771. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8772. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8773. NewFD->setInvalidDecl();
  8774. return true;
  8775. }
  8776. for (const auto *FD : OldFD->redecls()) {
  8777. const auto *CurTA = FD->getAttr<TargetAttr>();
  8778. // We allow forward declarations before ANY multiversioning attributes, but
  8779. // nothing after the fact.
  8780. if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
  8781. (!CurTA || CurTA->isInherited())) {
  8782. S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
  8783. << 0;
  8784. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8785. NewFD->setInvalidDecl();
  8786. return true;
  8787. }
  8788. }
  8789. OldFD->setIsMultiVersion();
  8790. NewFD->setIsMultiVersion();
  8791. Redeclaration = false;
  8792. MergeTypeWithPrevious = false;
  8793. OldDecl = nullptr;
  8794. Previous.clear();
  8795. return false;
  8796. }
  8797. /// Check the validity of a new function declaration being added to an existing
  8798. /// multiversioned declaration collection.
  8799. static bool CheckMultiVersionAdditionalDecl(
  8800. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
  8801. MultiVersionKind NewMVType, const TargetAttr *NewTA,
  8802. const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
  8803. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8804. LookupResult &Previous) {
  8805. MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
  8806. // Disallow mixing of multiversioning types.
  8807. if ((OldMVType == MultiVersionKind::Target &&
  8808. NewMVType != MultiVersionKind::Target) ||
  8809. (NewMVType == MultiVersionKind::Target &&
  8810. OldMVType != MultiVersionKind::Target)) {
  8811. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8812. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8813. NewFD->setInvalidDecl();
  8814. return true;
  8815. }
  8816. TargetAttr::ParsedTargetAttr NewParsed;
  8817. if (NewTA) {
  8818. NewParsed = NewTA->parse();
  8819. llvm::sort(NewParsed.Features);
  8820. }
  8821. bool UseMemberUsingDeclRules =
  8822. S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
  8823. // Next, check ALL non-overloads to see if this is a redeclaration of a
  8824. // previous member of the MultiVersion set.
  8825. for (NamedDecl *ND : Previous) {
  8826. FunctionDecl *CurFD = ND->getAsFunction();
  8827. if (!CurFD)
  8828. continue;
  8829. if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
  8830. continue;
  8831. if (NewMVType == MultiVersionKind::Target) {
  8832. const auto *CurTA = CurFD->getAttr<TargetAttr>();
  8833. if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
  8834. NewFD->setIsMultiVersion();
  8835. Redeclaration = true;
  8836. OldDecl = ND;
  8837. return false;
  8838. }
  8839. TargetAttr::ParsedTargetAttr CurParsed =
  8840. CurTA->parse(std::less<std::string>());
  8841. if (CurParsed == NewParsed) {
  8842. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8843. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8844. NewFD->setInvalidDecl();
  8845. return true;
  8846. }
  8847. } else {
  8848. const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
  8849. const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
  8850. // Handle CPUDispatch/CPUSpecific versions.
  8851. // Only 1 CPUDispatch function is allowed, this will make it go through
  8852. // the redeclaration errors.
  8853. if (NewMVType == MultiVersionKind::CPUDispatch &&
  8854. CurFD->hasAttr<CPUDispatchAttr>()) {
  8855. if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
  8856. std::equal(
  8857. CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
  8858. NewCPUDisp->cpus_begin(),
  8859. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8860. return Cur->getName() == New->getName();
  8861. })) {
  8862. NewFD->setIsMultiVersion();
  8863. Redeclaration = true;
  8864. OldDecl = ND;
  8865. return false;
  8866. }
  8867. // If the declarations don't match, this is an error condition.
  8868. S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
  8869. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8870. NewFD->setInvalidDecl();
  8871. return true;
  8872. }
  8873. if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
  8874. if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
  8875. std::equal(
  8876. CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
  8877. NewCPUSpec->cpus_begin(),
  8878. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8879. return Cur->getName() == New->getName();
  8880. })) {
  8881. NewFD->setIsMultiVersion();
  8882. Redeclaration = true;
  8883. OldDecl = ND;
  8884. return false;
  8885. }
  8886. // Only 1 version of CPUSpecific is allowed for each CPU.
  8887. for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
  8888. for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
  8889. if (CurII == NewII) {
  8890. S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
  8891. << NewII;
  8892. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8893. NewFD->setInvalidDecl();
  8894. return true;
  8895. }
  8896. }
  8897. }
  8898. }
  8899. // If the two decls aren't the same MVType, there is no possible error
  8900. // condition.
  8901. }
  8902. }
  8903. // Else, this is simply a non-redecl case. Checking the 'value' is only
  8904. // necessary in the Target case, since The CPUSpecific/Dispatch cases are
  8905. // handled in the attribute adding step.
  8906. if (NewMVType == MultiVersionKind::Target &&
  8907. CheckMultiVersionValue(S, NewFD)) {
  8908. NewFD->setInvalidDecl();
  8909. return true;
  8910. }
  8911. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
  8912. !OldFD->isMultiVersion(), NewMVType)) {
  8913. NewFD->setInvalidDecl();
  8914. return true;
  8915. }
  8916. // Permit forward declarations in the case where these two are compatible.
  8917. if (!OldFD->isMultiVersion()) {
  8918. OldFD->setIsMultiVersion();
  8919. NewFD->setIsMultiVersion();
  8920. Redeclaration = true;
  8921. OldDecl = OldFD;
  8922. return false;
  8923. }
  8924. NewFD->setIsMultiVersion();
  8925. Redeclaration = false;
  8926. MergeTypeWithPrevious = false;
  8927. OldDecl = nullptr;
  8928. Previous.clear();
  8929. return false;
  8930. }
  8931. /// Check the validity of a mulitversion function declaration.
  8932. /// Also sets the multiversion'ness' of the function itself.
  8933. ///
  8934. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8935. ///
  8936. /// Returns true if there was an error, false otherwise.
  8937. static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
  8938. bool &Redeclaration, NamedDecl *&OldDecl,
  8939. bool &MergeTypeWithPrevious,
  8940. LookupResult &Previous) {
  8941. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  8942. const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
  8943. const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
  8944. // Mixing Multiversioning types is prohibited.
  8945. if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
  8946. (NewCPUDisp && NewCPUSpec)) {
  8947. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8948. NewFD->setInvalidDecl();
  8949. return true;
  8950. }
  8951. MultiVersionKind MVType = NewFD->getMultiVersionKind();
  8952. // Main isn't allowed to become a multiversion function, however it IS
  8953. // permitted to have 'main' be marked with the 'target' optimization hint.
  8954. if (NewFD->isMain()) {
  8955. if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
  8956. MVType == MultiVersionKind::CPUDispatch ||
  8957. MVType == MultiVersionKind::CPUSpecific) {
  8958. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
  8959. NewFD->setInvalidDecl();
  8960. return true;
  8961. }
  8962. return false;
  8963. }
  8964. if (!OldDecl || !OldDecl->getAsFunction() ||
  8965. OldDecl->getDeclContext()->getRedeclContext() !=
  8966. NewFD->getDeclContext()->getRedeclContext()) {
  8967. // If there's no previous declaration, AND this isn't attempting to cause
  8968. // multiversioning, this isn't an error condition.
  8969. if (MVType == MultiVersionKind::None)
  8970. return false;
  8971. return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
  8972. }
  8973. FunctionDecl *OldFD = OldDecl->getAsFunction();
  8974. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
  8975. return false;
  8976. if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
  8977. S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
  8978. << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
  8979. NewFD->setInvalidDecl();
  8980. return true;
  8981. }
  8982. // Handle the target potentially causes multiversioning case.
  8983. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
  8984. return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
  8985. Redeclaration, OldDecl,
  8986. MergeTypeWithPrevious, Previous);
  8987. // At this point, we have a multiversion function decl (in OldFD) AND an
  8988. // appropriate attribute in the current function decl. Resolve that these are
  8989. // still compatible with previous declarations.
  8990. return CheckMultiVersionAdditionalDecl(
  8991. S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
  8992. OldDecl, MergeTypeWithPrevious, Previous);
  8993. }
  8994. /// Perform semantic checking of a new function declaration.
  8995. ///
  8996. /// Performs semantic analysis of the new function declaration
  8997. /// NewFD. This routine performs all semantic checking that does not
  8998. /// require the actual declarator involved in the declaration, and is
  8999. /// used both for the declaration of functions as they are parsed
  9000. /// (called via ActOnDeclarator) and for the declaration of functions
  9001. /// that have been instantiated via C++ template instantiation (called
  9002. /// via InstantiateDecl).
  9003. ///
  9004. /// \param IsMemberSpecialization whether this new function declaration is
  9005. /// a member specialization (that replaces any definition provided by the
  9006. /// previous declaration).
  9007. ///
  9008. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  9009. ///
  9010. /// \returns true if the function declaration is a redeclaration.
  9011. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  9012. LookupResult &Previous,
  9013. bool IsMemberSpecialization) {
  9014. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  9015. "Variably modified return types are not handled here");
  9016. // Determine whether the type of this function should be merged with
  9017. // a previous visible declaration. This never happens for functions in C++,
  9018. // and always happens in C if the previous declaration was visible.
  9019. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  9020. !Previous.isShadowed();
  9021. bool Redeclaration = false;
  9022. NamedDecl *OldDecl = nullptr;
  9023. bool MayNeedOverloadableChecks = false;
  9024. // Merge or overload the declaration with an existing declaration of
  9025. // the same name, if appropriate.
  9026. if (!Previous.empty()) {
  9027. // Determine whether NewFD is an overload of PrevDecl or
  9028. // a declaration that requires merging. If it's an overload,
  9029. // there's no more work to do here; we'll just add the new
  9030. // function to the scope.
  9031. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  9032. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  9033. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  9034. Redeclaration = true;
  9035. OldDecl = Candidate;
  9036. }
  9037. } else {
  9038. MayNeedOverloadableChecks = true;
  9039. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  9040. /*NewIsUsingDecl*/ false)) {
  9041. case Ovl_Match:
  9042. Redeclaration = true;
  9043. break;
  9044. case Ovl_NonFunction:
  9045. Redeclaration = true;
  9046. break;
  9047. case Ovl_Overload:
  9048. Redeclaration = false;
  9049. break;
  9050. }
  9051. }
  9052. }
  9053. // Check for a previous extern "C" declaration with this name.
  9054. if (!Redeclaration &&
  9055. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  9056. if (!Previous.empty()) {
  9057. // This is an extern "C" declaration with the same name as a previous
  9058. // declaration, and thus redeclares that entity...
  9059. Redeclaration = true;
  9060. OldDecl = Previous.getFoundDecl();
  9061. MergeTypeWithPrevious = false;
  9062. // ... except in the presence of __attribute__((overloadable)).
  9063. if (OldDecl->hasAttr<OverloadableAttr>() ||
  9064. NewFD->hasAttr<OverloadableAttr>()) {
  9065. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  9066. MayNeedOverloadableChecks = true;
  9067. Redeclaration = false;
  9068. OldDecl = nullptr;
  9069. }
  9070. }
  9071. }
  9072. }
  9073. if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
  9074. MergeTypeWithPrevious, Previous))
  9075. return Redeclaration;
  9076. // C++11 [dcl.constexpr]p8:
  9077. // A constexpr specifier for a non-static member function that is not
  9078. // a constructor declares that member function to be const.
  9079. //
  9080. // This needs to be delayed until we know whether this is an out-of-line
  9081. // definition of a static member function.
  9082. //
  9083. // This rule is not present in C++1y, so we produce a backwards
  9084. // compatibility warning whenever it happens in C++11.
  9085. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  9086. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  9087. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  9088. !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
  9089. CXXMethodDecl *OldMD = nullptr;
  9090. if (OldDecl)
  9091. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  9092. if (!OldMD || !OldMD->isStatic()) {
  9093. const FunctionProtoType *FPT =
  9094. MD->getType()->castAs<FunctionProtoType>();
  9095. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9096. EPI.TypeQuals.addConst();
  9097. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  9098. FPT->getParamTypes(), EPI));
  9099. // Warn that we did this, if we're not performing template instantiation.
  9100. // In that case, we'll have warned already when the template was defined.
  9101. if (!inTemplateInstantiation()) {
  9102. SourceLocation AddConstLoc;
  9103. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  9104. .IgnoreParens().getAs<FunctionTypeLoc>())
  9105. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  9106. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  9107. << FixItHint::CreateInsertion(AddConstLoc, " const");
  9108. }
  9109. }
  9110. }
  9111. if (Redeclaration) {
  9112. // NewFD and OldDecl represent declarations that need to be
  9113. // merged.
  9114. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  9115. NewFD->setInvalidDecl();
  9116. return Redeclaration;
  9117. }
  9118. Previous.clear();
  9119. Previous.addDecl(OldDecl);
  9120. if (FunctionTemplateDecl *OldTemplateDecl =
  9121. dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  9122. auto *OldFD = OldTemplateDecl->getTemplatedDecl();
  9123. FunctionTemplateDecl *NewTemplateDecl
  9124. = NewFD->getDescribedFunctionTemplate();
  9125. assert(NewTemplateDecl && "Template/non-template mismatch");
  9126. // The call to MergeFunctionDecl above may have created some state in
  9127. // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
  9128. // can add it as a redeclaration.
  9129. NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
  9130. NewFD->setPreviousDeclaration(OldFD);
  9131. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  9132. if (NewFD->isCXXClassMember()) {
  9133. NewFD->setAccess(OldTemplateDecl->getAccess());
  9134. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  9135. }
  9136. // If this is an explicit specialization of a member that is a function
  9137. // template, mark it as a member specialization.
  9138. if (IsMemberSpecialization &&
  9139. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  9140. NewTemplateDecl->setMemberSpecialization();
  9141. assert(OldTemplateDecl->isMemberSpecialization());
  9142. // Explicit specializations of a member template do not inherit deleted
  9143. // status from the parent member template that they are specializing.
  9144. if (OldFD->isDeleted()) {
  9145. // FIXME: This assert will not hold in the presence of modules.
  9146. assert(OldFD->getCanonicalDecl() == OldFD);
  9147. // FIXME: We need an update record for this AST mutation.
  9148. OldFD->setDeletedAsWritten(false);
  9149. }
  9150. }
  9151. } else {
  9152. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  9153. auto *OldFD = cast<FunctionDecl>(OldDecl);
  9154. // This needs to happen first so that 'inline' propagates.
  9155. NewFD->setPreviousDeclaration(OldFD);
  9156. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  9157. if (NewFD->isCXXClassMember())
  9158. NewFD->setAccess(OldFD->getAccess());
  9159. }
  9160. }
  9161. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  9162. !NewFD->getAttr<OverloadableAttr>()) {
  9163. assert((Previous.empty() ||
  9164. llvm::any_of(Previous,
  9165. [](const NamedDecl *ND) {
  9166. return ND->hasAttr<OverloadableAttr>();
  9167. })) &&
  9168. "Non-redecls shouldn't happen without overloadable present");
  9169. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  9170. const auto *FD = dyn_cast<FunctionDecl>(ND);
  9171. return FD && !FD->hasAttr<OverloadableAttr>();
  9172. });
  9173. if (OtherUnmarkedIter != Previous.end()) {
  9174. Diag(NewFD->getLocation(),
  9175. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  9176. Diag((*OtherUnmarkedIter)->getLocation(),
  9177. diag::note_attribute_overloadable_prev_overload)
  9178. << false;
  9179. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  9180. }
  9181. }
  9182. // Semantic checking for this function declaration (in isolation).
  9183. if (getLangOpts().CPlusPlus) {
  9184. // C++-specific checks.
  9185. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  9186. CheckConstructor(Constructor);
  9187. } else if (CXXDestructorDecl *Destructor =
  9188. dyn_cast<CXXDestructorDecl>(NewFD)) {
  9189. CXXRecordDecl *Record = Destructor->getParent();
  9190. QualType ClassType = Context.getTypeDeclType(Record);
  9191. // FIXME: Shouldn't we be able to perform this check even when the class
  9192. // type is dependent? Both gcc and edg can handle that.
  9193. if (!ClassType->isDependentType()) {
  9194. DeclarationName Name
  9195. = Context.DeclarationNames.getCXXDestructorName(
  9196. Context.getCanonicalType(ClassType));
  9197. if (NewFD->getDeclName() != Name) {
  9198. Diag(NewFD->getLocation(), diag::err_destructor_name);
  9199. NewFD->setInvalidDecl();
  9200. return Redeclaration;
  9201. }
  9202. }
  9203. } else if (CXXConversionDecl *Conversion
  9204. = dyn_cast<CXXConversionDecl>(NewFD)) {
  9205. ActOnConversionDeclarator(Conversion);
  9206. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  9207. if (auto *TD = Guide->getDescribedFunctionTemplate())
  9208. CheckDeductionGuideTemplate(TD);
  9209. // A deduction guide is not on the list of entities that can be
  9210. // explicitly specialized.
  9211. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  9212. Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
  9213. << /*explicit specialization*/ 1;
  9214. }
  9215. // Find any virtual functions that this function overrides.
  9216. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  9217. if (!Method->isFunctionTemplateSpecialization() &&
  9218. !Method->getDescribedFunctionTemplate() &&
  9219. Method->isCanonicalDecl()) {
  9220. if (AddOverriddenMethods(Method->getParent(), Method)) {
  9221. // If the function was marked as "static", we have a problem.
  9222. if (NewFD->getStorageClass() == SC_Static) {
  9223. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  9224. }
  9225. }
  9226. }
  9227. if (Method->isStatic())
  9228. checkThisInStaticMemberFunctionType(Method);
  9229. }
  9230. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  9231. if (NewFD->isOverloadedOperator() &&
  9232. CheckOverloadedOperatorDeclaration(NewFD)) {
  9233. NewFD->setInvalidDecl();
  9234. return Redeclaration;
  9235. }
  9236. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  9237. if (NewFD->getLiteralIdentifier() &&
  9238. CheckLiteralOperatorDeclaration(NewFD)) {
  9239. NewFD->setInvalidDecl();
  9240. return Redeclaration;
  9241. }
  9242. // In C++, check default arguments now that we have merged decls. Unless
  9243. // the lexical context is the class, because in this case this is done
  9244. // during delayed parsing anyway.
  9245. if (!CurContext->isRecord())
  9246. CheckCXXDefaultArguments(NewFD);
  9247. // If this function declares a builtin function, check the type of this
  9248. // declaration against the expected type for the builtin.
  9249. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  9250. ASTContext::GetBuiltinTypeError Error;
  9251. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  9252. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  9253. // If the type of the builtin differs only in its exception
  9254. // specification, that's OK.
  9255. // FIXME: If the types do differ in this way, it would be better to
  9256. // retain the 'noexcept' form of the type.
  9257. if (!T.isNull() &&
  9258. !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
  9259. NewFD->getType()))
  9260. // The type of this function differs from the type of the builtin,
  9261. // so forget about the builtin entirely.
  9262. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  9263. }
  9264. // If this function is declared as being extern "C", then check to see if
  9265. // the function returns a UDT (class, struct, or union type) that is not C
  9266. // compatible, and if it does, warn the user.
  9267. // But, issue any diagnostic on the first declaration only.
  9268. if (Previous.empty() && NewFD->isExternC()) {
  9269. QualType R = NewFD->getReturnType();
  9270. if (R->isIncompleteType() && !R->isVoidType())
  9271. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  9272. << NewFD << R;
  9273. else if (!R.isPODType(Context) && !R->isVoidType() &&
  9274. !R->isObjCObjectPointerType())
  9275. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  9276. }
  9277. // C++1z [dcl.fct]p6:
  9278. // [...] whether the function has a non-throwing exception-specification
  9279. // [is] part of the function type
  9280. //
  9281. // This results in an ABI break between C++14 and C++17 for functions whose
  9282. // declared type includes an exception-specification in a parameter or
  9283. // return type. (Exception specifications on the function itself are OK in
  9284. // most cases, and exception specifications are not permitted in most other
  9285. // contexts where they could make it into a mangling.)
  9286. if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
  9287. auto HasNoexcept = [&](QualType T) -> bool {
  9288. // Strip off declarator chunks that could be between us and a function
  9289. // type. We don't need to look far, exception specifications are very
  9290. // restricted prior to C++17.
  9291. if (auto *RT = T->getAs<ReferenceType>())
  9292. T = RT->getPointeeType();
  9293. else if (T->isAnyPointerType())
  9294. T = T->getPointeeType();
  9295. else if (auto *MPT = T->getAs<MemberPointerType>())
  9296. T = MPT->getPointeeType();
  9297. if (auto *FPT = T->getAs<FunctionProtoType>())
  9298. if (FPT->isNothrow())
  9299. return true;
  9300. return false;
  9301. };
  9302. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  9303. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  9304. for (QualType T : FPT->param_types())
  9305. AnyNoexcept |= HasNoexcept(T);
  9306. if (AnyNoexcept)
  9307. Diag(NewFD->getLocation(),
  9308. diag::warn_cxx17_compat_exception_spec_in_signature)
  9309. << NewFD;
  9310. }
  9311. if (!Redeclaration && LangOpts.CUDA)
  9312. checkCUDATargetOverload(NewFD, Previous);
  9313. }
  9314. return Redeclaration;
  9315. }
  9316. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  9317. // C++11 [basic.start.main]p3:
  9318. // A program that [...] declares main to be inline, static or
  9319. // constexpr is ill-formed.
  9320. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  9321. // appear in a declaration of main.
  9322. // static main is not an error under C99, but we should warn about it.
  9323. // We accept _Noreturn main as an extension.
  9324. if (FD->getStorageClass() == SC_Static)
  9325. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  9326. ? diag::err_static_main : diag::warn_static_main)
  9327. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  9328. if (FD->isInlineSpecified())
  9329. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  9330. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  9331. if (DS.isNoreturnSpecified()) {
  9332. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  9333. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  9334. Diag(NoreturnLoc, diag::ext_noreturn_main);
  9335. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  9336. << FixItHint::CreateRemoval(NoreturnRange);
  9337. }
  9338. if (FD->isConstexpr()) {
  9339. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  9340. << FD->isConsteval()
  9341. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  9342. FD->setConstexprKind(CSK_unspecified);
  9343. }
  9344. if (getLangOpts().OpenCL) {
  9345. Diag(FD->getLocation(), diag::err_opencl_no_main)
  9346. << FD->hasAttr<OpenCLKernelAttr>();
  9347. FD->setInvalidDecl();
  9348. return;
  9349. }
  9350. QualType T = FD->getType();
  9351. assert(T->isFunctionType() && "function decl is not of function type");
  9352. const FunctionType* FT = T->castAs<FunctionType>();
  9353. // Set default calling convention for main()
  9354. if (FT->getCallConv() != CC_C) {
  9355. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
  9356. FD->setType(QualType(FT, 0));
  9357. T = Context.getCanonicalType(FD->getType());
  9358. }
  9359. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  9360. // In C with GNU extensions we allow main() to have non-integer return
  9361. // type, but we should warn about the extension, and we disable the
  9362. // implicit-return-zero rule.
  9363. // GCC in C mode accepts qualified 'int'.
  9364. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  9365. FD->setHasImplicitReturnZero(true);
  9366. else {
  9367. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  9368. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9369. if (RTRange.isValid())
  9370. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  9371. << FixItHint::CreateReplacement(RTRange, "int");
  9372. }
  9373. } else {
  9374. // In C and C++, main magically returns 0 if you fall off the end;
  9375. // set the flag which tells us that.
  9376. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  9377. // All the standards say that main() should return 'int'.
  9378. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  9379. FD->setHasImplicitReturnZero(true);
  9380. else {
  9381. // Otherwise, this is just a flat-out error.
  9382. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9383. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  9384. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  9385. : FixItHint());
  9386. FD->setInvalidDecl(true);
  9387. }
  9388. }
  9389. // Treat protoless main() as nullary.
  9390. if (isa<FunctionNoProtoType>(FT)) return;
  9391. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  9392. unsigned nparams = FTP->getNumParams();
  9393. assert(FD->getNumParams() == nparams);
  9394. bool HasExtraParameters = (nparams > 3);
  9395. if (FTP->isVariadic()) {
  9396. Diag(FD->getLocation(), diag::ext_variadic_main);
  9397. // FIXME: if we had information about the location of the ellipsis, we
  9398. // could add a FixIt hint to remove it as a parameter.
  9399. }
  9400. // Darwin passes an undocumented fourth argument of type char**. If
  9401. // other platforms start sprouting these, the logic below will start
  9402. // getting shifty.
  9403. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  9404. HasExtraParameters = false;
  9405. if (HasExtraParameters) {
  9406. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  9407. FD->setInvalidDecl(true);
  9408. nparams = 3;
  9409. }
  9410. // FIXME: a lot of the following diagnostics would be improved
  9411. // if we had some location information about types.
  9412. QualType CharPP =
  9413. Context.getPointerType(Context.getPointerType(Context.CharTy));
  9414. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  9415. for (unsigned i = 0; i < nparams; ++i) {
  9416. QualType AT = FTP->getParamType(i);
  9417. bool mismatch = true;
  9418. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  9419. mismatch = false;
  9420. else if (Expected[i] == CharPP) {
  9421. // As an extension, the following forms are okay:
  9422. // char const **
  9423. // char const * const *
  9424. // char * const *
  9425. QualifierCollector qs;
  9426. const PointerType* PT;
  9427. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  9428. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  9429. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  9430. Context.CharTy)) {
  9431. qs.removeConst();
  9432. mismatch = !qs.empty();
  9433. }
  9434. }
  9435. if (mismatch) {
  9436. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  9437. // TODO: suggest replacing given type with expected type
  9438. FD->setInvalidDecl(true);
  9439. }
  9440. }
  9441. if (nparams == 1 && !FD->isInvalidDecl()) {
  9442. Diag(FD->getLocation(), diag::warn_main_one_arg);
  9443. }
  9444. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9445. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9446. FD->setInvalidDecl();
  9447. }
  9448. }
  9449. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  9450. QualType T = FD->getType();
  9451. assert(T->isFunctionType() && "function decl is not of function type");
  9452. const FunctionType *FT = T->castAs<FunctionType>();
  9453. // Set an implicit return of 'zero' if the function can return some integral,
  9454. // enumeration, pointer or nullptr type.
  9455. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  9456. FT->getReturnType()->isAnyPointerType() ||
  9457. FT->getReturnType()->isNullPtrType())
  9458. // DllMain is exempt because a return value of zero means it failed.
  9459. if (FD->getName() != "DllMain")
  9460. FD->setHasImplicitReturnZero(true);
  9461. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9462. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9463. FD->setInvalidDecl();
  9464. }
  9465. }
  9466. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  9467. // FIXME: Need strict checking. In C89, we need to check for
  9468. // any assignment, increment, decrement, function-calls, or
  9469. // commas outside of a sizeof. In C99, it's the same list,
  9470. // except that the aforementioned are allowed in unevaluated
  9471. // expressions. Everything else falls under the
  9472. // "may accept other forms of constant expressions" exception.
  9473. // (We never end up here for C++, so the constant expression
  9474. // rules there don't matter.)
  9475. const Expr *Culprit;
  9476. if (Init->isConstantInitializer(Context, false, &Culprit))
  9477. return false;
  9478. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  9479. << Culprit->getSourceRange();
  9480. return true;
  9481. }
  9482. namespace {
  9483. // Visits an initialization expression to see if OrigDecl is evaluated in
  9484. // its own initialization and throws a warning if it does.
  9485. class SelfReferenceChecker
  9486. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  9487. Sema &S;
  9488. Decl *OrigDecl;
  9489. bool isRecordType;
  9490. bool isPODType;
  9491. bool isReferenceType;
  9492. bool isInitList;
  9493. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  9494. public:
  9495. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  9496. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  9497. S(S), OrigDecl(OrigDecl) {
  9498. isPODType = false;
  9499. isRecordType = false;
  9500. isReferenceType = false;
  9501. isInitList = false;
  9502. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  9503. isPODType = VD->getType().isPODType(S.Context);
  9504. isRecordType = VD->getType()->isRecordType();
  9505. isReferenceType = VD->getType()->isReferenceType();
  9506. }
  9507. }
  9508. // For most expressions, just call the visitor. For initializer lists,
  9509. // track the index of the field being initialized since fields are
  9510. // initialized in order allowing use of previously initialized fields.
  9511. void CheckExpr(Expr *E) {
  9512. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  9513. if (!InitList) {
  9514. Visit(E);
  9515. return;
  9516. }
  9517. // Track and increment the index here.
  9518. isInitList = true;
  9519. InitFieldIndex.push_back(0);
  9520. for (auto Child : InitList->children()) {
  9521. CheckExpr(cast<Expr>(Child));
  9522. ++InitFieldIndex.back();
  9523. }
  9524. InitFieldIndex.pop_back();
  9525. }
  9526. // Returns true if MemberExpr is checked and no further checking is needed.
  9527. // Returns false if additional checking is required.
  9528. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  9529. llvm::SmallVector<FieldDecl*, 4> Fields;
  9530. Expr *Base = E;
  9531. bool ReferenceField = false;
  9532. // Get the field members used.
  9533. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9534. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  9535. if (!FD)
  9536. return false;
  9537. Fields.push_back(FD);
  9538. if (FD->getType()->isReferenceType())
  9539. ReferenceField = true;
  9540. Base = ME->getBase()->IgnoreParenImpCasts();
  9541. }
  9542. // Keep checking only if the base Decl is the same.
  9543. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  9544. if (!DRE || DRE->getDecl() != OrigDecl)
  9545. return false;
  9546. // A reference field can be bound to an unininitialized field.
  9547. if (CheckReference && !ReferenceField)
  9548. return true;
  9549. // Convert FieldDecls to their index number.
  9550. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  9551. for (const FieldDecl *I : llvm::reverse(Fields))
  9552. UsedFieldIndex.push_back(I->getFieldIndex());
  9553. // See if a warning is needed by checking the first difference in index
  9554. // numbers. If field being used has index less than the field being
  9555. // initialized, then the use is safe.
  9556. for (auto UsedIter = UsedFieldIndex.begin(),
  9557. UsedEnd = UsedFieldIndex.end(),
  9558. OrigIter = InitFieldIndex.begin(),
  9559. OrigEnd = InitFieldIndex.end();
  9560. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  9561. if (*UsedIter < *OrigIter)
  9562. return true;
  9563. if (*UsedIter > *OrigIter)
  9564. break;
  9565. }
  9566. // TODO: Add a different warning which will print the field names.
  9567. HandleDeclRefExpr(DRE);
  9568. return true;
  9569. }
  9570. // For most expressions, the cast is directly above the DeclRefExpr.
  9571. // For conditional operators, the cast can be outside the conditional
  9572. // operator if both expressions are DeclRefExpr's.
  9573. void HandleValue(Expr *E) {
  9574. E = E->IgnoreParens();
  9575. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  9576. HandleDeclRefExpr(DRE);
  9577. return;
  9578. }
  9579. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  9580. Visit(CO->getCond());
  9581. HandleValue(CO->getTrueExpr());
  9582. HandleValue(CO->getFalseExpr());
  9583. return;
  9584. }
  9585. if (BinaryConditionalOperator *BCO =
  9586. dyn_cast<BinaryConditionalOperator>(E)) {
  9587. Visit(BCO->getCond());
  9588. HandleValue(BCO->getFalseExpr());
  9589. return;
  9590. }
  9591. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  9592. HandleValue(OVE->getSourceExpr());
  9593. return;
  9594. }
  9595. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9596. if (BO->getOpcode() == BO_Comma) {
  9597. Visit(BO->getLHS());
  9598. HandleValue(BO->getRHS());
  9599. return;
  9600. }
  9601. }
  9602. if (isa<MemberExpr>(E)) {
  9603. if (isInitList) {
  9604. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  9605. false /*CheckReference*/))
  9606. return;
  9607. }
  9608. Expr *Base = E->IgnoreParenImpCasts();
  9609. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9610. // Check for static member variables and don't warn on them.
  9611. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9612. return;
  9613. Base = ME->getBase()->IgnoreParenImpCasts();
  9614. }
  9615. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  9616. HandleDeclRefExpr(DRE);
  9617. return;
  9618. }
  9619. Visit(E);
  9620. }
  9621. // Reference types not handled in HandleValue are handled here since all
  9622. // uses of references are bad, not just r-value uses.
  9623. void VisitDeclRefExpr(DeclRefExpr *E) {
  9624. if (isReferenceType)
  9625. HandleDeclRefExpr(E);
  9626. }
  9627. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  9628. if (E->getCastKind() == CK_LValueToRValue) {
  9629. HandleValue(E->getSubExpr());
  9630. return;
  9631. }
  9632. Inherited::VisitImplicitCastExpr(E);
  9633. }
  9634. void VisitMemberExpr(MemberExpr *E) {
  9635. if (isInitList) {
  9636. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  9637. return;
  9638. }
  9639. // Don't warn on arrays since they can be treated as pointers.
  9640. if (E->getType()->canDecayToPointerType()) return;
  9641. // Warn when a non-static method call is followed by non-static member
  9642. // field accesses, which is followed by a DeclRefExpr.
  9643. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  9644. bool Warn = (MD && !MD->isStatic());
  9645. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  9646. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9647. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9648. Warn = false;
  9649. Base = ME->getBase()->IgnoreParenImpCasts();
  9650. }
  9651. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  9652. if (Warn)
  9653. HandleDeclRefExpr(DRE);
  9654. return;
  9655. }
  9656. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  9657. // Visit that expression.
  9658. Visit(Base);
  9659. }
  9660. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  9661. Expr *Callee = E->getCallee();
  9662. if (isa<UnresolvedLookupExpr>(Callee))
  9663. return Inherited::VisitCXXOperatorCallExpr(E);
  9664. Visit(Callee);
  9665. for (auto Arg: E->arguments())
  9666. HandleValue(Arg->IgnoreParenImpCasts());
  9667. }
  9668. void VisitUnaryOperator(UnaryOperator *E) {
  9669. // For POD record types, addresses of its own members are well-defined.
  9670. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  9671. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  9672. if (!isPODType)
  9673. HandleValue(E->getSubExpr());
  9674. return;
  9675. }
  9676. if (E->isIncrementDecrementOp()) {
  9677. HandleValue(E->getSubExpr());
  9678. return;
  9679. }
  9680. Inherited::VisitUnaryOperator(E);
  9681. }
  9682. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  9683. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  9684. if (E->getConstructor()->isCopyConstructor()) {
  9685. Expr *ArgExpr = E->getArg(0);
  9686. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  9687. if (ILE->getNumInits() == 1)
  9688. ArgExpr = ILE->getInit(0);
  9689. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  9690. if (ICE->getCastKind() == CK_NoOp)
  9691. ArgExpr = ICE->getSubExpr();
  9692. HandleValue(ArgExpr);
  9693. return;
  9694. }
  9695. Inherited::VisitCXXConstructExpr(E);
  9696. }
  9697. void VisitCallExpr(CallExpr *E) {
  9698. // Treat std::move as a use.
  9699. if (E->isCallToStdMove()) {
  9700. HandleValue(E->getArg(0));
  9701. return;
  9702. }
  9703. Inherited::VisitCallExpr(E);
  9704. }
  9705. void VisitBinaryOperator(BinaryOperator *E) {
  9706. if (E->isCompoundAssignmentOp()) {
  9707. HandleValue(E->getLHS());
  9708. Visit(E->getRHS());
  9709. return;
  9710. }
  9711. Inherited::VisitBinaryOperator(E);
  9712. }
  9713. // A custom visitor for BinaryConditionalOperator is needed because the
  9714. // regular visitor would check the condition and true expression separately
  9715. // but both point to the same place giving duplicate diagnostics.
  9716. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  9717. Visit(E->getCond());
  9718. Visit(E->getFalseExpr());
  9719. }
  9720. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  9721. Decl* ReferenceDecl = DRE->getDecl();
  9722. if (OrigDecl != ReferenceDecl) return;
  9723. unsigned diag;
  9724. if (isReferenceType) {
  9725. diag = diag::warn_uninit_self_reference_in_reference_init;
  9726. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  9727. diag = diag::warn_static_self_reference_in_init;
  9728. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  9729. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  9730. DRE->getDecl()->getType()->isRecordType()) {
  9731. diag = diag::warn_uninit_self_reference_in_init;
  9732. } else {
  9733. // Local variables will be handled by the CFG analysis.
  9734. return;
  9735. }
  9736. S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
  9737. S.PDiag(diag)
  9738. << DRE->getDecl() << OrigDecl->getLocation()
  9739. << DRE->getSourceRange());
  9740. }
  9741. };
  9742. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  9743. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  9744. bool DirectInit) {
  9745. // Parameters arguments are occassionially constructed with itself,
  9746. // for instance, in recursive functions. Skip them.
  9747. if (isa<ParmVarDecl>(OrigDecl))
  9748. return;
  9749. E = E->IgnoreParens();
  9750. // Skip checking T a = a where T is not a record or reference type.
  9751. // Doing so is a way to silence uninitialized warnings.
  9752. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  9753. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  9754. if (ICE->getCastKind() == CK_LValueToRValue)
  9755. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  9756. if (DRE->getDecl() == OrigDecl)
  9757. return;
  9758. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  9759. }
  9760. } // end anonymous namespace
  9761. namespace {
  9762. // Simple wrapper to add the name of a variable or (if no variable is
  9763. // available) a DeclarationName into a diagnostic.
  9764. struct VarDeclOrName {
  9765. VarDecl *VDecl;
  9766. DeclarationName Name;
  9767. friend const Sema::SemaDiagnosticBuilder &
  9768. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  9769. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  9770. }
  9771. };
  9772. } // end anonymous namespace
  9773. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  9774. DeclarationName Name, QualType Type,
  9775. TypeSourceInfo *TSI,
  9776. SourceRange Range, bool DirectInit,
  9777. Expr *Init) {
  9778. bool IsInitCapture = !VDecl;
  9779. assert((!VDecl || !VDecl->isInitCapture()) &&
  9780. "init captures are expected to be deduced prior to initialization");
  9781. VarDeclOrName VN{VDecl, Name};
  9782. DeducedType *Deduced = Type->getContainedDeducedType();
  9783. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  9784. // C++11 [dcl.spec.auto]p3
  9785. if (!Init) {
  9786. assert(VDecl && "no init for init capture deduction?");
  9787. // Except for class argument deduction, and then for an initializing
  9788. // declaration only, i.e. no static at class scope or extern.
  9789. if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
  9790. VDecl->hasExternalStorage() ||
  9791. VDecl->isStaticDataMember()) {
  9792. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  9793. << VDecl->getDeclName() << Type;
  9794. return QualType();
  9795. }
  9796. }
  9797. ArrayRef<Expr*> DeduceInits;
  9798. if (Init)
  9799. DeduceInits = Init;
  9800. if (DirectInit) {
  9801. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  9802. DeduceInits = PL->exprs();
  9803. }
  9804. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  9805. assert(VDecl && "non-auto type for init capture deduction?");
  9806. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9807. InitializationKind Kind = InitializationKind::CreateForInit(
  9808. VDecl->getLocation(), DirectInit, Init);
  9809. // FIXME: Initialization should not be taking a mutable list of inits.
  9810. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  9811. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  9812. InitsCopy);
  9813. }
  9814. if (DirectInit) {
  9815. if (auto *IL = dyn_cast<InitListExpr>(Init))
  9816. DeduceInits = IL->inits();
  9817. }
  9818. // Deduction only works if we have exactly one source expression.
  9819. if (DeduceInits.empty()) {
  9820. // It isn't possible to write this directly, but it is possible to
  9821. // end up in this situation with "auto x(some_pack...);"
  9822. Diag(Init->getBeginLoc(), IsInitCapture
  9823. ? diag::err_init_capture_no_expression
  9824. : diag::err_auto_var_init_no_expression)
  9825. << VN << Type << Range;
  9826. return QualType();
  9827. }
  9828. if (DeduceInits.size() > 1) {
  9829. Diag(DeduceInits[1]->getBeginLoc(),
  9830. IsInitCapture ? diag::err_init_capture_multiple_expressions
  9831. : diag::err_auto_var_init_multiple_expressions)
  9832. << VN << Type << Range;
  9833. return QualType();
  9834. }
  9835. Expr *DeduceInit = DeduceInits[0];
  9836. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  9837. Diag(Init->getBeginLoc(), IsInitCapture
  9838. ? diag::err_init_capture_paren_braces
  9839. : diag::err_auto_var_init_paren_braces)
  9840. << isa<InitListExpr>(Init) << VN << Type << Range;
  9841. return QualType();
  9842. }
  9843. // Expressions default to 'id' when we're in a debugger.
  9844. bool DefaultedAnyToId = false;
  9845. if (getLangOpts().DebuggerCastResultToId &&
  9846. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  9847. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9848. if (Result.isInvalid()) {
  9849. return QualType();
  9850. }
  9851. Init = Result.get();
  9852. DefaultedAnyToId = true;
  9853. }
  9854. // C++ [dcl.decomp]p1:
  9855. // If the assignment-expression [...] has array type A and no ref-qualifier
  9856. // is present, e has type cv A
  9857. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  9858. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  9859. DeduceInit->getType()->isConstantArrayType())
  9860. return Context.getQualifiedType(DeduceInit->getType(),
  9861. Type.getQualifiers());
  9862. QualType DeducedType;
  9863. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  9864. if (!IsInitCapture)
  9865. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  9866. else if (isa<InitListExpr>(Init))
  9867. Diag(Range.getBegin(),
  9868. diag::err_init_capture_deduction_failure_from_init_list)
  9869. << VN
  9870. << (DeduceInit->getType().isNull() ? TSI->getType()
  9871. : DeduceInit->getType())
  9872. << DeduceInit->getSourceRange();
  9873. else
  9874. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  9875. << VN << TSI->getType()
  9876. << (DeduceInit->getType().isNull() ? TSI->getType()
  9877. : DeduceInit->getType())
  9878. << DeduceInit->getSourceRange();
  9879. }
  9880. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  9881. // 'id' instead of a specific object type prevents most of our usual
  9882. // checks.
  9883. // We only want to warn outside of template instantiations, though:
  9884. // inside a template, the 'id' could have come from a parameter.
  9885. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  9886. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  9887. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  9888. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  9889. }
  9890. return DeducedType;
  9891. }
  9892. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  9893. Expr *Init) {
  9894. QualType DeducedType = deduceVarTypeFromInitializer(
  9895. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  9896. VDecl->getSourceRange(), DirectInit, Init);
  9897. if (DeducedType.isNull()) {
  9898. VDecl->setInvalidDecl();
  9899. return true;
  9900. }
  9901. VDecl->setType(DeducedType);
  9902. assert(VDecl->isLinkageValid());
  9903. // In ARC, infer lifetime.
  9904. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  9905. VDecl->setInvalidDecl();
  9906. // If this is a redeclaration, check that the type we just deduced matches
  9907. // the previously declared type.
  9908. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  9909. // We never need to merge the type, because we cannot form an incomplete
  9910. // array of auto, nor deduce such a type.
  9911. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  9912. }
  9913. // Check the deduced type is valid for a variable declaration.
  9914. CheckVariableDeclarationType(VDecl);
  9915. return VDecl->isInvalidDecl();
  9916. }
  9917. void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
  9918. SourceLocation Loc) {
  9919. if (auto *CE = dyn_cast<ConstantExpr>(Init))
  9920. Init = CE->getSubExpr();
  9921. QualType InitType = Init->getType();
  9922. assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  9923. InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
  9924. "shouldn't be called if type doesn't have a non-trivial C struct");
  9925. if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
  9926. for (auto I : ILE->inits()) {
  9927. if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
  9928. !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
  9929. continue;
  9930. SourceLocation SL = I->getExprLoc();
  9931. checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
  9932. }
  9933. return;
  9934. }
  9935. if (isa<ImplicitValueInitExpr>(Init)) {
  9936. if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  9937. checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
  9938. NTCUK_Init);
  9939. } else {
  9940. // Assume all other explicit initializers involving copying some existing
  9941. // object.
  9942. // TODO: ignore any explicit initializers where we can guarantee
  9943. // copy-elision.
  9944. if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
  9945. checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
  9946. }
  9947. }
  9948. namespace {
  9949. bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
  9950. // Ignore unavailable fields. A field can be marked as unavailable explicitly
  9951. // in the source code or implicitly by the compiler if it is in a union
  9952. // defined in a system header and has non-trivial ObjC ownership
  9953. // qualifications. We don't want those fields to participate in determining
  9954. // whether the containing union is non-trivial.
  9955. return FD->hasAttr<UnavailableAttr>();
  9956. }
  9957. struct DiagNonTrivalCUnionDefaultInitializeVisitor
  9958. : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  9959. void> {
  9960. using Super =
  9961. DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  9962. void>;
  9963. DiagNonTrivalCUnionDefaultInitializeVisitor(
  9964. QualType OrigTy, SourceLocation OrigLoc,
  9965. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  9966. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  9967. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
  9968. const FieldDecl *FD, bool InNonTrivialUnion) {
  9969. if (const auto *AT = S.Context.getAsArrayType(QT))
  9970. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  9971. InNonTrivialUnion);
  9972. return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
  9973. }
  9974. void visitARCStrong(QualType QT, const FieldDecl *FD,
  9975. bool InNonTrivialUnion) {
  9976. if (InNonTrivialUnion)
  9977. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9978. << 1 << 0 << QT << FD->getName();
  9979. }
  9980. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9981. if (InNonTrivialUnion)
  9982. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9983. << 1 << 0 << QT << FD->getName();
  9984. }
  9985. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9986. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  9987. if (RD->isUnion()) {
  9988. if (OrigLoc.isValid()) {
  9989. bool IsUnion = false;
  9990. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  9991. IsUnion = OrigRD->isUnion();
  9992. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  9993. << 0 << OrigTy << IsUnion << UseContext;
  9994. // Reset OrigLoc so that this diagnostic is emitted only once.
  9995. OrigLoc = SourceLocation();
  9996. }
  9997. InNonTrivialUnion = true;
  9998. }
  9999. if (InNonTrivialUnion)
  10000. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  10001. << 0 << 0 << QT.getUnqualifiedType() << "";
  10002. for (const FieldDecl *FD : RD->fields())
  10003. if (!shouldIgnoreForRecordTriviality(FD))
  10004. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  10005. }
  10006. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  10007. // The non-trivial C union type or the struct/union type that contains a
  10008. // non-trivial C union.
  10009. QualType OrigTy;
  10010. SourceLocation OrigLoc;
  10011. Sema::NonTrivialCUnionContext UseContext;
  10012. Sema &S;
  10013. };
  10014. struct DiagNonTrivalCUnionDestructedTypeVisitor
  10015. : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
  10016. using Super =
  10017. DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
  10018. DiagNonTrivalCUnionDestructedTypeVisitor(
  10019. QualType OrigTy, SourceLocation OrigLoc,
  10020. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  10021. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  10022. void visitWithKind(QualType::DestructionKind DK, QualType QT,
  10023. const FieldDecl *FD, bool InNonTrivialUnion) {
  10024. if (const auto *AT = S.Context.getAsArrayType(QT))
  10025. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  10026. InNonTrivialUnion);
  10027. return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
  10028. }
  10029. void visitARCStrong(QualType QT, const FieldDecl *FD,
  10030. bool InNonTrivialUnion) {
  10031. if (InNonTrivialUnion)
  10032. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10033. << 1 << 1 << QT << FD->getName();
  10034. }
  10035. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10036. if (InNonTrivialUnion)
  10037. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10038. << 1 << 1 << QT << FD->getName();
  10039. }
  10040. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10041. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  10042. if (RD->isUnion()) {
  10043. if (OrigLoc.isValid()) {
  10044. bool IsUnion = false;
  10045. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  10046. IsUnion = OrigRD->isUnion();
  10047. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  10048. << 1 << OrigTy << IsUnion << UseContext;
  10049. // Reset OrigLoc so that this diagnostic is emitted only once.
  10050. OrigLoc = SourceLocation();
  10051. }
  10052. InNonTrivialUnion = true;
  10053. }
  10054. if (InNonTrivialUnion)
  10055. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  10056. << 0 << 1 << QT.getUnqualifiedType() << "";
  10057. for (const FieldDecl *FD : RD->fields())
  10058. if (!shouldIgnoreForRecordTriviality(FD))
  10059. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  10060. }
  10061. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  10062. void visitCXXDestructor(QualType QT, const FieldDecl *FD,
  10063. bool InNonTrivialUnion) {}
  10064. // The non-trivial C union type or the struct/union type that contains a
  10065. // non-trivial C union.
  10066. QualType OrigTy;
  10067. SourceLocation OrigLoc;
  10068. Sema::NonTrivialCUnionContext UseContext;
  10069. Sema &S;
  10070. };
  10071. struct DiagNonTrivalCUnionCopyVisitor
  10072. : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
  10073. using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
  10074. DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
  10075. Sema::NonTrivialCUnionContext UseContext,
  10076. Sema &S)
  10077. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  10078. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
  10079. const FieldDecl *FD, bool InNonTrivialUnion) {
  10080. if (const auto *AT = S.Context.getAsArrayType(QT))
  10081. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  10082. InNonTrivialUnion);
  10083. return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
  10084. }
  10085. void visitARCStrong(QualType QT, const FieldDecl *FD,
  10086. bool InNonTrivialUnion) {
  10087. if (InNonTrivialUnion)
  10088. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10089. << 1 << 2 << QT << FD->getName();
  10090. }
  10091. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10092. if (InNonTrivialUnion)
  10093. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10094. << 1 << 2 << QT << FD->getName();
  10095. }
  10096. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10097. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  10098. if (RD->isUnion()) {
  10099. if (OrigLoc.isValid()) {
  10100. bool IsUnion = false;
  10101. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  10102. IsUnion = OrigRD->isUnion();
  10103. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  10104. << 2 << OrigTy << IsUnion << UseContext;
  10105. // Reset OrigLoc so that this diagnostic is emitted only once.
  10106. OrigLoc = SourceLocation();
  10107. }
  10108. InNonTrivialUnion = true;
  10109. }
  10110. if (InNonTrivialUnion)
  10111. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  10112. << 0 << 2 << QT.getUnqualifiedType() << "";
  10113. for (const FieldDecl *FD : RD->fields())
  10114. if (!shouldIgnoreForRecordTriviality(FD))
  10115. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  10116. }
  10117. void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
  10118. const FieldDecl *FD, bool InNonTrivialUnion) {}
  10119. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  10120. void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
  10121. bool InNonTrivialUnion) {}
  10122. // The non-trivial C union type or the struct/union type that contains a
  10123. // non-trivial C union.
  10124. QualType OrigTy;
  10125. SourceLocation OrigLoc;
  10126. Sema::NonTrivialCUnionContext UseContext;
  10127. Sema &S;
  10128. };
  10129. } // namespace
  10130. void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
  10131. NonTrivialCUnionContext UseContext,
  10132. unsigned NonTrivialKind) {
  10133. assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  10134. QT.hasNonTrivialToPrimitiveDestructCUnion() ||
  10135. QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
  10136. "shouldn't be called if type doesn't have a non-trivial C union");
  10137. if ((NonTrivialKind & NTCUK_Init) &&
  10138. QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  10139. DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
  10140. .visit(QT, nullptr, false);
  10141. if ((NonTrivialKind & NTCUK_Destruct) &&
  10142. QT.hasNonTrivialToPrimitiveDestructCUnion())
  10143. DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
  10144. .visit(QT, nullptr, false);
  10145. if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
  10146. DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
  10147. .visit(QT, nullptr, false);
  10148. }
  10149. /// AddInitializerToDecl - Adds the initializer Init to the
  10150. /// declaration dcl. If DirectInit is true, this is C++ direct
  10151. /// initialization rather than copy initialization.
  10152. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  10153. // If there is no declaration, there was an error parsing it. Just ignore
  10154. // the initializer.
  10155. if (!RealDecl || RealDecl->isInvalidDecl()) {
  10156. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  10157. return;
  10158. }
  10159. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  10160. // Pure-specifiers are handled in ActOnPureSpecifier.
  10161. Diag(Method->getLocation(), diag::err_member_function_initialization)
  10162. << Method->getDeclName() << Init->getSourceRange();
  10163. Method->setInvalidDecl();
  10164. return;
  10165. }
  10166. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  10167. if (!VDecl) {
  10168. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  10169. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  10170. RealDecl->setInvalidDecl();
  10171. return;
  10172. }
  10173. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  10174. if (VDecl->getType()->isUndeducedType()) {
  10175. // Attempt typo correction early so that the type of the init expression can
  10176. // be deduced based on the chosen correction if the original init contains a
  10177. // TypoExpr.
  10178. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  10179. if (!Res.isUsable()) {
  10180. RealDecl->setInvalidDecl();
  10181. return;
  10182. }
  10183. Init = Res.get();
  10184. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  10185. return;
  10186. }
  10187. // dllimport cannot be used on variable definitions.
  10188. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  10189. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  10190. VDecl->setInvalidDecl();
  10191. return;
  10192. }
  10193. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  10194. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  10195. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  10196. VDecl->setInvalidDecl();
  10197. return;
  10198. }
  10199. if (!VDecl->getType()->isDependentType()) {
  10200. // A definition must end up with a complete type, which means it must be
  10201. // complete with the restriction that an array type might be completed by
  10202. // the initializer; note that later code assumes this restriction.
  10203. QualType BaseDeclType = VDecl->getType();
  10204. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  10205. BaseDeclType = Array->getElementType();
  10206. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  10207. diag::err_typecheck_decl_incomplete_type)) {
  10208. RealDecl->setInvalidDecl();
  10209. return;
  10210. }
  10211. // The variable can not have an abstract class type.
  10212. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  10213. diag::err_abstract_type_in_decl,
  10214. AbstractVariableType))
  10215. VDecl->setInvalidDecl();
  10216. }
  10217. // If adding the initializer will turn this declaration into a definition,
  10218. // and we already have a definition for this variable, diagnose or otherwise
  10219. // handle the situation.
  10220. VarDecl *Def;
  10221. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  10222. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  10223. !VDecl->isThisDeclarationADemotedDefinition() &&
  10224. checkVarDeclRedefinition(Def, VDecl))
  10225. return;
  10226. if (getLangOpts().CPlusPlus) {
  10227. // C++ [class.static.data]p4
  10228. // If a static data member is of const integral or const
  10229. // enumeration type, its declaration in the class definition can
  10230. // specify a constant-initializer which shall be an integral
  10231. // constant expression (5.19). In that case, the member can appear
  10232. // in integral constant expressions. The member shall still be
  10233. // defined in a namespace scope if it is used in the program and the
  10234. // namespace scope definition shall not contain an initializer.
  10235. //
  10236. // We already performed a redefinition check above, but for static
  10237. // data members we also need to check whether there was an in-class
  10238. // declaration with an initializer.
  10239. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  10240. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  10241. << VDecl->getDeclName();
  10242. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  10243. diag::note_previous_initializer)
  10244. << 0;
  10245. return;
  10246. }
  10247. if (VDecl->hasLocalStorage())
  10248. setFunctionHasBranchProtectedScope();
  10249. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  10250. VDecl->setInvalidDecl();
  10251. return;
  10252. }
  10253. }
  10254. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  10255. // a kernel function cannot be initialized."
  10256. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  10257. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  10258. VDecl->setInvalidDecl();
  10259. return;
  10260. }
  10261. // Get the decls type and save a reference for later, since
  10262. // CheckInitializerTypes may change it.
  10263. QualType DclT = VDecl->getType(), SavT = DclT;
  10264. // Expressions default to 'id' when we're in a debugger
  10265. // and we are assigning it to a variable of Objective-C pointer type.
  10266. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  10267. Init->getType() == Context.UnknownAnyTy) {
  10268. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  10269. if (Result.isInvalid()) {
  10270. VDecl->setInvalidDecl();
  10271. return;
  10272. }
  10273. Init = Result.get();
  10274. }
  10275. // Perform the initialization.
  10276. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  10277. if (!VDecl->isInvalidDecl()) {
  10278. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  10279. InitializationKind Kind = InitializationKind::CreateForInit(
  10280. VDecl->getLocation(), DirectInit, Init);
  10281. MultiExprArg Args = Init;
  10282. if (CXXDirectInit)
  10283. Args = MultiExprArg(CXXDirectInit->getExprs(),
  10284. CXXDirectInit->getNumExprs());
  10285. // Try to correct any TypoExprs in the initialization arguments.
  10286. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  10287. ExprResult Res = CorrectDelayedTyposInExpr(
  10288. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  10289. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  10290. return Init.Failed() ? ExprError() : E;
  10291. });
  10292. if (Res.isInvalid()) {
  10293. VDecl->setInvalidDecl();
  10294. } else if (Res.get() != Args[Idx]) {
  10295. Args[Idx] = Res.get();
  10296. }
  10297. }
  10298. if (VDecl->isInvalidDecl())
  10299. return;
  10300. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  10301. /*TopLevelOfInitList=*/false,
  10302. /*TreatUnavailableAsInvalid=*/false);
  10303. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  10304. if (Result.isInvalid()) {
  10305. VDecl->setInvalidDecl();
  10306. return;
  10307. }
  10308. Init = Result.getAs<Expr>();
  10309. }
  10310. // Check for self-references within variable initializers.
  10311. // Variables declared within a function/method body (except for references)
  10312. // are handled by a dataflow analysis.
  10313. // This is undefined behavior in C++, but valid in C.
  10314. if (getLangOpts().CPlusPlus) {
  10315. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  10316. VDecl->getType()->isReferenceType()) {
  10317. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  10318. }
  10319. }
  10320. // If the type changed, it means we had an incomplete type that was
  10321. // completed by the initializer. For example:
  10322. // int ary[] = { 1, 3, 5 };
  10323. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  10324. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  10325. VDecl->setType(DclT);
  10326. if (!VDecl->isInvalidDecl()) {
  10327. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  10328. if (VDecl->hasAttr<BlocksAttr>())
  10329. checkRetainCycles(VDecl, Init);
  10330. // It is safe to assign a weak reference into a strong variable.
  10331. // Although this code can still have problems:
  10332. // id x = self.weakProp;
  10333. // id y = self.weakProp;
  10334. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  10335. // paths through the function. This should be revisited if
  10336. // -Wrepeated-use-of-weak is made flow-sensitive.
  10337. if (FunctionScopeInfo *FSI = getCurFunction())
  10338. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  10339. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  10340. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  10341. Init->getBeginLoc()))
  10342. FSI->markSafeWeakUse(Init);
  10343. }
  10344. // The initialization is usually a full-expression.
  10345. //
  10346. // FIXME: If this is a braced initialization of an aggregate, it is not
  10347. // an expression, and each individual field initializer is a separate
  10348. // full-expression. For instance, in:
  10349. //
  10350. // struct Temp { ~Temp(); };
  10351. // struct S { S(Temp); };
  10352. // struct T { S a, b; } t = { Temp(), Temp() }
  10353. //
  10354. // we should destroy the first Temp before constructing the second.
  10355. ExprResult Result =
  10356. ActOnFinishFullExpr(Init, VDecl->getLocation(),
  10357. /*DiscardedValue*/ false, VDecl->isConstexpr());
  10358. if (Result.isInvalid()) {
  10359. VDecl->setInvalidDecl();
  10360. return;
  10361. }
  10362. Init = Result.get();
  10363. // Attach the initializer to the decl.
  10364. VDecl->setInit(Init);
  10365. if (VDecl->isLocalVarDecl()) {
  10366. // Don't check the initializer if the declaration is malformed.
  10367. if (VDecl->isInvalidDecl()) {
  10368. // do nothing
  10369. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  10370. // This is true even in C++ for OpenCL.
  10371. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  10372. CheckForConstantInitializer(Init, DclT);
  10373. // Otherwise, C++ does not restrict the initializer.
  10374. } else if (getLangOpts().CPlusPlus) {
  10375. // do nothing
  10376. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  10377. // static storage duration shall be constant expressions or string literals.
  10378. } else if (VDecl->getStorageClass() == SC_Static) {
  10379. CheckForConstantInitializer(Init, DclT);
  10380. // C89 is stricter than C99 for aggregate initializers.
  10381. // C89 6.5.7p3: All the expressions [...] in an initializer list
  10382. // for an object that has aggregate or union type shall be
  10383. // constant expressions.
  10384. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  10385. isa<InitListExpr>(Init)) {
  10386. const Expr *Culprit;
  10387. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  10388. Diag(Culprit->getExprLoc(),
  10389. diag::ext_aggregate_init_not_constant)
  10390. << Culprit->getSourceRange();
  10391. }
  10392. }
  10393. if (auto *E = dyn_cast<ExprWithCleanups>(Init))
  10394. if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
  10395. if (VDecl->hasLocalStorage())
  10396. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  10397. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  10398. VDecl->getLexicalDeclContext()->isRecord()) {
  10399. // This is an in-class initialization for a static data member, e.g.,
  10400. //
  10401. // struct S {
  10402. // static const int value = 17;
  10403. // };
  10404. // C++ [class.mem]p4:
  10405. // A member-declarator can contain a constant-initializer only
  10406. // if it declares a static member (9.4) of const integral or
  10407. // const enumeration type, see 9.4.2.
  10408. //
  10409. // C++11 [class.static.data]p3:
  10410. // If a non-volatile non-inline const static data member is of integral
  10411. // or enumeration type, its declaration in the class definition can
  10412. // specify a brace-or-equal-initializer in which every initializer-clause
  10413. // that is an assignment-expression is a constant expression. A static
  10414. // data member of literal type can be declared in the class definition
  10415. // with the constexpr specifier; if so, its declaration shall specify a
  10416. // brace-or-equal-initializer in which every initializer-clause that is
  10417. // an assignment-expression is a constant expression.
  10418. // Do nothing on dependent types.
  10419. if (DclT->isDependentType()) {
  10420. // Allow any 'static constexpr' members, whether or not they are of literal
  10421. // type. We separately check that every constexpr variable is of literal
  10422. // type.
  10423. } else if (VDecl->isConstexpr()) {
  10424. // Require constness.
  10425. } else if (!DclT.isConstQualified()) {
  10426. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  10427. << Init->getSourceRange();
  10428. VDecl->setInvalidDecl();
  10429. // We allow integer constant expressions in all cases.
  10430. } else if (DclT->isIntegralOrEnumerationType()) {
  10431. // Check whether the expression is a constant expression.
  10432. SourceLocation Loc;
  10433. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  10434. // In C++11, a non-constexpr const static data member with an
  10435. // in-class initializer cannot be volatile.
  10436. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  10437. else if (Init->isValueDependent())
  10438. ; // Nothing to check.
  10439. else if (Init->isIntegerConstantExpr(Context, &Loc))
  10440. ; // Ok, it's an ICE!
  10441. else if (Init->getType()->isScopedEnumeralType() &&
  10442. Init->isCXX11ConstantExpr(Context))
  10443. ; // Ok, it is a scoped-enum constant expression.
  10444. else if (Init->isEvaluatable(Context)) {
  10445. // If we can constant fold the initializer through heroics, accept it,
  10446. // but report this as a use of an extension for -pedantic.
  10447. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  10448. << Init->getSourceRange();
  10449. } else {
  10450. // Otherwise, this is some crazy unknown case. Report the issue at the
  10451. // location provided by the isIntegerConstantExpr failed check.
  10452. Diag(Loc, diag::err_in_class_initializer_non_constant)
  10453. << Init->getSourceRange();
  10454. VDecl->setInvalidDecl();
  10455. }
  10456. // We allow foldable floating-point constants as an extension.
  10457. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  10458. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  10459. // it anyway and provide a fixit to add the 'constexpr'.
  10460. if (getLangOpts().CPlusPlus11) {
  10461. Diag(VDecl->getLocation(),
  10462. diag::ext_in_class_initializer_float_type_cxx11)
  10463. << DclT << Init->getSourceRange();
  10464. Diag(VDecl->getBeginLoc(),
  10465. diag::note_in_class_initializer_float_type_cxx11)
  10466. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10467. } else {
  10468. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  10469. << DclT << Init->getSourceRange();
  10470. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  10471. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  10472. << Init->getSourceRange();
  10473. VDecl->setInvalidDecl();
  10474. }
  10475. }
  10476. // Suggest adding 'constexpr' in C++11 for literal types.
  10477. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  10478. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  10479. << DclT << Init->getSourceRange()
  10480. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10481. VDecl->setConstexpr(true);
  10482. } else {
  10483. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  10484. << DclT << Init->getSourceRange();
  10485. VDecl->setInvalidDecl();
  10486. }
  10487. } else if (VDecl->isFileVarDecl()) {
  10488. // In C, extern is typically used to avoid tentative definitions when
  10489. // declaring variables in headers, but adding an intializer makes it a
  10490. // definition. This is somewhat confusing, so GCC and Clang both warn on it.
  10491. // In C++, extern is often used to give implictly static const variables
  10492. // external linkage, so don't warn in that case. If selectany is present,
  10493. // this might be header code intended for C and C++ inclusion, so apply the
  10494. // C++ rules.
  10495. if (VDecl->getStorageClass() == SC_Extern &&
  10496. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  10497. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  10498. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  10499. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  10500. Diag(VDecl->getLocation(), diag::warn_extern_init);
  10501. // In Microsoft C++ mode, a const variable defined in namespace scope has
  10502. // external linkage by default if the variable is declared with
  10503. // __declspec(dllexport).
  10504. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  10505. getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
  10506. VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
  10507. VDecl->setStorageClass(SC_Extern);
  10508. // C99 6.7.8p4. All file scoped initializers need to be constant.
  10509. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  10510. CheckForConstantInitializer(Init, DclT);
  10511. }
  10512. QualType InitType = Init->getType();
  10513. if (!InitType.isNull() &&
  10514. (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  10515. InitType.hasNonTrivialToPrimitiveCopyCUnion()))
  10516. checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
  10517. // We will represent direct-initialization similarly to copy-initialization:
  10518. // int x(1); -as-> int x = 1;
  10519. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  10520. //
  10521. // Clients that want to distinguish between the two forms, can check for
  10522. // direct initializer using VarDecl::getInitStyle().
  10523. // A major benefit is that clients that don't particularly care about which
  10524. // exactly form was it (like the CodeGen) can handle both cases without
  10525. // special case code.
  10526. // C++ 8.5p11:
  10527. // The form of initialization (using parentheses or '=') is generally
  10528. // insignificant, but does matter when the entity being initialized has a
  10529. // class type.
  10530. if (CXXDirectInit) {
  10531. assert(DirectInit && "Call-style initializer must be direct init.");
  10532. VDecl->setInitStyle(VarDecl::CallInit);
  10533. } else if (DirectInit) {
  10534. // This must be list-initialization. No other way is direct-initialization.
  10535. VDecl->setInitStyle(VarDecl::ListInit);
  10536. }
  10537. CheckCompleteVariableDeclaration(VDecl);
  10538. }
  10539. /// ActOnInitializerError - Given that there was an error parsing an
  10540. /// initializer for the given declaration, try to return to some form
  10541. /// of sanity.
  10542. void Sema::ActOnInitializerError(Decl *D) {
  10543. // Our main concern here is re-establishing invariants like "a
  10544. // variable's type is either dependent or complete".
  10545. if (!D || D->isInvalidDecl()) return;
  10546. VarDecl *VD = dyn_cast<VarDecl>(D);
  10547. if (!VD) return;
  10548. // Bindings are not usable if we can't make sense of the initializer.
  10549. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  10550. for (auto *BD : DD->bindings())
  10551. BD->setInvalidDecl();
  10552. // Auto types are meaningless if we can't make sense of the initializer.
  10553. if (ParsingInitForAutoVars.count(D)) {
  10554. D->setInvalidDecl();
  10555. return;
  10556. }
  10557. QualType Ty = VD->getType();
  10558. if (Ty->isDependentType()) return;
  10559. // Require a complete type.
  10560. if (RequireCompleteType(VD->getLocation(),
  10561. Context.getBaseElementType(Ty),
  10562. diag::err_typecheck_decl_incomplete_type)) {
  10563. VD->setInvalidDecl();
  10564. return;
  10565. }
  10566. // Require a non-abstract type.
  10567. if (RequireNonAbstractType(VD->getLocation(), Ty,
  10568. diag::err_abstract_type_in_decl,
  10569. AbstractVariableType)) {
  10570. VD->setInvalidDecl();
  10571. return;
  10572. }
  10573. // Don't bother complaining about constructors or destructors,
  10574. // though.
  10575. }
  10576. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  10577. // If there is no declaration, there was an error parsing it. Just ignore it.
  10578. if (!RealDecl)
  10579. return;
  10580. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  10581. QualType Type = Var->getType();
  10582. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  10583. if (isa<DecompositionDecl>(RealDecl)) {
  10584. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  10585. Var->setInvalidDecl();
  10586. return;
  10587. }
  10588. if (Type->isUndeducedType() &&
  10589. DeduceVariableDeclarationType(Var, false, nullptr))
  10590. return;
  10591. // C++11 [class.static.data]p3: A static data member can be declared with
  10592. // the constexpr specifier; if so, its declaration shall specify
  10593. // a brace-or-equal-initializer.
  10594. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  10595. // the definition of a variable [...] or the declaration of a static data
  10596. // member.
  10597. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  10598. !Var->isThisDeclarationADemotedDefinition()) {
  10599. if (Var->isStaticDataMember()) {
  10600. // C++1z removes the relevant rule; the in-class declaration is always
  10601. // a definition there.
  10602. if (!getLangOpts().CPlusPlus17 &&
  10603. !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  10604. Diag(Var->getLocation(),
  10605. diag::err_constexpr_static_mem_var_requires_init)
  10606. << Var->getDeclName();
  10607. Var->setInvalidDecl();
  10608. return;
  10609. }
  10610. } else {
  10611. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  10612. Var->setInvalidDecl();
  10613. return;
  10614. }
  10615. }
  10616. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  10617. // be initialized.
  10618. if (!Var->isInvalidDecl() &&
  10619. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  10620. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  10621. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  10622. Var->setInvalidDecl();
  10623. return;
  10624. }
  10625. VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
  10626. if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
  10627. Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  10628. checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
  10629. NTCUC_DefaultInitializedObject, NTCUK_Init);
  10630. switch (DefKind) {
  10631. case VarDecl::Definition:
  10632. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  10633. break;
  10634. // We have an out-of-line definition of a static data member
  10635. // that has an in-class initializer, so we type-check this like
  10636. // a declaration.
  10637. //
  10638. LLVM_FALLTHROUGH;
  10639. case VarDecl::DeclarationOnly:
  10640. // It's only a declaration.
  10641. // Block scope. C99 6.7p7: If an identifier for an object is
  10642. // declared with no linkage (C99 6.2.2p6), the type for the
  10643. // object shall be complete.
  10644. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  10645. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  10646. RequireCompleteType(Var->getLocation(), Type,
  10647. diag::err_typecheck_decl_incomplete_type))
  10648. Var->setInvalidDecl();
  10649. // Make sure that the type is not abstract.
  10650. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10651. RequireNonAbstractType(Var->getLocation(), Type,
  10652. diag::err_abstract_type_in_decl,
  10653. AbstractVariableType))
  10654. Var->setInvalidDecl();
  10655. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10656. Var->getStorageClass() == SC_PrivateExtern) {
  10657. Diag(Var->getLocation(), diag::warn_private_extern);
  10658. Diag(Var->getLocation(), diag::note_private_extern);
  10659. }
  10660. return;
  10661. case VarDecl::TentativeDefinition:
  10662. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  10663. // object that has file scope without an initializer, and without a
  10664. // storage-class specifier or with the storage-class specifier "static",
  10665. // constitutes a tentative definition. Note: A tentative definition with
  10666. // external linkage is valid (C99 6.2.2p5).
  10667. if (!Var->isInvalidDecl()) {
  10668. if (const IncompleteArrayType *ArrayT
  10669. = Context.getAsIncompleteArrayType(Type)) {
  10670. if (RequireCompleteType(Var->getLocation(),
  10671. ArrayT->getElementType(),
  10672. diag::err_illegal_decl_array_incomplete_type))
  10673. Var->setInvalidDecl();
  10674. } else if (Var->getStorageClass() == SC_Static) {
  10675. // C99 6.9.2p3: If the declaration of an identifier for an object is
  10676. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  10677. // declared type shall not be an incomplete type.
  10678. // NOTE: code such as the following
  10679. // static struct s;
  10680. // struct s { int a; };
  10681. // is accepted by gcc. Hence here we issue a warning instead of
  10682. // an error and we do not invalidate the static declaration.
  10683. // NOTE: to avoid multiple warnings, only check the first declaration.
  10684. if (Var->isFirstDecl())
  10685. RequireCompleteType(Var->getLocation(), Type,
  10686. diag::ext_typecheck_decl_incomplete_type);
  10687. }
  10688. }
  10689. // Record the tentative definition; we're done.
  10690. if (!Var->isInvalidDecl())
  10691. TentativeDefinitions.push_back(Var);
  10692. return;
  10693. }
  10694. // Provide a specific diagnostic for uninitialized variable
  10695. // definitions with incomplete array type.
  10696. if (Type->isIncompleteArrayType()) {
  10697. Diag(Var->getLocation(),
  10698. diag::err_typecheck_incomplete_array_needs_initializer);
  10699. Var->setInvalidDecl();
  10700. return;
  10701. }
  10702. // Provide a specific diagnostic for uninitialized variable
  10703. // definitions with reference type.
  10704. if (Type->isReferenceType()) {
  10705. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  10706. << Var->getDeclName()
  10707. << SourceRange(Var->getLocation(), Var->getLocation());
  10708. Var->setInvalidDecl();
  10709. return;
  10710. }
  10711. // Do not attempt to type-check the default initializer for a
  10712. // variable with dependent type.
  10713. if (Type->isDependentType())
  10714. return;
  10715. if (Var->isInvalidDecl())
  10716. return;
  10717. if (!Var->hasAttr<AliasAttr>()) {
  10718. if (RequireCompleteType(Var->getLocation(),
  10719. Context.getBaseElementType(Type),
  10720. diag::err_typecheck_decl_incomplete_type)) {
  10721. Var->setInvalidDecl();
  10722. return;
  10723. }
  10724. } else {
  10725. return;
  10726. }
  10727. // The variable can not have an abstract class type.
  10728. if (RequireNonAbstractType(Var->getLocation(), Type,
  10729. diag::err_abstract_type_in_decl,
  10730. AbstractVariableType)) {
  10731. Var->setInvalidDecl();
  10732. return;
  10733. }
  10734. // Check for jumps past the implicit initializer. C++0x
  10735. // clarifies that this applies to a "variable with automatic
  10736. // storage duration", not a "local variable".
  10737. // C++11 [stmt.dcl]p3
  10738. // A program that jumps from a point where a variable with automatic
  10739. // storage duration is not in scope to a point where it is in scope is
  10740. // ill-formed unless the variable has scalar type, class type with a
  10741. // trivial default constructor and a trivial destructor, a cv-qualified
  10742. // version of one of these types, or an array of one of the preceding
  10743. // types and is declared without an initializer.
  10744. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  10745. if (const RecordType *Record
  10746. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  10747. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  10748. // Mark the function (if we're in one) for further checking even if the
  10749. // looser rules of C++11 do not require such checks, so that we can
  10750. // diagnose incompatibilities with C++98.
  10751. if (!CXXRecord->isPOD())
  10752. setFunctionHasBranchProtectedScope();
  10753. }
  10754. }
  10755. // In OpenCL, we can't initialize objects in the __local address space,
  10756. // even implicitly, so don't synthesize an implicit initializer.
  10757. if (getLangOpts().OpenCL &&
  10758. Var->getType().getAddressSpace() == LangAS::opencl_local)
  10759. return;
  10760. // C++03 [dcl.init]p9:
  10761. // If no initializer is specified for an object, and the
  10762. // object is of (possibly cv-qualified) non-POD class type (or
  10763. // array thereof), the object shall be default-initialized; if
  10764. // the object is of const-qualified type, the underlying class
  10765. // type shall have a user-declared default
  10766. // constructor. Otherwise, if no initializer is specified for
  10767. // a non- static object, the object and its subobjects, if
  10768. // any, have an indeterminate initial value); if the object
  10769. // or any of its subobjects are of const-qualified type, the
  10770. // program is ill-formed.
  10771. // C++0x [dcl.init]p11:
  10772. // If no initializer is specified for an object, the object is
  10773. // default-initialized; [...].
  10774. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  10775. InitializationKind Kind
  10776. = InitializationKind::CreateDefault(Var->getLocation());
  10777. InitializationSequence InitSeq(*this, Entity, Kind, None);
  10778. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  10779. if (Init.isInvalid())
  10780. Var->setInvalidDecl();
  10781. else if (Init.get()) {
  10782. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  10783. // This is important for template substitution.
  10784. Var->setInitStyle(VarDecl::CallInit);
  10785. }
  10786. CheckCompleteVariableDeclaration(Var);
  10787. }
  10788. }
  10789. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  10790. // If there is no declaration, there was an error parsing it. Ignore it.
  10791. if (!D)
  10792. return;
  10793. VarDecl *VD = dyn_cast<VarDecl>(D);
  10794. if (!VD) {
  10795. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  10796. D->setInvalidDecl();
  10797. return;
  10798. }
  10799. VD->setCXXForRangeDecl(true);
  10800. // for-range-declaration cannot be given a storage class specifier.
  10801. int Error = -1;
  10802. switch (VD->getStorageClass()) {
  10803. case SC_None:
  10804. break;
  10805. case SC_Extern:
  10806. Error = 0;
  10807. break;
  10808. case SC_Static:
  10809. Error = 1;
  10810. break;
  10811. case SC_PrivateExtern:
  10812. Error = 2;
  10813. break;
  10814. case SC_Auto:
  10815. Error = 3;
  10816. break;
  10817. case SC_Register:
  10818. Error = 4;
  10819. break;
  10820. }
  10821. if (Error != -1) {
  10822. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  10823. << VD->getDeclName() << Error;
  10824. D->setInvalidDecl();
  10825. }
  10826. }
  10827. StmtResult
  10828. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  10829. IdentifierInfo *Ident,
  10830. ParsedAttributes &Attrs,
  10831. SourceLocation AttrEnd) {
  10832. // C++1y [stmt.iter]p1:
  10833. // A range-based for statement of the form
  10834. // for ( for-range-identifier : for-range-initializer ) statement
  10835. // is equivalent to
  10836. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  10837. DeclSpec DS(Attrs.getPool().getFactory());
  10838. const char *PrevSpec;
  10839. unsigned DiagID;
  10840. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  10841. getPrintingPolicy());
  10842. Declarator D(DS, DeclaratorContext::ForContext);
  10843. D.SetIdentifier(Ident, IdentLoc);
  10844. D.takeAttributes(Attrs, AttrEnd);
  10845. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
  10846. IdentLoc);
  10847. Decl *Var = ActOnDeclarator(S, D);
  10848. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  10849. FinalizeDeclaration(Var);
  10850. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  10851. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  10852. }
  10853. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  10854. if (var->isInvalidDecl()) return;
  10855. if (getLangOpts().OpenCL) {
  10856. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  10857. // initialiser
  10858. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  10859. !var->hasInit()) {
  10860. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  10861. << 1 /*Init*/;
  10862. var->setInvalidDecl();
  10863. return;
  10864. }
  10865. }
  10866. // In Objective-C, don't allow jumps past the implicit initialization of a
  10867. // local retaining variable.
  10868. if (getLangOpts().ObjC &&
  10869. var->hasLocalStorage()) {
  10870. switch (var->getType().getObjCLifetime()) {
  10871. case Qualifiers::OCL_None:
  10872. case Qualifiers::OCL_ExplicitNone:
  10873. case Qualifiers::OCL_Autoreleasing:
  10874. break;
  10875. case Qualifiers::OCL_Weak:
  10876. case Qualifiers::OCL_Strong:
  10877. setFunctionHasBranchProtectedScope();
  10878. break;
  10879. }
  10880. }
  10881. if (var->hasLocalStorage() &&
  10882. var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  10883. setFunctionHasBranchProtectedScope();
  10884. // Warn about externally-visible variables being defined without a
  10885. // prior declaration. We only want to do this for global
  10886. // declarations, but we also specifically need to avoid doing it for
  10887. // class members because the linkage of an anonymous class can
  10888. // change if it's later given a typedef name.
  10889. if (var->isThisDeclarationADefinition() &&
  10890. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  10891. var->isExternallyVisible() && var->hasLinkage() &&
  10892. !var->isInline() && !var->getDescribedVarTemplate() &&
  10893. !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
  10894. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  10895. var->getLocation())) {
  10896. // Find a previous declaration that's not a definition.
  10897. VarDecl *prev = var->getPreviousDecl();
  10898. while (prev && prev->isThisDeclarationADefinition())
  10899. prev = prev->getPreviousDecl();
  10900. if (!prev) {
  10901. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  10902. Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  10903. << /* variable */ 0;
  10904. }
  10905. }
  10906. // Cache the result of checking for constant initialization.
  10907. Optional<bool> CacheHasConstInit;
  10908. const Expr *CacheCulprit = nullptr;
  10909. auto checkConstInit = [&]() mutable {
  10910. if (!CacheHasConstInit)
  10911. CacheHasConstInit = var->getInit()->isConstantInitializer(
  10912. Context, var->getType()->isReferenceType(), &CacheCulprit);
  10913. return *CacheHasConstInit;
  10914. };
  10915. if (var->getTLSKind() == VarDecl::TLS_Static) {
  10916. if (var->getType().isDestructedType()) {
  10917. // GNU C++98 edits for __thread, [basic.start.term]p3:
  10918. // The type of an object with thread storage duration shall not
  10919. // have a non-trivial destructor.
  10920. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  10921. if (getLangOpts().CPlusPlus11)
  10922. Diag(var->getLocation(), diag::note_use_thread_local);
  10923. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  10924. if (!checkConstInit()) {
  10925. // GNU C++98 edits for __thread, [basic.start.init]p4:
  10926. // An object of thread storage duration shall not require dynamic
  10927. // initialization.
  10928. // FIXME: Need strict checking here.
  10929. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  10930. << CacheCulprit->getSourceRange();
  10931. if (getLangOpts().CPlusPlus11)
  10932. Diag(var->getLocation(), diag::note_use_thread_local);
  10933. }
  10934. }
  10935. }
  10936. // Apply section attributes and pragmas to global variables.
  10937. bool GlobalStorage = var->hasGlobalStorage();
  10938. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  10939. !inTemplateInstantiation()) {
  10940. PragmaStack<StringLiteral *> *Stack = nullptr;
  10941. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  10942. if (var->getType().isConstQualified())
  10943. Stack = &ConstSegStack;
  10944. else if (!var->getInit()) {
  10945. Stack = &BSSSegStack;
  10946. SectionFlags |= ASTContext::PSF_Write;
  10947. } else {
  10948. Stack = &DataSegStack;
  10949. SectionFlags |= ASTContext::PSF_Write;
  10950. }
  10951. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
  10952. var->addAttr(SectionAttr::CreateImplicit(
  10953. Context, Stack->CurrentValue->getString(),
  10954. Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
  10955. SectionAttr::Declspec_allocate));
  10956. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  10957. if (UnifySection(SA->getName(), SectionFlags, var))
  10958. var->dropAttr<SectionAttr>();
  10959. // Apply the init_seg attribute if this has an initializer. If the
  10960. // initializer turns out to not be dynamic, we'll end up ignoring this
  10961. // attribute.
  10962. if (CurInitSeg && var->getInit())
  10963. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  10964. CurInitSegLoc,
  10965. AttributeCommonInfo::AS_Pragma));
  10966. }
  10967. // All the following checks are C++ only.
  10968. if (!getLangOpts().CPlusPlus) {
  10969. // If this variable must be emitted, add it as an initializer for the
  10970. // current module.
  10971. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10972. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10973. return;
  10974. }
  10975. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  10976. CheckCompleteDecompositionDeclaration(DD);
  10977. QualType type = var->getType();
  10978. if (type->isDependentType()) return;
  10979. if (var->hasAttr<BlocksAttr>())
  10980. getCurFunction()->addByrefBlockVar(var);
  10981. Expr *Init = var->getInit();
  10982. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  10983. QualType baseType = Context.getBaseElementType(type);
  10984. if (Init && !Init->isValueDependent()) {
  10985. if (var->isConstexpr()) {
  10986. SmallVector<PartialDiagnosticAt, 8> Notes;
  10987. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  10988. SourceLocation DiagLoc = var->getLocation();
  10989. // If the note doesn't add any useful information other than a source
  10990. // location, fold it into the primary diagnostic.
  10991. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10992. diag::note_invalid_subexpr_in_const_expr) {
  10993. DiagLoc = Notes[0].first;
  10994. Notes.clear();
  10995. }
  10996. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  10997. << var << Init->getSourceRange();
  10998. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10999. Diag(Notes[I].first, Notes[I].second);
  11000. }
  11001. } else if (var->mightBeUsableInConstantExpressions(Context)) {
  11002. // Check whether the initializer of a const variable of integral or
  11003. // enumeration type is an ICE now, since we can't tell whether it was
  11004. // initialized by a constant expression if we check later.
  11005. var->checkInitIsICE();
  11006. }
  11007. // Don't emit further diagnostics about constexpr globals since they
  11008. // were just diagnosed.
  11009. if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
  11010. // FIXME: Need strict checking in C++03 here.
  11011. bool DiagErr = getLangOpts().CPlusPlus11
  11012. ? !var->checkInitIsICE() : !checkConstInit();
  11013. if (DiagErr) {
  11014. auto *Attr = var->getAttr<ConstInitAttr>();
  11015. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  11016. << Init->getSourceRange();
  11017. Diag(Attr->getLocation(),
  11018. diag::note_declared_required_constant_init_here)
  11019. << Attr->getRange() << Attr->isConstinit();
  11020. if (getLangOpts().CPlusPlus11) {
  11021. APValue Value;
  11022. SmallVector<PartialDiagnosticAt, 8> Notes;
  11023. Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
  11024. for (auto &it : Notes)
  11025. Diag(it.first, it.second);
  11026. } else {
  11027. Diag(CacheCulprit->getExprLoc(),
  11028. diag::note_invalid_subexpr_in_const_expr)
  11029. << CacheCulprit->getSourceRange();
  11030. }
  11031. }
  11032. }
  11033. else if (!var->isConstexpr() && IsGlobal &&
  11034. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  11035. var->getLocation())) {
  11036. // Warn about globals which don't have a constant initializer. Don't
  11037. // warn about globals with a non-trivial destructor because we already
  11038. // warned about them.
  11039. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  11040. if (!(RD && !RD->hasTrivialDestructor())) {
  11041. if (!checkConstInit())
  11042. Diag(var->getLocation(), diag::warn_global_constructor)
  11043. << Init->getSourceRange();
  11044. }
  11045. }
  11046. }
  11047. // Require the destructor.
  11048. if (const RecordType *recordType = baseType->getAs<RecordType>())
  11049. FinalizeVarWithDestructor(var, recordType);
  11050. // If this variable must be emitted, add it as an initializer for the current
  11051. // module.
  11052. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  11053. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  11054. }
  11055. /// Determines if a variable's alignment is dependent.
  11056. static bool hasDependentAlignment(VarDecl *VD) {
  11057. if (VD->getType()->isDependentType())
  11058. return true;
  11059. for (auto *I : VD->specific_attrs<AlignedAttr>())
  11060. if (I->isAlignmentDependent())
  11061. return true;
  11062. return false;
  11063. }
  11064. /// Check if VD needs to be dllexport/dllimport due to being in a
  11065. /// dllexport/import function.
  11066. void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
  11067. assert(VD->isStaticLocal());
  11068. auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  11069. // Find outermost function when VD is in lambda function.
  11070. while (FD && !getDLLAttr(FD) &&
  11071. !FD->hasAttr<DLLExportStaticLocalAttr>() &&
  11072. !FD->hasAttr<DLLImportStaticLocalAttr>()) {
  11073. FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
  11074. }
  11075. if (!FD)
  11076. return;
  11077. // Static locals inherit dll attributes from their function.
  11078. if (Attr *A = getDLLAttr(FD)) {
  11079. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  11080. NewAttr->setInherited(true);
  11081. VD->addAttr(NewAttr);
  11082. } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
  11083. auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
  11084. NewAttr->setInherited(true);
  11085. VD->addAttr(NewAttr);
  11086. // Export this function to enforce exporting this static variable even
  11087. // if it is not used in this compilation unit.
  11088. if (!FD->hasAttr<DLLExportAttr>())
  11089. FD->addAttr(NewAttr);
  11090. } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
  11091. auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
  11092. NewAttr->setInherited(true);
  11093. VD->addAttr(NewAttr);
  11094. }
  11095. }
  11096. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  11097. /// any semantic actions necessary after any initializer has been attached.
  11098. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  11099. // Note that we are no longer parsing the initializer for this declaration.
  11100. ParsingInitForAutoVars.erase(ThisDecl);
  11101. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  11102. if (!VD)
  11103. return;
  11104. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  11105. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  11106. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  11107. if (PragmaClangBSSSection.Valid)
  11108. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
  11109. Context, PragmaClangBSSSection.SectionName,
  11110. PragmaClangBSSSection.PragmaLocation,
  11111. AttributeCommonInfo::AS_Pragma));
  11112. if (PragmaClangDataSection.Valid)
  11113. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
  11114. Context, PragmaClangDataSection.SectionName,
  11115. PragmaClangDataSection.PragmaLocation,
  11116. AttributeCommonInfo::AS_Pragma));
  11117. if (PragmaClangRodataSection.Valid)
  11118. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
  11119. Context, PragmaClangRodataSection.SectionName,
  11120. PragmaClangRodataSection.PragmaLocation,
  11121. AttributeCommonInfo::AS_Pragma));
  11122. }
  11123. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  11124. for (auto *BD : DD->bindings()) {
  11125. FinalizeDeclaration(BD);
  11126. }
  11127. }
  11128. checkAttributesAfterMerging(*this, *VD);
  11129. // Perform TLS alignment check here after attributes attached to the variable
  11130. // which may affect the alignment have been processed. Only perform the check
  11131. // if the target has a maximum TLS alignment (zero means no constraints).
  11132. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  11133. // Protect the check so that it's not performed on dependent types and
  11134. // dependent alignments (we can't determine the alignment in that case).
  11135. if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
  11136. !VD->isInvalidDecl()) {
  11137. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  11138. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  11139. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  11140. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  11141. << (unsigned)MaxAlignChars.getQuantity();
  11142. }
  11143. }
  11144. }
  11145. if (VD->isStaticLocal()) {
  11146. CheckStaticLocalForDllExport(VD);
  11147. if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  11148. // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
  11149. // function, only __shared__ variables or variables without any device
  11150. // memory qualifiers may be declared with static storage class.
  11151. // Note: It is unclear how a function-scope non-const static variable
  11152. // without device memory qualifier is implemented, therefore only static
  11153. // const variable without device memory qualifier is allowed.
  11154. [&]() {
  11155. if (!getLangOpts().CUDA)
  11156. return;
  11157. if (VD->hasAttr<CUDASharedAttr>())
  11158. return;
  11159. if (VD->getType().isConstQualified() &&
  11160. !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  11161. return;
  11162. if (CUDADiagIfDeviceCode(VD->getLocation(),
  11163. diag::err_device_static_local_var)
  11164. << CurrentCUDATarget())
  11165. VD->setInvalidDecl();
  11166. }();
  11167. }
  11168. }
  11169. // Perform check for initializers of device-side global variables.
  11170. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  11171. // 7.5). We must also apply the same checks to all __shared__
  11172. // variables whether they are local or not. CUDA also allows
  11173. // constant initializers for __constant__ and __device__ variables.
  11174. if (getLangOpts().CUDA)
  11175. checkAllowedCUDAInitializer(VD);
  11176. // Grab the dllimport or dllexport attribute off of the VarDecl.
  11177. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  11178. // Imported static data members cannot be defined out-of-line.
  11179. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  11180. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  11181. VD->isThisDeclarationADefinition()) {
  11182. // We allow definitions of dllimport class template static data members
  11183. // with a warning.
  11184. CXXRecordDecl *Context =
  11185. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  11186. bool IsClassTemplateMember =
  11187. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  11188. Context->getDescribedClassTemplate();
  11189. Diag(VD->getLocation(),
  11190. IsClassTemplateMember
  11191. ? diag::warn_attribute_dllimport_static_field_definition
  11192. : diag::err_attribute_dllimport_static_field_definition);
  11193. Diag(IA->getLocation(), diag::note_attribute);
  11194. if (!IsClassTemplateMember)
  11195. VD->setInvalidDecl();
  11196. }
  11197. }
  11198. // dllimport/dllexport variables cannot be thread local, their TLS index
  11199. // isn't exported with the variable.
  11200. if (DLLAttr && VD->getTLSKind()) {
  11201. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  11202. if (F && getDLLAttr(F)) {
  11203. assert(VD->isStaticLocal());
  11204. // But if this is a static local in a dlimport/dllexport function, the
  11205. // function will never be inlined, which means the var would never be
  11206. // imported, so having it marked import/export is safe.
  11207. } else {
  11208. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  11209. << DLLAttr;
  11210. VD->setInvalidDecl();
  11211. }
  11212. }
  11213. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  11214. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  11215. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  11216. VD->dropAttr<UsedAttr>();
  11217. }
  11218. }
  11219. const DeclContext *DC = VD->getDeclContext();
  11220. // If there's a #pragma GCC visibility in scope, and this isn't a class
  11221. // member, set the visibility of this variable.
  11222. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  11223. AddPushedVisibilityAttribute(VD);
  11224. // FIXME: Warn on unused var template partial specializations.
  11225. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  11226. MarkUnusedFileScopedDecl(VD);
  11227. // Now we have parsed the initializer and can update the table of magic
  11228. // tag values.
  11229. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  11230. !VD->getType()->isIntegralOrEnumerationType())
  11231. return;
  11232. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  11233. const Expr *MagicValueExpr = VD->getInit();
  11234. if (!MagicValueExpr) {
  11235. continue;
  11236. }
  11237. llvm::APSInt MagicValueInt;
  11238. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  11239. Diag(I->getRange().getBegin(),
  11240. diag::err_type_tag_for_datatype_not_ice)
  11241. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  11242. continue;
  11243. }
  11244. if (MagicValueInt.getActiveBits() > 64) {
  11245. Diag(I->getRange().getBegin(),
  11246. diag::err_type_tag_for_datatype_too_large)
  11247. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  11248. continue;
  11249. }
  11250. uint64_t MagicValue = MagicValueInt.getZExtValue();
  11251. RegisterTypeTagForDatatype(I->getArgumentKind(),
  11252. MagicValue,
  11253. I->getMatchingCType(),
  11254. I->getLayoutCompatible(),
  11255. I->getMustBeNull());
  11256. }
  11257. }
  11258. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  11259. auto *VD = dyn_cast<VarDecl>(DD);
  11260. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  11261. }
  11262. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  11263. ArrayRef<Decl *> Group) {
  11264. SmallVector<Decl*, 8> Decls;
  11265. if (DS.isTypeSpecOwned())
  11266. Decls.push_back(DS.getRepAsDecl());
  11267. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  11268. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  11269. bool DiagnosedMultipleDecomps = false;
  11270. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  11271. bool DiagnosedNonDeducedAuto = false;
  11272. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  11273. if (Decl *D = Group[i]) {
  11274. // For declarators, there are some additional syntactic-ish checks we need
  11275. // to perform.
  11276. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  11277. if (!FirstDeclaratorInGroup)
  11278. FirstDeclaratorInGroup = DD;
  11279. if (!FirstDecompDeclaratorInGroup)
  11280. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  11281. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  11282. !hasDeducedAuto(DD))
  11283. FirstNonDeducedAutoInGroup = DD;
  11284. if (FirstDeclaratorInGroup != DD) {
  11285. // A decomposition declaration cannot be combined with any other
  11286. // declaration in the same group.
  11287. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  11288. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  11289. diag::err_decomp_decl_not_alone)
  11290. << FirstDeclaratorInGroup->getSourceRange()
  11291. << DD->getSourceRange();
  11292. DiagnosedMultipleDecomps = true;
  11293. }
  11294. // A declarator that uses 'auto' in any way other than to declare a
  11295. // variable with a deduced type cannot be combined with any other
  11296. // declarator in the same group.
  11297. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  11298. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  11299. diag::err_auto_non_deduced_not_alone)
  11300. << FirstNonDeducedAutoInGroup->getType()
  11301. ->hasAutoForTrailingReturnType()
  11302. << FirstDeclaratorInGroup->getSourceRange()
  11303. << DD->getSourceRange();
  11304. DiagnosedNonDeducedAuto = true;
  11305. }
  11306. }
  11307. }
  11308. Decls.push_back(D);
  11309. }
  11310. }
  11311. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  11312. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  11313. handleTagNumbering(Tag, S);
  11314. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  11315. getLangOpts().CPlusPlus)
  11316. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  11317. }
  11318. }
  11319. return BuildDeclaratorGroup(Decls);
  11320. }
  11321. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  11322. /// group, performing any necessary semantic checking.
  11323. Sema::DeclGroupPtrTy
  11324. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  11325. // C++14 [dcl.spec.auto]p7: (DR1347)
  11326. // If the type that replaces the placeholder type is not the same in each
  11327. // deduction, the program is ill-formed.
  11328. if (Group.size() > 1) {
  11329. QualType Deduced;
  11330. VarDecl *DeducedDecl = nullptr;
  11331. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  11332. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  11333. if (!D || D->isInvalidDecl())
  11334. break;
  11335. DeducedType *DT = D->getType()->getContainedDeducedType();
  11336. if (!DT || DT->getDeducedType().isNull())
  11337. continue;
  11338. if (Deduced.isNull()) {
  11339. Deduced = DT->getDeducedType();
  11340. DeducedDecl = D;
  11341. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  11342. auto *AT = dyn_cast<AutoType>(DT);
  11343. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  11344. diag::err_auto_different_deductions)
  11345. << (AT ? (unsigned)AT->getKeyword() : 3)
  11346. << Deduced << DeducedDecl->getDeclName()
  11347. << DT->getDeducedType() << D->getDeclName()
  11348. << DeducedDecl->getInit()->getSourceRange()
  11349. << D->getInit()->getSourceRange();
  11350. D->setInvalidDecl();
  11351. break;
  11352. }
  11353. }
  11354. }
  11355. ActOnDocumentableDecls(Group);
  11356. return DeclGroupPtrTy::make(
  11357. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  11358. }
  11359. void Sema::ActOnDocumentableDecl(Decl *D) {
  11360. ActOnDocumentableDecls(D);
  11361. }
  11362. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  11363. // Don't parse the comment if Doxygen diagnostics are ignored.
  11364. if (Group.empty() || !Group[0])
  11365. return;
  11366. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  11367. Group[0]->getLocation()) &&
  11368. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  11369. Group[0]->getLocation()))
  11370. return;
  11371. if (Group.size() >= 2) {
  11372. // This is a decl group. Normally it will contain only declarations
  11373. // produced from declarator list. But in case we have any definitions or
  11374. // additional declaration references:
  11375. // 'typedef struct S {} S;'
  11376. // 'typedef struct S *S;'
  11377. // 'struct S *pS;'
  11378. // FinalizeDeclaratorGroup adds these as separate declarations.
  11379. Decl *MaybeTagDecl = Group[0];
  11380. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  11381. Group = Group.slice(1);
  11382. }
  11383. }
  11384. // FIMXE: We assume every Decl in the group is in the same file.
  11385. // This is false when preprocessor constructs the group from decls in
  11386. // different files (e. g. macros or #include).
  11387. Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
  11388. }
  11389. /// Common checks for a parameter-declaration that should apply to both function
  11390. /// parameters and non-type template parameters.
  11391. void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
  11392. // Check that there are no default arguments inside the type of this
  11393. // parameter.
  11394. if (getLangOpts().CPlusPlus)
  11395. CheckExtraCXXDefaultArguments(D);
  11396. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  11397. if (D.getCXXScopeSpec().isSet()) {
  11398. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  11399. << D.getCXXScopeSpec().getRange();
  11400. }
  11401. // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
  11402. // simple identifier except [...irrelevant cases...].
  11403. switch (D.getName().getKind()) {
  11404. case UnqualifiedIdKind::IK_Identifier:
  11405. break;
  11406. case UnqualifiedIdKind::IK_OperatorFunctionId:
  11407. case UnqualifiedIdKind::IK_ConversionFunctionId:
  11408. case UnqualifiedIdKind::IK_LiteralOperatorId:
  11409. case UnqualifiedIdKind::IK_ConstructorName:
  11410. case UnqualifiedIdKind::IK_DestructorName:
  11411. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  11412. case UnqualifiedIdKind::IK_DeductionGuideName:
  11413. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  11414. << GetNameForDeclarator(D).getName();
  11415. break;
  11416. case UnqualifiedIdKind::IK_TemplateId:
  11417. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  11418. // GetNameForDeclarator would not produce a useful name in this case.
  11419. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
  11420. break;
  11421. }
  11422. }
  11423. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  11424. /// to introduce parameters into function prototype scope.
  11425. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  11426. const DeclSpec &DS = D.getDeclSpec();
  11427. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  11428. // C++03 [dcl.stc]p2 also permits 'auto'.
  11429. StorageClass SC = SC_None;
  11430. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  11431. SC = SC_Register;
  11432. // In C++11, the 'register' storage class specifier is deprecated.
  11433. // In C++17, it is not allowed, but we tolerate it as an extension.
  11434. if (getLangOpts().CPlusPlus11) {
  11435. Diag(DS.getStorageClassSpecLoc(),
  11436. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  11437. : diag::warn_deprecated_register)
  11438. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  11439. }
  11440. } else if (getLangOpts().CPlusPlus &&
  11441. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  11442. SC = SC_Auto;
  11443. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  11444. Diag(DS.getStorageClassSpecLoc(),
  11445. diag::err_invalid_storage_class_in_func_decl);
  11446. D.getMutableDeclSpec().ClearStorageClassSpecs();
  11447. }
  11448. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  11449. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  11450. << DeclSpec::getSpecifierName(TSCS);
  11451. if (DS.isInlineSpecified())
  11452. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  11453. << getLangOpts().CPlusPlus17;
  11454. if (DS.hasConstexprSpecifier())
  11455. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  11456. << 0 << D.getDeclSpec().getConstexprSpecifier();
  11457. DiagnoseFunctionSpecifiers(DS);
  11458. CheckFunctionOrTemplateParamDeclarator(S, D);
  11459. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11460. QualType parmDeclType = TInfo->getType();
  11461. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  11462. IdentifierInfo *II = D.getIdentifier();
  11463. if (II) {
  11464. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  11465. ForVisibleRedeclaration);
  11466. LookupName(R, S);
  11467. if (R.isSingleResult()) {
  11468. NamedDecl *PrevDecl = R.getFoundDecl();
  11469. if (PrevDecl->isTemplateParameter()) {
  11470. // Maybe we will complain about the shadowed template parameter.
  11471. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11472. // Just pretend that we didn't see the previous declaration.
  11473. PrevDecl = nullptr;
  11474. } else if (S->isDeclScope(PrevDecl)) {
  11475. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  11476. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  11477. // Recover by removing the name
  11478. II = nullptr;
  11479. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  11480. D.setInvalidType(true);
  11481. }
  11482. }
  11483. }
  11484. // Temporarily put parameter variables in the translation unit, not
  11485. // the enclosing context. This prevents them from accidentally
  11486. // looking like class members in C++.
  11487. ParmVarDecl *New =
  11488. CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
  11489. D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
  11490. if (D.isInvalidType())
  11491. New->setInvalidDecl();
  11492. assert(S->isFunctionPrototypeScope());
  11493. assert(S->getFunctionPrototypeDepth() >= 1);
  11494. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  11495. S->getNextFunctionPrototypeIndex());
  11496. // Add the parameter declaration into this scope.
  11497. S->AddDecl(New);
  11498. if (II)
  11499. IdResolver.AddDecl(New);
  11500. ProcessDeclAttributes(S, New, D);
  11501. if (D.getDeclSpec().isModulePrivateSpecified())
  11502. Diag(New->getLocation(), diag::err_module_private_local)
  11503. << 1 << New->getDeclName()
  11504. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  11505. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  11506. if (New->hasAttr<BlocksAttr>()) {
  11507. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  11508. }
  11509. return New;
  11510. }
  11511. /// Synthesizes a variable for a parameter arising from a
  11512. /// typedef.
  11513. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  11514. SourceLocation Loc,
  11515. QualType T) {
  11516. /* FIXME: setting StartLoc == Loc.
  11517. Would it be worth to modify callers so as to provide proper source
  11518. location for the unnamed parameters, embedding the parameter's type? */
  11519. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  11520. T, Context.getTrivialTypeSourceInfo(T, Loc),
  11521. SC_None, nullptr);
  11522. Param->setImplicit();
  11523. return Param;
  11524. }
  11525. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  11526. // Don't diagnose unused-parameter errors in template instantiations; we
  11527. // will already have done so in the template itself.
  11528. if (inTemplateInstantiation())
  11529. return;
  11530. for (const ParmVarDecl *Parameter : Parameters) {
  11531. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  11532. !Parameter->hasAttr<UnusedAttr>()) {
  11533. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  11534. << Parameter->getDeclName();
  11535. }
  11536. }
  11537. }
  11538. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  11539. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  11540. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  11541. return;
  11542. // Warn if the return value is pass-by-value and larger than the specified
  11543. // threshold.
  11544. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  11545. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  11546. if (Size > LangOpts.NumLargeByValueCopy)
  11547. Diag(D->getLocation(), diag::warn_return_value_size)
  11548. << D->getDeclName() << Size;
  11549. }
  11550. // Warn if any parameter is pass-by-value and larger than the specified
  11551. // threshold.
  11552. for (const ParmVarDecl *Parameter : Parameters) {
  11553. QualType T = Parameter->getType();
  11554. if (T->isDependentType() || !T.isPODType(Context))
  11555. continue;
  11556. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  11557. if (Size > LangOpts.NumLargeByValueCopy)
  11558. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  11559. << Parameter->getDeclName() << Size;
  11560. }
  11561. }
  11562. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  11563. SourceLocation NameLoc, IdentifierInfo *Name,
  11564. QualType T, TypeSourceInfo *TSInfo,
  11565. StorageClass SC) {
  11566. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  11567. if (getLangOpts().ObjCAutoRefCount &&
  11568. T.getObjCLifetime() == Qualifiers::OCL_None &&
  11569. T->isObjCLifetimeType()) {
  11570. Qualifiers::ObjCLifetime lifetime;
  11571. // Special cases for arrays:
  11572. // - if it's const, use __unsafe_unretained
  11573. // - otherwise, it's an error
  11574. if (T->isArrayType()) {
  11575. if (!T.isConstQualified()) {
  11576. if (DelayedDiagnostics.shouldDelayDiagnostics())
  11577. DelayedDiagnostics.add(
  11578. sema::DelayedDiagnostic::makeForbiddenType(
  11579. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  11580. else
  11581. Diag(NameLoc, diag::err_arc_array_param_no_ownership)
  11582. << TSInfo->getTypeLoc().getSourceRange();
  11583. }
  11584. lifetime = Qualifiers::OCL_ExplicitNone;
  11585. } else {
  11586. lifetime = T->getObjCARCImplicitLifetime();
  11587. }
  11588. T = Context.getLifetimeQualifiedType(T, lifetime);
  11589. }
  11590. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  11591. Context.getAdjustedParameterType(T),
  11592. TSInfo, SC, nullptr);
  11593. // Make a note if we created a new pack in the scope of a lambda, so that
  11594. // we know that references to that pack must also be expanded within the
  11595. // lambda scope.
  11596. if (New->isParameterPack())
  11597. if (auto *LSI = getEnclosingLambda())
  11598. LSI->LocalPacks.push_back(New);
  11599. if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
  11600. New->getType().hasNonTrivialToPrimitiveCopyCUnion())
  11601. checkNonTrivialCUnion(New->getType(), New->getLocation(),
  11602. NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
  11603. // Parameters can not be abstract class types.
  11604. // For record types, this is done by the AbstractClassUsageDiagnoser once
  11605. // the class has been completely parsed.
  11606. if (!CurContext->isRecord() &&
  11607. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  11608. AbstractParamType))
  11609. New->setInvalidDecl();
  11610. // Parameter declarators cannot be interface types. All ObjC objects are
  11611. // passed by reference.
  11612. if (T->isObjCObjectType()) {
  11613. SourceLocation TypeEndLoc =
  11614. getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
  11615. Diag(NameLoc,
  11616. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  11617. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  11618. T = Context.getObjCObjectPointerType(T);
  11619. New->setType(T);
  11620. }
  11621. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  11622. // duration shall not be qualified by an address-space qualifier."
  11623. // Since all parameters have automatic store duration, they can not have
  11624. // an address space.
  11625. if (T.getAddressSpace() != LangAS::Default &&
  11626. // OpenCL allows function arguments declared to be an array of a type
  11627. // to be qualified with an address space.
  11628. !(getLangOpts().OpenCL &&
  11629. (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
  11630. Diag(NameLoc, diag::err_arg_with_address_space);
  11631. New->setInvalidDecl();
  11632. }
  11633. return New;
  11634. }
  11635. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  11636. SourceLocation LocAfterDecls) {
  11637. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  11638. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  11639. // for a K&R function.
  11640. if (!FTI.hasPrototype) {
  11641. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  11642. --i;
  11643. if (FTI.Params[i].Param == nullptr) {
  11644. SmallString<256> Code;
  11645. llvm::raw_svector_ostream(Code)
  11646. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  11647. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  11648. << FTI.Params[i].Ident
  11649. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  11650. // Implicitly declare the argument as type 'int' for lack of a better
  11651. // type.
  11652. AttributeFactory attrs;
  11653. DeclSpec DS(attrs);
  11654. const char* PrevSpec; // unused
  11655. unsigned DiagID; // unused
  11656. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  11657. DiagID, Context.getPrintingPolicy());
  11658. // Use the identifier location for the type source range.
  11659. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  11660. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  11661. Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
  11662. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  11663. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  11664. }
  11665. }
  11666. }
  11667. }
  11668. Decl *
  11669. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  11670. MultiTemplateParamsArg TemplateParameterLists,
  11671. SkipBodyInfo *SkipBody) {
  11672. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  11673. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  11674. Scope *ParentScope = FnBodyScope->getParent();
  11675. D.setFunctionDefinitionKind(FDK_Definition);
  11676. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  11677. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  11678. }
  11679. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  11680. Consumer.HandleInlineFunctionDefinition(D);
  11681. }
  11682. static bool
  11683. ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  11684. const FunctionDecl *&PossiblePrototype) {
  11685. // Don't warn about invalid declarations.
  11686. if (FD->isInvalidDecl())
  11687. return false;
  11688. // Or declarations that aren't global.
  11689. if (!FD->isGlobal())
  11690. return false;
  11691. // Don't warn about C++ member functions.
  11692. if (isa<CXXMethodDecl>(FD))
  11693. return false;
  11694. // Don't warn about 'main'.
  11695. if (FD->isMain())
  11696. return false;
  11697. // Don't warn about inline functions.
  11698. if (FD->isInlined())
  11699. return false;
  11700. // Don't warn about function templates.
  11701. if (FD->getDescribedFunctionTemplate())
  11702. return false;
  11703. // Don't warn about function template specializations.
  11704. if (FD->isFunctionTemplateSpecialization())
  11705. return false;
  11706. // Don't warn for OpenCL kernels.
  11707. if (FD->hasAttr<OpenCLKernelAttr>())
  11708. return false;
  11709. // Don't warn on explicitly deleted functions.
  11710. if (FD->isDeleted())
  11711. return false;
  11712. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  11713. Prev; Prev = Prev->getPreviousDecl()) {
  11714. // Ignore any declarations that occur in function or method
  11715. // scope, because they aren't visible from the header.
  11716. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  11717. continue;
  11718. PossiblePrototype = Prev;
  11719. return Prev->getType()->isFunctionNoProtoType();
  11720. }
  11721. return true;
  11722. }
  11723. void
  11724. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  11725. const FunctionDecl *EffectiveDefinition,
  11726. SkipBodyInfo *SkipBody) {
  11727. const FunctionDecl *Definition = EffectiveDefinition;
  11728. if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
  11729. // If this is a friend function defined in a class template, it does not
  11730. // have a body until it is used, nevertheless it is a definition, see
  11731. // [temp.inst]p2:
  11732. //
  11733. // ... for the purpose of determining whether an instantiated redeclaration
  11734. // is valid according to [basic.def.odr] and [class.mem], a declaration that
  11735. // corresponds to a definition in the template is considered to be a
  11736. // definition.
  11737. //
  11738. // The following code must produce redefinition error:
  11739. //
  11740. // template<typename T> struct C20 { friend void func_20() {} };
  11741. // C20<int> c20i;
  11742. // void func_20() {}
  11743. //
  11744. for (auto I : FD->redecls()) {
  11745. if (I != FD && !I->isInvalidDecl() &&
  11746. I->getFriendObjectKind() != Decl::FOK_None) {
  11747. if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
  11748. if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
  11749. // A merged copy of the same function, instantiated as a member of
  11750. // the same class, is OK.
  11751. if (declaresSameEntity(OrigFD, Original) &&
  11752. declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
  11753. cast<Decl>(FD->getLexicalDeclContext())))
  11754. continue;
  11755. }
  11756. if (Original->isThisDeclarationADefinition()) {
  11757. Definition = I;
  11758. break;
  11759. }
  11760. }
  11761. }
  11762. }
  11763. }
  11764. if (!Definition)
  11765. // Similar to friend functions a friend function template may be a
  11766. // definition and do not have a body if it is instantiated in a class
  11767. // template.
  11768. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
  11769. for (auto I : FTD->redecls()) {
  11770. auto D = cast<FunctionTemplateDecl>(I);
  11771. if (D != FTD) {
  11772. assert(!D->isThisDeclarationADefinition() &&
  11773. "More than one definition in redeclaration chain");
  11774. if (D->getFriendObjectKind() != Decl::FOK_None)
  11775. if (FunctionTemplateDecl *FT =
  11776. D->getInstantiatedFromMemberTemplate()) {
  11777. if (FT->isThisDeclarationADefinition()) {
  11778. Definition = D->getTemplatedDecl();
  11779. break;
  11780. }
  11781. }
  11782. }
  11783. }
  11784. }
  11785. if (!Definition)
  11786. return;
  11787. if (canRedefineFunction(Definition, getLangOpts()))
  11788. return;
  11789. // Don't emit an error when this is redefinition of a typo-corrected
  11790. // definition.
  11791. if (TypoCorrectedFunctionDefinitions.count(Definition))
  11792. return;
  11793. // If we don't have a visible definition of the function, and it's inline or
  11794. // a template, skip the new definition.
  11795. if (SkipBody && !hasVisibleDefinition(Definition) &&
  11796. (Definition->getFormalLinkage() == InternalLinkage ||
  11797. Definition->isInlined() ||
  11798. Definition->getDescribedFunctionTemplate() ||
  11799. Definition->getNumTemplateParameterLists())) {
  11800. SkipBody->ShouldSkip = true;
  11801. SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
  11802. if (auto *TD = Definition->getDescribedFunctionTemplate())
  11803. makeMergedDefinitionVisible(TD);
  11804. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  11805. return;
  11806. }
  11807. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  11808. Definition->getStorageClass() == SC_Extern)
  11809. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  11810. << FD->getDeclName() << getLangOpts().CPlusPlus;
  11811. else
  11812. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  11813. Diag(Definition->getLocation(), diag::note_previous_definition);
  11814. FD->setInvalidDecl();
  11815. }
  11816. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  11817. Sema &S) {
  11818. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  11819. LambdaScopeInfo *LSI = S.PushLambdaScope();
  11820. LSI->CallOperator = CallOperator;
  11821. LSI->Lambda = LambdaClass;
  11822. LSI->ReturnType = CallOperator->getReturnType();
  11823. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  11824. if (LCD == LCD_None)
  11825. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  11826. else if (LCD == LCD_ByCopy)
  11827. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  11828. else if (LCD == LCD_ByRef)
  11829. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  11830. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  11831. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  11832. LSI->Mutable = !CallOperator->isConst();
  11833. // Add the captures to the LSI so they can be noted as already
  11834. // captured within tryCaptureVar.
  11835. auto I = LambdaClass->field_begin();
  11836. for (const auto &C : LambdaClass->captures()) {
  11837. if (C.capturesVariable()) {
  11838. VarDecl *VD = C.getCapturedVar();
  11839. if (VD->isInitCapture())
  11840. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  11841. QualType CaptureType = VD->getType();
  11842. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  11843. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  11844. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  11845. /*EllipsisLoc*/C.isPackExpansion()
  11846. ? C.getEllipsisLoc() : SourceLocation(),
  11847. CaptureType, /*Invalid*/false);
  11848. } else if (C.capturesThis()) {
  11849. LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
  11850. C.getCaptureKind() == LCK_StarThis);
  11851. } else {
  11852. LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
  11853. I->getType());
  11854. }
  11855. ++I;
  11856. }
  11857. }
  11858. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  11859. SkipBodyInfo *SkipBody) {
  11860. if (!D) {
  11861. // Parsing the function declaration failed in some way. Push on a fake scope
  11862. // anyway so we can try to parse the function body.
  11863. PushFunctionScope();
  11864. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11865. return D;
  11866. }
  11867. FunctionDecl *FD = nullptr;
  11868. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  11869. FD = FunTmpl->getTemplatedDecl();
  11870. else
  11871. FD = cast<FunctionDecl>(D);
  11872. // Do not push if it is a lambda because one is already pushed when building
  11873. // the lambda in ActOnStartOfLambdaDefinition().
  11874. if (!isLambdaCallOperator(FD))
  11875. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11876. // Check for defining attributes before the check for redefinition.
  11877. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  11878. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  11879. FD->dropAttr<AliasAttr>();
  11880. FD->setInvalidDecl();
  11881. }
  11882. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  11883. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  11884. FD->dropAttr<IFuncAttr>();
  11885. FD->setInvalidDecl();
  11886. }
  11887. // See if this is a redefinition. If 'will have body' is already set, then
  11888. // these checks were already performed when it was set.
  11889. if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
  11890. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  11891. // If we're skipping the body, we're done. Don't enter the scope.
  11892. if (SkipBody && SkipBody->ShouldSkip)
  11893. return D;
  11894. }
  11895. // Mark this function as "will have a body eventually". This lets users to
  11896. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  11897. // this function.
  11898. FD->setWillHaveBody();
  11899. // If we are instantiating a generic lambda call operator, push
  11900. // a LambdaScopeInfo onto the function stack. But use the information
  11901. // that's already been calculated (ActOnLambdaExpr) to prime the current
  11902. // LambdaScopeInfo.
  11903. // When the template operator is being specialized, the LambdaScopeInfo,
  11904. // has to be properly restored so that tryCaptureVariable doesn't try
  11905. // and capture any new variables. In addition when calculating potential
  11906. // captures during transformation of nested lambdas, it is necessary to
  11907. // have the LSI properly restored.
  11908. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  11909. assert(inTemplateInstantiation() &&
  11910. "There should be an active template instantiation on the stack "
  11911. "when instantiating a generic lambda!");
  11912. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  11913. } else {
  11914. // Enter a new function scope
  11915. PushFunctionScope();
  11916. }
  11917. // Builtin functions cannot be defined.
  11918. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11919. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  11920. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  11921. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  11922. FD->setInvalidDecl();
  11923. }
  11924. }
  11925. // The return type of a function definition must be complete
  11926. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  11927. QualType ResultType = FD->getReturnType();
  11928. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  11929. !FD->isInvalidDecl() &&
  11930. RequireCompleteType(FD->getLocation(), ResultType,
  11931. diag::err_func_def_incomplete_result))
  11932. FD->setInvalidDecl();
  11933. if (FnBodyScope)
  11934. PushDeclContext(FnBodyScope, FD);
  11935. // Check the validity of our function parameters
  11936. CheckParmsForFunctionDef(FD->parameters(),
  11937. /*CheckParameterNames=*/true);
  11938. // Add non-parameter declarations already in the function to the current
  11939. // scope.
  11940. if (FnBodyScope) {
  11941. for (Decl *NPD : FD->decls()) {
  11942. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  11943. if (!NonParmDecl)
  11944. continue;
  11945. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  11946. "parameters should not be in newly created FD yet");
  11947. // If the decl has a name, make it accessible in the current scope.
  11948. if (NonParmDecl->getDeclName())
  11949. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  11950. // Similarly, dive into enums and fish their constants out, making them
  11951. // accessible in this scope.
  11952. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  11953. for (auto *EI : ED->enumerators())
  11954. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  11955. }
  11956. }
  11957. }
  11958. // Introduce our parameters into the function scope
  11959. for (auto Param : FD->parameters()) {
  11960. Param->setOwningFunction(FD);
  11961. // If this has an identifier, add it to the scope stack.
  11962. if (Param->getIdentifier() && FnBodyScope) {
  11963. CheckShadow(FnBodyScope, Param);
  11964. PushOnScopeChains(Param, FnBodyScope);
  11965. }
  11966. }
  11967. // Ensure that the function's exception specification is instantiated.
  11968. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  11969. ResolveExceptionSpec(D->getLocation(), FPT);
  11970. // dllimport cannot be applied to non-inline function definitions.
  11971. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  11972. !FD->isTemplateInstantiation()) {
  11973. assert(!FD->hasAttr<DLLExportAttr>());
  11974. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  11975. FD->setInvalidDecl();
  11976. return D;
  11977. }
  11978. // We want to attach documentation to original Decl (which might be
  11979. // a function template).
  11980. ActOnDocumentableDecl(D);
  11981. if (getCurLexicalContext()->isObjCContainer() &&
  11982. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  11983. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  11984. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  11985. return D;
  11986. }
  11987. /// Given the set of return statements within a function body,
  11988. /// compute the variables that are subject to the named return value
  11989. /// optimization.
  11990. ///
  11991. /// Each of the variables that is subject to the named return value
  11992. /// optimization will be marked as NRVO variables in the AST, and any
  11993. /// return statement that has a marked NRVO variable as its NRVO candidate can
  11994. /// use the named return value optimization.
  11995. ///
  11996. /// This function applies a very simplistic algorithm for NRVO: if every return
  11997. /// statement in the scope of a variable has the same NRVO candidate, that
  11998. /// candidate is an NRVO variable.
  11999. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  12000. ReturnStmt **Returns = Scope->Returns.data();
  12001. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  12002. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  12003. if (!NRVOCandidate->isNRVOVariable())
  12004. Returns[I]->setNRVOCandidate(nullptr);
  12005. }
  12006. }
  12007. }
  12008. bool Sema::canDelayFunctionBody(const Declarator &D) {
  12009. // We can't delay parsing the body of a constexpr function template (yet).
  12010. if (D.getDeclSpec().hasConstexprSpecifier())
  12011. return false;
  12012. // We can't delay parsing the body of a function template with a deduced
  12013. // return type (yet).
  12014. if (D.getDeclSpec().hasAutoTypeSpec()) {
  12015. // If the placeholder introduces a non-deduced trailing return type,
  12016. // we can still delay parsing it.
  12017. if (D.getNumTypeObjects()) {
  12018. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  12019. if (Outer.Kind == DeclaratorChunk::Function &&
  12020. Outer.Fun.hasTrailingReturnType()) {
  12021. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  12022. return Ty.isNull() || !Ty->isUndeducedType();
  12023. }
  12024. }
  12025. return false;
  12026. }
  12027. return true;
  12028. }
  12029. bool Sema::canSkipFunctionBody(Decl *D) {
  12030. // We cannot skip the body of a function (or function template) which is
  12031. // constexpr, since we may need to evaluate its body in order to parse the
  12032. // rest of the file.
  12033. // We cannot skip the body of a function with an undeduced return type,
  12034. // because any callers of that function need to know the type.
  12035. if (const FunctionDecl *FD = D->getAsFunction()) {
  12036. if (FD->isConstexpr())
  12037. return false;
  12038. // We can't simply call Type::isUndeducedType here, because inside template
  12039. // auto can be deduced to a dependent type, which is not considered
  12040. // "undeduced".
  12041. if (FD->getReturnType()->getContainedDeducedType())
  12042. return false;
  12043. }
  12044. return Consumer.shouldSkipFunctionBody(D);
  12045. }
  12046. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  12047. if (!Decl)
  12048. return nullptr;
  12049. if (FunctionDecl *FD = Decl->getAsFunction())
  12050. FD->setHasSkippedBody();
  12051. else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
  12052. MD->setHasSkippedBody();
  12053. return Decl;
  12054. }
  12055. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  12056. return ActOnFinishFunctionBody(D, BodyArg, false);
  12057. }
  12058. /// RAII object that pops an ExpressionEvaluationContext when exiting a function
  12059. /// body.
  12060. class ExitFunctionBodyRAII {
  12061. public:
  12062. ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
  12063. ~ExitFunctionBodyRAII() {
  12064. if (!IsLambda)
  12065. S.PopExpressionEvaluationContext();
  12066. }
  12067. private:
  12068. Sema &S;
  12069. bool IsLambda = false;
  12070. };
  12071. static void diagnoseImplicitlyRetainedSelf(Sema &S) {
  12072. llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
  12073. auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
  12074. if (EscapeInfo.count(BD))
  12075. return EscapeInfo[BD];
  12076. bool R = false;
  12077. const BlockDecl *CurBD = BD;
  12078. do {
  12079. R = !CurBD->doesNotEscape();
  12080. if (R)
  12081. break;
  12082. CurBD = CurBD->getParent()->getInnermostBlockDecl();
  12083. } while (CurBD);
  12084. return EscapeInfo[BD] = R;
  12085. };
  12086. // If the location where 'self' is implicitly retained is inside a escaping
  12087. // block, emit a diagnostic.
  12088. for (const std::pair<SourceLocation, const BlockDecl *> &P :
  12089. S.ImplicitlyRetainedSelfLocs)
  12090. if (IsOrNestedInEscapingBlock(P.second))
  12091. S.Diag(P.first, diag::warn_implicitly_retains_self)
  12092. << FixItHint::CreateInsertion(P.first, "self->");
  12093. }
  12094. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  12095. bool IsInstantiation) {
  12096. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  12097. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  12098. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  12099. if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
  12100. CheckCompletedCoroutineBody(FD, Body);
  12101. // Do not call PopExpressionEvaluationContext() if it is a lambda because one
  12102. // is already popped when finishing the lambda in BuildLambdaExpr(). This is
  12103. // meant to pop the context added in ActOnStartOfFunctionDef().
  12104. ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
  12105. if (FD) {
  12106. FD->setBody(Body);
  12107. FD->setWillHaveBody(false);
  12108. if (getLangOpts().CPlusPlus14) {
  12109. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  12110. FD->getReturnType()->isUndeducedType()) {
  12111. // If the function has a deduced result type but contains no 'return'
  12112. // statements, the result type as written must be exactly 'auto', and
  12113. // the deduced result type is 'void'.
  12114. if (!FD->getReturnType()->getAs<AutoType>()) {
  12115. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  12116. << FD->getReturnType();
  12117. FD->setInvalidDecl();
  12118. } else {
  12119. // Substitute 'void' for the 'auto' in the type.
  12120. TypeLoc ResultType = getReturnTypeLoc(FD);
  12121. Context.adjustDeducedFunctionResultType(
  12122. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  12123. }
  12124. }
  12125. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  12126. // In C++11, we don't use 'auto' deduction rules for lambda call
  12127. // operators because we don't support return type deduction.
  12128. auto *LSI = getCurLambda();
  12129. if (LSI->HasImplicitReturnType) {
  12130. deduceClosureReturnType(*LSI);
  12131. // C++11 [expr.prim.lambda]p4:
  12132. // [...] if there are no return statements in the compound-statement
  12133. // [the deduced type is] the type void
  12134. QualType RetType =
  12135. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  12136. // Update the return type to the deduced type.
  12137. const FunctionProtoType *Proto =
  12138. FD->getType()->getAs<FunctionProtoType>();
  12139. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  12140. Proto->getExtProtoInfo()));
  12141. }
  12142. }
  12143. // If the function implicitly returns zero (like 'main') or is naked,
  12144. // don't complain about missing return statements.
  12145. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  12146. WP.disableCheckFallThrough();
  12147. // MSVC permits the use of pure specifier (=0) on function definition,
  12148. // defined at class scope, warn about this non-standard construct.
  12149. if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
  12150. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  12151. if (!FD->isInvalidDecl()) {
  12152. // Don't diagnose unused parameters of defaulted or deleted functions.
  12153. if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
  12154. DiagnoseUnusedParameters(FD->parameters());
  12155. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  12156. FD->getReturnType(), FD);
  12157. // If this is a structor, we need a vtable.
  12158. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  12159. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  12160. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  12161. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  12162. // Try to apply the named return value optimization. We have to check
  12163. // if we can do this here because lambdas keep return statements around
  12164. // to deduce an implicit return type.
  12165. if (FD->getReturnType()->isRecordType() &&
  12166. (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
  12167. computeNRVO(Body, getCurFunction());
  12168. }
  12169. // GNU warning -Wmissing-prototypes:
  12170. // Warn if a global function is defined without a previous
  12171. // prototype declaration. This warning is issued even if the
  12172. // definition itself provides a prototype. The aim is to detect
  12173. // global functions that fail to be declared in header files.
  12174. const FunctionDecl *PossiblePrototype = nullptr;
  12175. if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
  12176. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  12177. if (PossiblePrototype) {
  12178. // We found a declaration that is not a prototype,
  12179. // but that could be a zero-parameter prototype
  12180. if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
  12181. TypeLoc TL = TI->getTypeLoc();
  12182. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  12183. Diag(PossiblePrototype->getLocation(),
  12184. diag::note_declaration_not_a_prototype)
  12185. << (FD->getNumParams() != 0)
  12186. << (FD->getNumParams() == 0
  12187. ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
  12188. : FixItHint{});
  12189. }
  12190. } else {
  12191. Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  12192. << /* function */ 1
  12193. << (FD->getStorageClass() == SC_None
  12194. ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
  12195. "static ")
  12196. : FixItHint{});
  12197. }
  12198. // GNU warning -Wstrict-prototypes
  12199. // Warn if K&R function is defined without a previous declaration.
  12200. // This warning is issued only if the definition itself does not provide
  12201. // a prototype. Only K&R definitions do not provide a prototype.
  12202. // An empty list in a function declarator that is part of a definition
  12203. // of that function specifies that the function has no parameters
  12204. // (C99 6.7.5.3p14)
  12205. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  12206. !LangOpts.CPlusPlus) {
  12207. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  12208. TypeLoc TL = TI->getTypeLoc();
  12209. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  12210. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
  12211. }
  12212. }
  12213. // Warn on CPUDispatch with an actual body.
  12214. if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
  12215. if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
  12216. if (!CmpndBody->body_empty())
  12217. Diag(CmpndBody->body_front()->getBeginLoc(),
  12218. diag::warn_dispatch_body_ignored);
  12219. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  12220. const CXXMethodDecl *KeyFunction;
  12221. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  12222. MD->isVirtual() &&
  12223. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  12224. MD == KeyFunction->getCanonicalDecl()) {
  12225. // Update the key-function state if necessary for this ABI.
  12226. if (FD->isInlined() &&
  12227. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  12228. Context.setNonKeyFunction(MD);
  12229. // If the newly-chosen key function is already defined, then we
  12230. // need to mark the vtable as used retroactively.
  12231. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  12232. const FunctionDecl *Definition;
  12233. if (KeyFunction && KeyFunction->isDefined(Definition))
  12234. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  12235. } else {
  12236. // We just defined they key function; mark the vtable as used.
  12237. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  12238. }
  12239. }
  12240. }
  12241. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  12242. "Function parsing confused");
  12243. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  12244. assert(MD == getCurMethodDecl() && "Method parsing confused");
  12245. MD->setBody(Body);
  12246. if (!MD->isInvalidDecl()) {
  12247. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  12248. MD->getReturnType(), MD);
  12249. if (Body)
  12250. computeNRVO(Body, getCurFunction());
  12251. }
  12252. if (getCurFunction()->ObjCShouldCallSuper) {
  12253. Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
  12254. << MD->getSelector().getAsString();
  12255. getCurFunction()->ObjCShouldCallSuper = false;
  12256. }
  12257. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  12258. const ObjCMethodDecl *InitMethod = nullptr;
  12259. bool isDesignated =
  12260. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  12261. assert(isDesignated && InitMethod);
  12262. (void)isDesignated;
  12263. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  12264. auto IFace = MD->getClassInterface();
  12265. if (!IFace)
  12266. return false;
  12267. auto SuperD = IFace->getSuperClass();
  12268. if (!SuperD)
  12269. return false;
  12270. return SuperD->getIdentifier() ==
  12271. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  12272. };
  12273. // Don't issue this warning for unavailable inits or direct subclasses
  12274. // of NSObject.
  12275. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  12276. Diag(MD->getLocation(),
  12277. diag::warn_objc_designated_init_missing_super_call);
  12278. Diag(InitMethod->getLocation(),
  12279. diag::note_objc_designated_init_marked_here);
  12280. }
  12281. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  12282. }
  12283. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  12284. // Don't issue this warning for unavaialable inits.
  12285. if (!MD->isUnavailable())
  12286. Diag(MD->getLocation(),
  12287. diag::warn_objc_secondary_init_missing_init_call);
  12288. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  12289. }
  12290. diagnoseImplicitlyRetainedSelf(*this);
  12291. } else {
  12292. // Parsing the function declaration failed in some way. Pop the fake scope
  12293. // we pushed on.
  12294. PopFunctionScopeInfo(ActivePolicy, dcl);
  12295. return nullptr;
  12296. }
  12297. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  12298. DiagnoseUnguardedAvailabilityViolations(dcl);
  12299. assert(!getCurFunction()->ObjCShouldCallSuper &&
  12300. "This should only be set for ObjC methods, which should have been "
  12301. "handled in the block above.");
  12302. // Verify and clean out per-function state.
  12303. if (Body && (!FD || !FD->isDefaulted())) {
  12304. // C++ constructors that have function-try-blocks can't have return
  12305. // statements in the handlers of that block. (C++ [except.handle]p14)
  12306. // Verify this.
  12307. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  12308. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  12309. // Verify that gotos and switch cases don't jump into scopes illegally.
  12310. if (getCurFunction()->NeedsScopeChecking() &&
  12311. !PP.isCodeCompletionEnabled())
  12312. DiagnoseInvalidJumps(Body);
  12313. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  12314. if (!Destructor->getParent()->isDependentType())
  12315. CheckDestructor(Destructor);
  12316. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  12317. Destructor->getParent());
  12318. }
  12319. // If any errors have occurred, clear out any temporaries that may have
  12320. // been leftover. This ensures that these temporaries won't be picked up for
  12321. // deletion in some later function.
  12322. if (getDiagnostics().hasErrorOccurred() ||
  12323. getDiagnostics().getSuppressAllDiagnostics()) {
  12324. DiscardCleanupsInEvaluationContext();
  12325. }
  12326. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  12327. !isa<FunctionTemplateDecl>(dcl)) {
  12328. // Since the body is valid, issue any analysis-based warnings that are
  12329. // enabled.
  12330. ActivePolicy = &WP;
  12331. }
  12332. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  12333. !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
  12334. FD->setInvalidDecl();
  12335. if (FD && FD->hasAttr<NakedAttr>()) {
  12336. for (const Stmt *S : Body->children()) {
  12337. // Allow local register variables without initializer as they don't
  12338. // require prologue.
  12339. bool RegisterVariables = false;
  12340. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  12341. for (const auto *Decl : DS->decls()) {
  12342. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  12343. RegisterVariables =
  12344. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  12345. if (!RegisterVariables)
  12346. break;
  12347. }
  12348. }
  12349. }
  12350. if (RegisterVariables)
  12351. continue;
  12352. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  12353. Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
  12354. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  12355. FD->setInvalidDecl();
  12356. break;
  12357. }
  12358. }
  12359. }
  12360. assert(ExprCleanupObjects.size() ==
  12361. ExprEvalContexts.back().NumCleanupObjects &&
  12362. "Leftover temporaries in function");
  12363. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  12364. assert(MaybeODRUseExprs.empty() &&
  12365. "Leftover expressions for odr-use checking");
  12366. }
  12367. if (!IsInstantiation)
  12368. PopDeclContext();
  12369. PopFunctionScopeInfo(ActivePolicy, dcl);
  12370. // If any errors have occurred, clear out any temporaries that may have
  12371. // been leftover. This ensures that these temporaries won't be picked up for
  12372. // deletion in some later function.
  12373. if (getDiagnostics().hasErrorOccurred()) {
  12374. DiscardCleanupsInEvaluationContext();
  12375. }
  12376. return dcl;
  12377. }
  12378. /// When we finish delayed parsing of an attribute, we must attach it to the
  12379. /// relevant Decl.
  12380. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  12381. ParsedAttributes &Attrs) {
  12382. // Always attach attributes to the underlying decl.
  12383. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  12384. D = TD->getTemplatedDecl();
  12385. ProcessDeclAttributeList(S, D, Attrs);
  12386. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  12387. if (Method->isStatic())
  12388. checkThisInStaticMemberFunctionAttributes(Method);
  12389. }
  12390. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  12391. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  12392. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  12393. IdentifierInfo &II, Scope *S) {
  12394. // Find the scope in which the identifier is injected and the corresponding
  12395. // DeclContext.
  12396. // FIXME: C89 does not say what happens if there is no enclosing block scope.
  12397. // In that case, we inject the declaration into the translation unit scope
  12398. // instead.
  12399. Scope *BlockScope = S;
  12400. while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
  12401. BlockScope = BlockScope->getParent();
  12402. Scope *ContextScope = BlockScope;
  12403. while (!ContextScope->getEntity())
  12404. ContextScope = ContextScope->getParent();
  12405. ContextRAII SavedContext(*this, ContextScope->getEntity());
  12406. // Before we produce a declaration for an implicitly defined
  12407. // function, see whether there was a locally-scoped declaration of
  12408. // this name as a function or variable. If so, use that
  12409. // (non-visible) declaration, and complain about it.
  12410. NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
  12411. if (ExternCPrev) {
  12412. // We still need to inject the function into the enclosing block scope so
  12413. // that later (non-call) uses can see it.
  12414. PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
  12415. // C89 footnote 38:
  12416. // If in fact it is not defined as having type "function returning int",
  12417. // the behavior is undefined.
  12418. if (!isa<FunctionDecl>(ExternCPrev) ||
  12419. !Context.typesAreCompatible(
  12420. cast<FunctionDecl>(ExternCPrev)->getType(),
  12421. Context.getFunctionNoProtoType(Context.IntTy))) {
  12422. Diag(Loc, diag::ext_use_out_of_scope_declaration)
  12423. << ExternCPrev << !getLangOpts().C99;
  12424. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  12425. return ExternCPrev;
  12426. }
  12427. }
  12428. // Extension in C99. Legal in C90, but warn about it.
  12429. unsigned diag_id;
  12430. if (II.getName().startswith("__builtin_"))
  12431. diag_id = diag::warn_builtin_unknown;
  12432. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  12433. else if (getLangOpts().OpenCL)
  12434. diag_id = diag::err_opencl_implicit_function_decl;
  12435. else if (getLangOpts().C99)
  12436. diag_id = diag::ext_implicit_function_decl;
  12437. else
  12438. diag_id = diag::warn_implicit_function_decl;
  12439. Diag(Loc, diag_id) << &II;
  12440. // If we found a prior declaration of this function, don't bother building
  12441. // another one. We've already pushed that one into scope, so there's nothing
  12442. // more to do.
  12443. if (ExternCPrev)
  12444. return ExternCPrev;
  12445. // Because typo correction is expensive, only do it if the implicit
  12446. // function declaration is going to be treated as an error.
  12447. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  12448. TypoCorrection Corrected;
  12449. DeclFilterCCC<FunctionDecl> CCC{};
  12450. if (S && (Corrected =
  12451. CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
  12452. S, nullptr, CCC, CTK_NonError)))
  12453. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  12454. /*ErrorRecovery*/false);
  12455. }
  12456. // Set a Declarator for the implicit definition: int foo();
  12457. const char *Dummy;
  12458. AttributeFactory attrFactory;
  12459. DeclSpec DS(attrFactory);
  12460. unsigned DiagID;
  12461. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  12462. Context.getPrintingPolicy());
  12463. (void)Error; // Silence warning.
  12464. assert(!Error && "Error setting up implicit decl!");
  12465. SourceLocation NoLoc;
  12466. Declarator D(DS, DeclaratorContext::BlockContext);
  12467. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  12468. /*IsAmbiguous=*/false,
  12469. /*LParenLoc=*/NoLoc,
  12470. /*Params=*/nullptr,
  12471. /*NumParams=*/0,
  12472. /*EllipsisLoc=*/NoLoc,
  12473. /*RParenLoc=*/NoLoc,
  12474. /*RefQualifierIsLvalueRef=*/true,
  12475. /*RefQualifierLoc=*/NoLoc,
  12476. /*MutableLoc=*/NoLoc, EST_None,
  12477. /*ESpecRange=*/SourceRange(),
  12478. /*Exceptions=*/nullptr,
  12479. /*ExceptionRanges=*/nullptr,
  12480. /*NumExceptions=*/0,
  12481. /*NoexceptExpr=*/nullptr,
  12482. /*ExceptionSpecTokens=*/nullptr,
  12483. /*DeclsInPrototype=*/None, Loc,
  12484. Loc, D),
  12485. std::move(DS.getAttributes()), SourceLocation());
  12486. D.SetIdentifier(&II, Loc);
  12487. // Insert this function into the enclosing block scope.
  12488. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
  12489. FD->setImplicit();
  12490. AddKnownFunctionAttributes(FD);
  12491. return FD;
  12492. }
  12493. /// Adds any function attributes that we know a priori based on
  12494. /// the declaration of this function.
  12495. ///
  12496. /// These attributes can apply both to implicitly-declared builtins
  12497. /// (like __builtin___printf_chk) or to library-declared functions
  12498. /// like NSLog or printf.
  12499. ///
  12500. /// We need to check for duplicate attributes both here and where user-written
  12501. /// attributes are applied to declarations.
  12502. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  12503. if (FD->isInvalidDecl())
  12504. return;
  12505. // If this is a built-in function, map its builtin attributes to
  12506. // actual attributes.
  12507. if (unsigned BuiltinID = FD->getBuiltinID()) {
  12508. // Handle printf-formatting attributes.
  12509. unsigned FormatIdx;
  12510. bool HasVAListArg;
  12511. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  12512. if (!FD->hasAttr<FormatAttr>()) {
  12513. const char *fmt = "printf";
  12514. unsigned int NumParams = FD->getNumParams();
  12515. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  12516. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  12517. fmt = "NSString";
  12518. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12519. &Context.Idents.get(fmt),
  12520. FormatIdx+1,
  12521. HasVAListArg ? 0 : FormatIdx+2,
  12522. FD->getLocation()));
  12523. }
  12524. }
  12525. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  12526. HasVAListArg)) {
  12527. if (!FD->hasAttr<FormatAttr>())
  12528. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12529. &Context.Idents.get("scanf"),
  12530. FormatIdx+1,
  12531. HasVAListArg ? 0 : FormatIdx+2,
  12532. FD->getLocation()));
  12533. }
  12534. // Handle automatically recognized callbacks.
  12535. SmallVector<int, 4> Encoding;
  12536. if (!FD->hasAttr<CallbackAttr>() &&
  12537. Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
  12538. FD->addAttr(CallbackAttr::CreateImplicit(
  12539. Context, Encoding.data(), Encoding.size(), FD->getLocation()));
  12540. // Mark const if we don't care about errno and that is the only thing
  12541. // preventing the function from being const. This allows IRgen to use LLVM
  12542. // intrinsics for such functions.
  12543. if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
  12544. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
  12545. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12546. // We make "fma" on some platforms const because we know it does not set
  12547. // errno in those environments even though it could set errno based on the
  12548. // C standard.
  12549. const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
  12550. if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
  12551. !FD->hasAttr<ConstAttr>()) {
  12552. switch (BuiltinID) {
  12553. case Builtin::BI__builtin_fma:
  12554. case Builtin::BI__builtin_fmaf:
  12555. case Builtin::BI__builtin_fmal:
  12556. case Builtin::BIfma:
  12557. case Builtin::BIfmaf:
  12558. case Builtin::BIfmal:
  12559. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12560. break;
  12561. default:
  12562. break;
  12563. }
  12564. }
  12565. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  12566. !FD->hasAttr<ReturnsTwiceAttr>())
  12567. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  12568. FD->getLocation()));
  12569. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  12570. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12571. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  12572. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  12573. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  12574. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12575. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  12576. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  12577. // Add the appropriate attribute, depending on the CUDA compilation mode
  12578. // and which target the builtin belongs to. For example, during host
  12579. // compilation, aux builtins are __device__, while the rest are __host__.
  12580. if (getLangOpts().CUDAIsDevice !=
  12581. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  12582. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  12583. else
  12584. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  12585. }
  12586. }
  12587. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  12588. // throw, add an implicit nothrow attribute to any extern "C" function we come
  12589. // across.
  12590. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  12591. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  12592. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  12593. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  12594. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12595. }
  12596. IdentifierInfo *Name = FD->getIdentifier();
  12597. if (!Name)
  12598. return;
  12599. if ((!getLangOpts().CPlusPlus &&
  12600. FD->getDeclContext()->isTranslationUnit()) ||
  12601. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  12602. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  12603. LinkageSpecDecl::lang_c)) {
  12604. // Okay: this could be a libc/libm/Objective-C function we know
  12605. // about.
  12606. } else
  12607. return;
  12608. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  12609. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  12610. // target-specific builtins, perhaps?
  12611. if (!FD->hasAttr<FormatAttr>())
  12612. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12613. &Context.Idents.get("printf"), 2,
  12614. Name->isStr("vasprintf") ? 0 : 3,
  12615. FD->getLocation()));
  12616. }
  12617. if (Name->isStr("__CFStringMakeConstantString")) {
  12618. // We already have a __builtin___CFStringMakeConstantString,
  12619. // but builds that use -fno-constant-cfstrings don't go through that.
  12620. if (!FD->hasAttr<FormatArgAttr>())
  12621. FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
  12622. FD->getLocation()));
  12623. }
  12624. }
  12625. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  12626. TypeSourceInfo *TInfo) {
  12627. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  12628. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  12629. if (!TInfo) {
  12630. assert(D.isInvalidType() && "no declarator info for valid type");
  12631. TInfo = Context.getTrivialTypeSourceInfo(T);
  12632. }
  12633. // Scope manipulation handled by caller.
  12634. TypedefDecl *NewTD =
  12635. TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
  12636. D.getIdentifierLoc(), D.getIdentifier(), TInfo);
  12637. // Bail out immediately if we have an invalid declaration.
  12638. if (D.isInvalidType()) {
  12639. NewTD->setInvalidDecl();
  12640. return NewTD;
  12641. }
  12642. if (D.getDeclSpec().isModulePrivateSpecified()) {
  12643. if (CurContext->isFunctionOrMethod())
  12644. Diag(NewTD->getLocation(), diag::err_module_private_local)
  12645. << 2 << NewTD->getDeclName()
  12646. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  12647. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  12648. else
  12649. NewTD->setModulePrivate();
  12650. }
  12651. // C++ [dcl.typedef]p8:
  12652. // If the typedef declaration defines an unnamed class (or
  12653. // enum), the first typedef-name declared by the declaration
  12654. // to be that class type (or enum type) is used to denote the
  12655. // class type (or enum type) for linkage purposes only.
  12656. // We need to check whether the type was declared in the declaration.
  12657. switch (D.getDeclSpec().getTypeSpecType()) {
  12658. case TST_enum:
  12659. case TST_struct:
  12660. case TST_interface:
  12661. case TST_union:
  12662. case TST_class: {
  12663. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  12664. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  12665. break;
  12666. }
  12667. default:
  12668. break;
  12669. }
  12670. return NewTD;
  12671. }
  12672. /// Check that this is a valid underlying type for an enum declaration.
  12673. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  12674. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  12675. QualType T = TI->getType();
  12676. if (T->isDependentType())
  12677. return false;
  12678. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  12679. if (BT->isInteger())
  12680. return false;
  12681. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  12682. return true;
  12683. }
  12684. /// Check whether this is a valid redeclaration of a previous enumeration.
  12685. /// \return true if the redeclaration was invalid.
  12686. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  12687. QualType EnumUnderlyingTy, bool IsFixed,
  12688. const EnumDecl *Prev) {
  12689. if (IsScoped != Prev->isScoped()) {
  12690. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  12691. << Prev->isScoped();
  12692. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12693. return true;
  12694. }
  12695. if (IsFixed && Prev->isFixed()) {
  12696. if (!EnumUnderlyingTy->isDependentType() &&
  12697. !Prev->getIntegerType()->isDependentType() &&
  12698. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  12699. Prev->getIntegerType())) {
  12700. // TODO: Highlight the underlying type of the redeclaration.
  12701. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  12702. << EnumUnderlyingTy << Prev->getIntegerType();
  12703. Diag(Prev->getLocation(), diag::note_previous_declaration)
  12704. << Prev->getIntegerTypeRange();
  12705. return true;
  12706. }
  12707. } else if (IsFixed != Prev->isFixed()) {
  12708. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  12709. << Prev->isFixed();
  12710. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12711. return true;
  12712. }
  12713. return false;
  12714. }
  12715. /// Get diagnostic %select index for tag kind for
  12716. /// redeclaration diagnostic message.
  12717. /// WARNING: Indexes apply to particular diagnostics only!
  12718. ///
  12719. /// \returns diagnostic %select index.
  12720. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  12721. switch (Tag) {
  12722. case TTK_Struct: return 0;
  12723. case TTK_Interface: return 1;
  12724. case TTK_Class: return 2;
  12725. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  12726. }
  12727. }
  12728. /// Determine if tag kind is a class-key compatible with
  12729. /// class for redeclaration (class, struct, or __interface).
  12730. ///
  12731. /// \returns true iff the tag kind is compatible.
  12732. static bool isClassCompatTagKind(TagTypeKind Tag)
  12733. {
  12734. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  12735. }
  12736. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  12737. TagTypeKind TTK) {
  12738. if (isa<TypedefDecl>(PrevDecl))
  12739. return NTK_Typedef;
  12740. else if (isa<TypeAliasDecl>(PrevDecl))
  12741. return NTK_TypeAlias;
  12742. else if (isa<ClassTemplateDecl>(PrevDecl))
  12743. return NTK_Template;
  12744. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  12745. return NTK_TypeAliasTemplate;
  12746. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  12747. return NTK_TemplateTemplateArgument;
  12748. switch (TTK) {
  12749. case TTK_Struct:
  12750. case TTK_Interface:
  12751. case TTK_Class:
  12752. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  12753. case TTK_Union:
  12754. return NTK_NonUnion;
  12755. case TTK_Enum:
  12756. return NTK_NonEnum;
  12757. }
  12758. llvm_unreachable("invalid TTK");
  12759. }
  12760. /// Determine whether a tag with a given kind is acceptable
  12761. /// as a redeclaration of the given tag declaration.
  12762. ///
  12763. /// \returns true if the new tag kind is acceptable, false otherwise.
  12764. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  12765. TagTypeKind NewTag, bool isDefinition,
  12766. SourceLocation NewTagLoc,
  12767. const IdentifierInfo *Name) {
  12768. // C++ [dcl.type.elab]p3:
  12769. // The class-key or enum keyword present in the
  12770. // elaborated-type-specifier shall agree in kind with the
  12771. // declaration to which the name in the elaborated-type-specifier
  12772. // refers. This rule also applies to the form of
  12773. // elaborated-type-specifier that declares a class-name or
  12774. // friend class since it can be construed as referring to the
  12775. // definition of the class. Thus, in any
  12776. // elaborated-type-specifier, the enum keyword shall be used to
  12777. // refer to an enumeration (7.2), the union class-key shall be
  12778. // used to refer to a union (clause 9), and either the class or
  12779. // struct class-key shall be used to refer to a class (clause 9)
  12780. // declared using the class or struct class-key.
  12781. TagTypeKind OldTag = Previous->getTagKind();
  12782. if (OldTag != NewTag &&
  12783. !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
  12784. return false;
  12785. // Tags are compatible, but we might still want to warn on mismatched tags.
  12786. // Non-class tags can't be mismatched at this point.
  12787. if (!isClassCompatTagKind(NewTag))
  12788. return true;
  12789. // Declarations for which -Wmismatched-tags is disabled are entirely ignored
  12790. // by our warning analysis. We don't want to warn about mismatches with (eg)
  12791. // declarations in system headers that are designed to be specialized, but if
  12792. // a user asks us to warn, we should warn if their code contains mismatched
  12793. // declarations.
  12794. auto IsIgnoredLoc = [&](SourceLocation Loc) {
  12795. return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
  12796. Loc);
  12797. };
  12798. if (IsIgnoredLoc(NewTagLoc))
  12799. return true;
  12800. auto IsIgnored = [&](const TagDecl *Tag) {
  12801. return IsIgnoredLoc(Tag->getLocation());
  12802. };
  12803. while (IsIgnored(Previous)) {
  12804. Previous = Previous->getPreviousDecl();
  12805. if (!Previous)
  12806. return true;
  12807. OldTag = Previous->getTagKind();
  12808. }
  12809. bool isTemplate = false;
  12810. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  12811. isTemplate = Record->getDescribedClassTemplate();
  12812. if (inTemplateInstantiation()) {
  12813. if (OldTag != NewTag) {
  12814. // In a template instantiation, do not offer fix-its for tag mismatches
  12815. // since they usually mess up the template instead of fixing the problem.
  12816. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12817. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12818. << getRedeclDiagFromTagKind(OldTag);
  12819. // FIXME: Note previous location?
  12820. }
  12821. return true;
  12822. }
  12823. if (isDefinition) {
  12824. // On definitions, check all previous tags and issue a fix-it for each
  12825. // one that doesn't match the current tag.
  12826. if (Previous->getDefinition()) {
  12827. // Don't suggest fix-its for redefinitions.
  12828. return true;
  12829. }
  12830. bool previousMismatch = false;
  12831. for (const TagDecl *I : Previous->redecls()) {
  12832. if (I->getTagKind() != NewTag) {
  12833. // Ignore previous declarations for which the warning was disabled.
  12834. if (IsIgnored(I))
  12835. continue;
  12836. if (!previousMismatch) {
  12837. previousMismatch = true;
  12838. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  12839. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12840. << getRedeclDiagFromTagKind(I->getTagKind());
  12841. }
  12842. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  12843. << getRedeclDiagFromTagKind(NewTag)
  12844. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  12845. TypeWithKeyword::getTagTypeKindName(NewTag));
  12846. }
  12847. }
  12848. return true;
  12849. }
  12850. // Identify the prevailing tag kind: this is the kind of the definition (if
  12851. // there is a non-ignored definition), or otherwise the kind of the prior
  12852. // (non-ignored) declaration.
  12853. const TagDecl *PrevDef = Previous->getDefinition();
  12854. if (PrevDef && IsIgnored(PrevDef))
  12855. PrevDef = nullptr;
  12856. const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
  12857. if (Redecl->getTagKind() != NewTag) {
  12858. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12859. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12860. << getRedeclDiagFromTagKind(OldTag);
  12861. Diag(Redecl->getLocation(), diag::note_previous_use);
  12862. // If there is a previous definition, suggest a fix-it.
  12863. if (PrevDef) {
  12864. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  12865. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  12866. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  12867. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  12868. }
  12869. }
  12870. return true;
  12871. }
  12872. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  12873. /// from an outer enclosing namespace or file scope inside a friend declaration.
  12874. /// This should provide the commented out code in the following snippet:
  12875. /// namespace N {
  12876. /// struct X;
  12877. /// namespace M {
  12878. /// struct Y { friend struct /*N::*/ X; };
  12879. /// }
  12880. /// }
  12881. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  12882. SourceLocation NameLoc) {
  12883. // While the decl is in a namespace, do repeated lookup of that name and see
  12884. // if we get the same namespace back. If we do not, continue until
  12885. // translation unit scope, at which point we have a fully qualified NNS.
  12886. SmallVector<IdentifierInfo *, 4> Namespaces;
  12887. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  12888. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  12889. // This tag should be declared in a namespace, which can only be enclosed by
  12890. // other namespaces. Bail if there's an anonymous namespace in the chain.
  12891. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  12892. if (!Namespace || Namespace->isAnonymousNamespace())
  12893. return FixItHint();
  12894. IdentifierInfo *II = Namespace->getIdentifier();
  12895. Namespaces.push_back(II);
  12896. NamedDecl *Lookup = SemaRef.LookupSingleName(
  12897. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  12898. if (Lookup == Namespace)
  12899. break;
  12900. }
  12901. // Once we have all the namespaces, reverse them to go outermost first, and
  12902. // build an NNS.
  12903. SmallString<64> Insertion;
  12904. llvm::raw_svector_ostream OS(Insertion);
  12905. if (DC->isTranslationUnit())
  12906. OS << "::";
  12907. std::reverse(Namespaces.begin(), Namespaces.end());
  12908. for (auto *II : Namespaces)
  12909. OS << II->getName() << "::";
  12910. return FixItHint::CreateInsertion(NameLoc, Insertion);
  12911. }
  12912. /// Determine whether a tag originally declared in context \p OldDC can
  12913. /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
  12914. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  12915. /// using-declaration).
  12916. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  12917. DeclContext *NewDC) {
  12918. OldDC = OldDC->getRedeclContext();
  12919. NewDC = NewDC->getRedeclContext();
  12920. if (OldDC->Equals(NewDC))
  12921. return true;
  12922. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  12923. // encloses the other).
  12924. if (S.getLangOpts().MSVCCompat &&
  12925. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  12926. return true;
  12927. return false;
  12928. }
  12929. /// This is invoked when we see 'struct foo' or 'struct {'. In the
  12930. /// former case, Name will be non-null. In the later case, Name will be null.
  12931. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  12932. /// reference/declaration/definition of a tag.
  12933. ///
  12934. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  12935. /// trailing-type-specifier) other than one in an alias-declaration.
  12936. ///
  12937. /// \param SkipBody If non-null, will be set to indicate if the caller should
  12938. /// skip the definition of this tag and treat it as if it were a declaration.
  12939. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  12940. SourceLocation KWLoc, CXXScopeSpec &SS,
  12941. IdentifierInfo *Name, SourceLocation NameLoc,
  12942. const ParsedAttributesView &Attrs, AccessSpecifier AS,
  12943. SourceLocation ModulePrivateLoc,
  12944. MultiTemplateParamsArg TemplateParameterLists,
  12945. bool &OwnedDecl, bool &IsDependent,
  12946. SourceLocation ScopedEnumKWLoc,
  12947. bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
  12948. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  12949. SkipBodyInfo *SkipBody) {
  12950. // If this is not a definition, it must have a name.
  12951. IdentifierInfo *OrigName = Name;
  12952. assert((Name != nullptr || TUK == TUK_Definition) &&
  12953. "Nameless record must be a definition!");
  12954. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  12955. OwnedDecl = false;
  12956. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12957. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  12958. // FIXME: Check member specializations more carefully.
  12959. bool isMemberSpecialization = false;
  12960. bool Invalid = false;
  12961. // We only need to do this matching if we have template parameters
  12962. // or a scope specifier, which also conveniently avoids this work
  12963. // for non-C++ cases.
  12964. if (TemplateParameterLists.size() > 0 ||
  12965. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  12966. if (TemplateParameterList *TemplateParams =
  12967. MatchTemplateParametersToScopeSpecifier(
  12968. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  12969. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  12970. if (Kind == TTK_Enum) {
  12971. Diag(KWLoc, diag::err_enum_template);
  12972. return nullptr;
  12973. }
  12974. if (TemplateParams->size() > 0) {
  12975. // This is a declaration or definition of a class template (which may
  12976. // be a member of another template).
  12977. if (Invalid)
  12978. return nullptr;
  12979. OwnedDecl = false;
  12980. DeclResult Result = CheckClassTemplate(
  12981. S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
  12982. AS, ModulePrivateLoc,
  12983. /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
  12984. TemplateParameterLists.data(), SkipBody);
  12985. return Result.get();
  12986. } else {
  12987. // The "template<>" header is extraneous.
  12988. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12989. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12990. isMemberSpecialization = true;
  12991. }
  12992. }
  12993. }
  12994. // Figure out the underlying type if this a enum declaration. We need to do
  12995. // this early, because it's needed to detect if this is an incompatible
  12996. // redeclaration.
  12997. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  12998. bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
  12999. if (Kind == TTK_Enum) {
  13000. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
  13001. // No underlying type explicitly specified, or we failed to parse the
  13002. // type, default to int.
  13003. EnumUnderlying = Context.IntTy.getTypePtr();
  13004. } else if (UnderlyingType.get()) {
  13005. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  13006. // integral type; any cv-qualification is ignored.
  13007. TypeSourceInfo *TI = nullptr;
  13008. GetTypeFromParser(UnderlyingType.get(), &TI);
  13009. EnumUnderlying = TI;
  13010. if (CheckEnumUnderlyingType(TI))
  13011. // Recover by falling back to int.
  13012. EnumUnderlying = Context.IntTy.getTypePtr();
  13013. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  13014. UPPC_FixedUnderlyingType))
  13015. EnumUnderlying = Context.IntTy.getTypePtr();
  13016. } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
  13017. // For MSVC ABI compatibility, unfixed enums must use an underlying type
  13018. // of 'int'. However, if this is an unfixed forward declaration, don't set
  13019. // the underlying type unless the user enables -fms-compatibility. This
  13020. // makes unfixed forward declared enums incomplete and is more conforming.
  13021. if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
  13022. EnumUnderlying = Context.IntTy.getTypePtr();
  13023. }
  13024. }
  13025. DeclContext *SearchDC = CurContext;
  13026. DeclContext *DC = CurContext;
  13027. bool isStdBadAlloc = false;
  13028. bool isStdAlignValT = false;
  13029. RedeclarationKind Redecl = forRedeclarationInCurContext();
  13030. if (TUK == TUK_Friend || TUK == TUK_Reference)
  13031. Redecl = NotForRedeclaration;
  13032. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  13033. /// implemented asks for structural equivalence checking, the returned decl
  13034. /// here is passed back to the parser, allowing the tag body to be parsed.
  13035. auto createTagFromNewDecl = [&]() -> TagDecl * {
  13036. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  13037. // If there is an identifier, use the location of the identifier as the
  13038. // location of the decl, otherwise use the location of the struct/union
  13039. // keyword.
  13040. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  13041. TagDecl *New = nullptr;
  13042. if (Kind == TTK_Enum) {
  13043. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  13044. ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
  13045. // If this is an undefined enum, bail.
  13046. if (TUK != TUK_Definition && !Invalid)
  13047. return nullptr;
  13048. if (EnumUnderlying) {
  13049. EnumDecl *ED = cast<EnumDecl>(New);
  13050. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  13051. ED->setIntegerTypeSourceInfo(TI);
  13052. else
  13053. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  13054. ED->setPromotionType(ED->getIntegerType());
  13055. }
  13056. } else { // struct/union
  13057. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13058. nullptr);
  13059. }
  13060. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  13061. // Add alignment attributes if necessary; these attributes are checked
  13062. // when the ASTContext lays out the structure.
  13063. //
  13064. // It is important for implementing the correct semantics that this
  13065. // happen here (in ActOnTag). The #pragma pack stack is
  13066. // maintained as a result of parser callbacks which can occur at
  13067. // many points during the parsing of a struct declaration (because
  13068. // the #pragma tokens are effectively skipped over during the
  13069. // parsing of the struct).
  13070. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  13071. AddAlignmentAttributesForRecord(RD);
  13072. AddMsStructLayoutForRecord(RD);
  13073. }
  13074. }
  13075. New->setLexicalDeclContext(CurContext);
  13076. return New;
  13077. };
  13078. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  13079. if (Name && SS.isNotEmpty()) {
  13080. // We have a nested-name tag ('struct foo::bar').
  13081. // Check for invalid 'foo::'.
  13082. if (SS.isInvalid()) {
  13083. Name = nullptr;
  13084. goto CreateNewDecl;
  13085. }
  13086. // If this is a friend or a reference to a class in a dependent
  13087. // context, don't try to make a decl for it.
  13088. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  13089. DC = computeDeclContext(SS, false);
  13090. if (!DC) {
  13091. IsDependent = true;
  13092. return nullptr;
  13093. }
  13094. } else {
  13095. DC = computeDeclContext(SS, true);
  13096. if (!DC) {
  13097. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  13098. << SS.getRange();
  13099. return nullptr;
  13100. }
  13101. }
  13102. if (RequireCompleteDeclContext(SS, DC))
  13103. return nullptr;
  13104. SearchDC = DC;
  13105. // Look-up name inside 'foo::'.
  13106. LookupQualifiedName(Previous, DC);
  13107. if (Previous.isAmbiguous())
  13108. return nullptr;
  13109. if (Previous.empty()) {
  13110. // Name lookup did not find anything. However, if the
  13111. // nested-name-specifier refers to the current instantiation,
  13112. // and that current instantiation has any dependent base
  13113. // classes, we might find something at instantiation time: treat
  13114. // this as a dependent elaborated-type-specifier.
  13115. // But this only makes any sense for reference-like lookups.
  13116. if (Previous.wasNotFoundInCurrentInstantiation() &&
  13117. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  13118. IsDependent = true;
  13119. return nullptr;
  13120. }
  13121. // A tag 'foo::bar' must already exist.
  13122. Diag(NameLoc, diag::err_not_tag_in_scope)
  13123. << Kind << Name << DC << SS.getRange();
  13124. Name = nullptr;
  13125. Invalid = true;
  13126. goto CreateNewDecl;
  13127. }
  13128. } else if (Name) {
  13129. // C++14 [class.mem]p14:
  13130. // If T is the name of a class, then each of the following shall have a
  13131. // name different from T:
  13132. // -- every member of class T that is itself a type
  13133. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  13134. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  13135. return nullptr;
  13136. // If this is a named struct, check to see if there was a previous forward
  13137. // declaration or definition.
  13138. // FIXME: We're looking into outer scopes here, even when we
  13139. // shouldn't be. Doing so can result in ambiguities that we
  13140. // shouldn't be diagnosing.
  13141. LookupName(Previous, S);
  13142. // When declaring or defining a tag, ignore ambiguities introduced
  13143. // by types using'ed into this scope.
  13144. if (Previous.isAmbiguous() &&
  13145. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  13146. LookupResult::Filter F = Previous.makeFilter();
  13147. while (F.hasNext()) {
  13148. NamedDecl *ND = F.next();
  13149. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  13150. SearchDC->getRedeclContext()))
  13151. F.erase();
  13152. }
  13153. F.done();
  13154. }
  13155. // C++11 [namespace.memdef]p3:
  13156. // If the name in a friend declaration is neither qualified nor
  13157. // a template-id and the declaration is a function or an
  13158. // elaborated-type-specifier, the lookup to determine whether
  13159. // the entity has been previously declared shall not consider
  13160. // any scopes outside the innermost enclosing namespace.
  13161. //
  13162. // MSVC doesn't implement the above rule for types, so a friend tag
  13163. // declaration may be a redeclaration of a type declared in an enclosing
  13164. // scope. They do implement this rule for friend functions.
  13165. //
  13166. // Does it matter that this should be by scope instead of by
  13167. // semantic context?
  13168. if (!Previous.empty() && TUK == TUK_Friend) {
  13169. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  13170. LookupResult::Filter F = Previous.makeFilter();
  13171. bool FriendSawTagOutsideEnclosingNamespace = false;
  13172. while (F.hasNext()) {
  13173. NamedDecl *ND = F.next();
  13174. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  13175. if (DC->isFileContext() &&
  13176. !EnclosingNS->Encloses(ND->getDeclContext())) {
  13177. if (getLangOpts().MSVCCompat)
  13178. FriendSawTagOutsideEnclosingNamespace = true;
  13179. else
  13180. F.erase();
  13181. }
  13182. }
  13183. F.done();
  13184. // Diagnose this MSVC extension in the easy case where lookup would have
  13185. // unambiguously found something outside the enclosing namespace.
  13186. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  13187. NamedDecl *ND = Previous.getFoundDecl();
  13188. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  13189. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  13190. }
  13191. }
  13192. // Note: there used to be some attempt at recovery here.
  13193. if (Previous.isAmbiguous())
  13194. return nullptr;
  13195. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  13196. // FIXME: This makes sure that we ignore the contexts associated
  13197. // with C structs, unions, and enums when looking for a matching
  13198. // tag declaration or definition. See the similar lookup tweak
  13199. // in Sema::LookupName; is there a better way to deal with this?
  13200. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  13201. SearchDC = SearchDC->getParent();
  13202. }
  13203. }
  13204. if (Previous.isSingleResult() &&
  13205. Previous.getFoundDecl()->isTemplateParameter()) {
  13206. // Maybe we will complain about the shadowed template parameter.
  13207. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  13208. // Just pretend that we didn't see the previous declaration.
  13209. Previous.clear();
  13210. }
  13211. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  13212. DC->Equals(getStdNamespace())) {
  13213. if (Name->isStr("bad_alloc")) {
  13214. // This is a declaration of or a reference to "std::bad_alloc".
  13215. isStdBadAlloc = true;
  13216. // If std::bad_alloc has been implicitly declared (but made invisible to
  13217. // name lookup), fill in this implicit declaration as the previous
  13218. // declaration, so that the declarations get chained appropriately.
  13219. if (Previous.empty() && StdBadAlloc)
  13220. Previous.addDecl(getStdBadAlloc());
  13221. } else if (Name->isStr("align_val_t")) {
  13222. isStdAlignValT = true;
  13223. if (Previous.empty() && StdAlignValT)
  13224. Previous.addDecl(getStdAlignValT());
  13225. }
  13226. }
  13227. // If we didn't find a previous declaration, and this is a reference
  13228. // (or friend reference), move to the correct scope. In C++, we
  13229. // also need to do a redeclaration lookup there, just in case
  13230. // there's a shadow friend decl.
  13231. if (Name && Previous.empty() &&
  13232. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  13233. if (Invalid) goto CreateNewDecl;
  13234. assert(SS.isEmpty());
  13235. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  13236. // C++ [basic.scope.pdecl]p5:
  13237. // -- for an elaborated-type-specifier of the form
  13238. //
  13239. // class-key identifier
  13240. //
  13241. // if the elaborated-type-specifier is used in the
  13242. // decl-specifier-seq or parameter-declaration-clause of a
  13243. // function defined in namespace scope, the identifier is
  13244. // declared as a class-name in the namespace that contains
  13245. // the declaration; otherwise, except as a friend
  13246. // declaration, the identifier is declared in the smallest
  13247. // non-class, non-function-prototype scope that contains the
  13248. // declaration.
  13249. //
  13250. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  13251. // C structs and unions.
  13252. //
  13253. // It is an error in C++ to declare (rather than define) an enum
  13254. // type, including via an elaborated type specifier. We'll
  13255. // diagnose that later; for now, declare the enum in the same
  13256. // scope as we would have picked for any other tag type.
  13257. //
  13258. // GNU C also supports this behavior as part of its incomplete
  13259. // enum types extension, while GNU C++ does not.
  13260. //
  13261. // Find the context where we'll be declaring the tag.
  13262. // FIXME: We would like to maintain the current DeclContext as the
  13263. // lexical context,
  13264. SearchDC = getTagInjectionContext(SearchDC);
  13265. // Find the scope where we'll be declaring the tag.
  13266. S = getTagInjectionScope(S, getLangOpts());
  13267. } else {
  13268. assert(TUK == TUK_Friend);
  13269. // C++ [namespace.memdef]p3:
  13270. // If a friend declaration in a non-local class first declares a
  13271. // class or function, the friend class or function is a member of
  13272. // the innermost enclosing namespace.
  13273. SearchDC = SearchDC->getEnclosingNamespaceContext();
  13274. }
  13275. // In C++, we need to do a redeclaration lookup to properly
  13276. // diagnose some problems.
  13277. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  13278. // hidden declaration so that we don't get ambiguity errors when using a
  13279. // type declared by an elaborated-type-specifier. In C that is not correct
  13280. // and we should instead merge compatible types found by lookup.
  13281. if (getLangOpts().CPlusPlus) {
  13282. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  13283. LookupQualifiedName(Previous, SearchDC);
  13284. } else {
  13285. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  13286. LookupName(Previous, S);
  13287. }
  13288. }
  13289. // If we have a known previous declaration to use, then use it.
  13290. if (Previous.empty() && SkipBody && SkipBody->Previous)
  13291. Previous.addDecl(SkipBody->Previous);
  13292. if (!Previous.empty()) {
  13293. NamedDecl *PrevDecl = Previous.getFoundDecl();
  13294. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  13295. // It's okay to have a tag decl in the same scope as a typedef
  13296. // which hides a tag decl in the same scope. Finding this
  13297. // insanity with a redeclaration lookup can only actually happen
  13298. // in C++.
  13299. //
  13300. // This is also okay for elaborated-type-specifiers, which is
  13301. // technically forbidden by the current standard but which is
  13302. // okay according to the likely resolution of an open issue;
  13303. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  13304. if (getLangOpts().CPlusPlus) {
  13305. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13306. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  13307. TagDecl *Tag = TT->getDecl();
  13308. if (Tag->getDeclName() == Name &&
  13309. Tag->getDeclContext()->getRedeclContext()
  13310. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  13311. PrevDecl = Tag;
  13312. Previous.clear();
  13313. Previous.addDecl(Tag);
  13314. Previous.resolveKind();
  13315. }
  13316. }
  13317. }
  13318. }
  13319. // If this is a redeclaration of a using shadow declaration, it must
  13320. // declare a tag in the same context. In MSVC mode, we allow a
  13321. // redefinition if either context is within the other.
  13322. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  13323. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  13324. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  13325. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  13326. !(OldTag && isAcceptableTagRedeclContext(
  13327. *this, OldTag->getDeclContext(), SearchDC))) {
  13328. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  13329. Diag(Shadow->getTargetDecl()->getLocation(),
  13330. diag::note_using_decl_target);
  13331. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  13332. << 0;
  13333. // Recover by ignoring the old declaration.
  13334. Previous.clear();
  13335. goto CreateNewDecl;
  13336. }
  13337. }
  13338. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  13339. // If this is a use of a previous tag, or if the tag is already declared
  13340. // in the same scope (so that the definition/declaration completes or
  13341. // rementions the tag), reuse the decl.
  13342. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  13343. isDeclInScope(DirectPrevDecl, SearchDC, S,
  13344. SS.isNotEmpty() || isMemberSpecialization)) {
  13345. // Make sure that this wasn't declared as an enum and now used as a
  13346. // struct or something similar.
  13347. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  13348. TUK == TUK_Definition, KWLoc,
  13349. Name)) {
  13350. bool SafeToContinue
  13351. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  13352. Kind != TTK_Enum);
  13353. if (SafeToContinue)
  13354. Diag(KWLoc, diag::err_use_with_wrong_tag)
  13355. << Name
  13356. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  13357. PrevTagDecl->getKindName());
  13358. else
  13359. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  13360. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  13361. if (SafeToContinue)
  13362. Kind = PrevTagDecl->getTagKind();
  13363. else {
  13364. // Recover by making this an anonymous redefinition.
  13365. Name = nullptr;
  13366. Previous.clear();
  13367. Invalid = true;
  13368. }
  13369. }
  13370. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  13371. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  13372. // If this is an elaborated-type-specifier for a scoped enumeration,
  13373. // the 'class' keyword is not necessary and not permitted.
  13374. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13375. if (ScopedEnum)
  13376. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  13377. << PrevEnum->isScoped()
  13378. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  13379. return PrevTagDecl;
  13380. }
  13381. QualType EnumUnderlyingTy;
  13382. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13383. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  13384. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  13385. EnumUnderlyingTy = QualType(T, 0);
  13386. // All conflicts with previous declarations are recovered by
  13387. // returning the previous declaration, unless this is a definition,
  13388. // in which case we want the caller to bail out.
  13389. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  13390. ScopedEnum, EnumUnderlyingTy,
  13391. IsFixed, PrevEnum))
  13392. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  13393. }
  13394. // C++11 [class.mem]p1:
  13395. // A member shall not be declared twice in the member-specification,
  13396. // except that a nested class or member class template can be declared
  13397. // and then later defined.
  13398. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  13399. S->isDeclScope(PrevDecl)) {
  13400. Diag(NameLoc, diag::ext_member_redeclared);
  13401. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  13402. }
  13403. if (!Invalid) {
  13404. // If this is a use, just return the declaration we found, unless
  13405. // we have attributes.
  13406. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13407. if (!Attrs.empty()) {
  13408. // FIXME: Diagnose these attributes. For now, we create a new
  13409. // declaration to hold them.
  13410. } else if (TUK == TUK_Reference &&
  13411. (PrevTagDecl->getFriendObjectKind() ==
  13412. Decl::FOK_Undeclared ||
  13413. PrevDecl->getOwningModule() != getCurrentModule()) &&
  13414. SS.isEmpty()) {
  13415. // This declaration is a reference to an existing entity, but
  13416. // has different visibility from that entity: it either makes
  13417. // a friend visible or it makes a type visible in a new module.
  13418. // In either case, create a new declaration. We only do this if
  13419. // the declaration would have meant the same thing if no prior
  13420. // declaration were found, that is, if it was found in the same
  13421. // scope where we would have injected a declaration.
  13422. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  13423. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  13424. return PrevTagDecl;
  13425. // This is in the injected scope, create a new declaration in
  13426. // that scope.
  13427. S = getTagInjectionScope(S, getLangOpts());
  13428. } else {
  13429. return PrevTagDecl;
  13430. }
  13431. }
  13432. // Diagnose attempts to redefine a tag.
  13433. if (TUK == TUK_Definition) {
  13434. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  13435. // If we're defining a specialization and the previous definition
  13436. // is from an implicit instantiation, don't emit an error
  13437. // here; we'll catch this in the general case below.
  13438. bool IsExplicitSpecializationAfterInstantiation = false;
  13439. if (isMemberSpecialization) {
  13440. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  13441. IsExplicitSpecializationAfterInstantiation =
  13442. RD->getTemplateSpecializationKind() !=
  13443. TSK_ExplicitSpecialization;
  13444. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  13445. IsExplicitSpecializationAfterInstantiation =
  13446. ED->getTemplateSpecializationKind() !=
  13447. TSK_ExplicitSpecialization;
  13448. }
  13449. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  13450. // not keep more that one definition around (merge them). However,
  13451. // ensure the decl passes the structural compatibility check in
  13452. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  13453. NamedDecl *Hidden = nullptr;
  13454. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  13455. // There is a definition of this tag, but it is not visible. We
  13456. // explicitly make use of C++'s one definition rule here, and
  13457. // assume that this definition is identical to the hidden one
  13458. // we already have. Make the existing definition visible and
  13459. // use it in place of this one.
  13460. if (!getLangOpts().CPlusPlus) {
  13461. // Postpone making the old definition visible until after we
  13462. // complete parsing the new one and do the structural
  13463. // comparison.
  13464. SkipBody->CheckSameAsPrevious = true;
  13465. SkipBody->New = createTagFromNewDecl();
  13466. SkipBody->Previous = Def;
  13467. return Def;
  13468. } else {
  13469. SkipBody->ShouldSkip = true;
  13470. SkipBody->Previous = Def;
  13471. makeMergedDefinitionVisible(Hidden);
  13472. // Carry on and handle it like a normal definition. We'll
  13473. // skip starting the definitiion later.
  13474. }
  13475. } else if (!IsExplicitSpecializationAfterInstantiation) {
  13476. // A redeclaration in function prototype scope in C isn't
  13477. // visible elsewhere, so merely issue a warning.
  13478. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  13479. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  13480. else
  13481. Diag(NameLoc, diag::err_redefinition) << Name;
  13482. notePreviousDefinition(Def,
  13483. NameLoc.isValid() ? NameLoc : KWLoc);
  13484. // If this is a redefinition, recover by making this
  13485. // struct be anonymous, which will make any later
  13486. // references get the previous definition.
  13487. Name = nullptr;
  13488. Previous.clear();
  13489. Invalid = true;
  13490. }
  13491. } else {
  13492. // If the type is currently being defined, complain
  13493. // about a nested redefinition.
  13494. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  13495. if (TD->isBeingDefined()) {
  13496. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  13497. Diag(PrevTagDecl->getLocation(),
  13498. diag::note_previous_definition);
  13499. Name = nullptr;
  13500. Previous.clear();
  13501. Invalid = true;
  13502. }
  13503. }
  13504. // Okay, this is definition of a previously declared or referenced
  13505. // tag. We're going to create a new Decl for it.
  13506. }
  13507. // Okay, we're going to make a redeclaration. If this is some kind
  13508. // of reference, make sure we build the redeclaration in the same DC
  13509. // as the original, and ignore the current access specifier.
  13510. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  13511. SearchDC = PrevTagDecl->getDeclContext();
  13512. AS = AS_none;
  13513. }
  13514. }
  13515. // If we get here we have (another) forward declaration or we
  13516. // have a definition. Just create a new decl.
  13517. } else {
  13518. // If we get here, this is a definition of a new tag type in a nested
  13519. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  13520. // new decl/type. We set PrevDecl to NULL so that the entities
  13521. // have distinct types.
  13522. Previous.clear();
  13523. }
  13524. // If we get here, we're going to create a new Decl. If PrevDecl
  13525. // is non-NULL, it's a definition of the tag declared by
  13526. // PrevDecl. If it's NULL, we have a new definition.
  13527. // Otherwise, PrevDecl is not a tag, but was found with tag
  13528. // lookup. This is only actually possible in C++, where a few
  13529. // things like templates still live in the tag namespace.
  13530. } else {
  13531. // Use a better diagnostic if an elaborated-type-specifier
  13532. // found the wrong kind of type on the first
  13533. // (non-redeclaration) lookup.
  13534. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  13535. !Previous.isForRedeclaration()) {
  13536. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13537. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  13538. << Kind;
  13539. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  13540. Invalid = true;
  13541. // Otherwise, only diagnose if the declaration is in scope.
  13542. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  13543. SS.isNotEmpty() || isMemberSpecialization)) {
  13544. // do nothing
  13545. // Diagnose implicit declarations introduced by elaborated types.
  13546. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13547. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13548. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  13549. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13550. Invalid = true;
  13551. // Otherwise it's a declaration. Call out a particularly common
  13552. // case here.
  13553. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13554. unsigned Kind = 0;
  13555. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  13556. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  13557. << Name << Kind << TND->getUnderlyingType();
  13558. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13559. Invalid = true;
  13560. // Otherwise, diagnose.
  13561. } else {
  13562. // The tag name clashes with something else in the target scope,
  13563. // issue an error and recover by making this tag be anonymous.
  13564. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  13565. notePreviousDefinition(PrevDecl, NameLoc);
  13566. Name = nullptr;
  13567. Invalid = true;
  13568. }
  13569. // The existing declaration isn't relevant to us; we're in a
  13570. // new scope, so clear out the previous declaration.
  13571. Previous.clear();
  13572. }
  13573. }
  13574. CreateNewDecl:
  13575. TagDecl *PrevDecl = nullptr;
  13576. if (Previous.isSingleResult())
  13577. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  13578. // If there is an identifier, use the location of the identifier as the
  13579. // location of the decl, otherwise use the location of the struct/union
  13580. // keyword.
  13581. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  13582. // Otherwise, create a new declaration. If there is a previous
  13583. // declaration of the same entity, the two will be linked via
  13584. // PrevDecl.
  13585. TagDecl *New;
  13586. if (Kind == TTK_Enum) {
  13587. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13588. // enum X { A, B, C } D; D should chain to X.
  13589. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  13590. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  13591. ScopedEnumUsesClassTag, IsFixed);
  13592. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  13593. StdAlignValT = cast<EnumDecl>(New);
  13594. // If this is an undefined enum, warn.
  13595. if (TUK != TUK_Definition && !Invalid) {
  13596. TagDecl *Def;
  13597. if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
  13598. // C++0x: 7.2p2: opaque-enum-declaration.
  13599. // Conflicts are diagnosed above. Do nothing.
  13600. }
  13601. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  13602. Diag(Loc, diag::ext_forward_ref_enum_def)
  13603. << New;
  13604. Diag(Def->getLocation(), diag::note_previous_definition);
  13605. } else {
  13606. unsigned DiagID = diag::ext_forward_ref_enum;
  13607. if (getLangOpts().MSVCCompat)
  13608. DiagID = diag::ext_ms_forward_ref_enum;
  13609. else if (getLangOpts().CPlusPlus)
  13610. DiagID = diag::err_forward_ref_enum;
  13611. Diag(Loc, DiagID);
  13612. }
  13613. }
  13614. if (EnumUnderlying) {
  13615. EnumDecl *ED = cast<EnumDecl>(New);
  13616. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13617. ED->setIntegerTypeSourceInfo(TI);
  13618. else
  13619. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  13620. ED->setPromotionType(ED->getIntegerType());
  13621. assert(ED->isComplete() && "enum with type should be complete");
  13622. }
  13623. } else {
  13624. // struct/union/class
  13625. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13626. // struct X { int A; } D; D should chain to X.
  13627. if (getLangOpts().CPlusPlus) {
  13628. // FIXME: Look for a way to use RecordDecl for simple structs.
  13629. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13630. cast_or_null<CXXRecordDecl>(PrevDecl));
  13631. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  13632. StdBadAlloc = cast<CXXRecordDecl>(New);
  13633. } else
  13634. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13635. cast_or_null<RecordDecl>(PrevDecl));
  13636. }
  13637. // C++11 [dcl.type]p3:
  13638. // A type-specifier-seq shall not define a class or enumeration [...].
  13639. if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
  13640. TUK == TUK_Definition) {
  13641. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  13642. << Context.getTagDeclType(New);
  13643. Invalid = true;
  13644. }
  13645. if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
  13646. DC->getDeclKind() == Decl::Enum) {
  13647. Diag(New->getLocation(), diag::err_type_defined_in_enum)
  13648. << Context.getTagDeclType(New);
  13649. Invalid = true;
  13650. }
  13651. // Maybe add qualifier info.
  13652. if (SS.isNotEmpty()) {
  13653. if (SS.isSet()) {
  13654. // If this is either a declaration or a definition, check the
  13655. // nested-name-specifier against the current context.
  13656. if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
  13657. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
  13658. isMemberSpecialization))
  13659. Invalid = true;
  13660. New->setQualifierInfo(SS.getWithLocInContext(Context));
  13661. if (TemplateParameterLists.size() > 0) {
  13662. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  13663. }
  13664. }
  13665. else
  13666. Invalid = true;
  13667. }
  13668. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  13669. // Add alignment attributes if necessary; these attributes are checked when
  13670. // the ASTContext lays out the structure.
  13671. //
  13672. // It is important for implementing the correct semantics that this
  13673. // happen here (in ActOnTag). The #pragma pack stack is
  13674. // maintained as a result of parser callbacks which can occur at
  13675. // many points during the parsing of a struct declaration (because
  13676. // the #pragma tokens are effectively skipped over during the
  13677. // parsing of the struct).
  13678. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  13679. AddAlignmentAttributesForRecord(RD);
  13680. AddMsStructLayoutForRecord(RD);
  13681. }
  13682. }
  13683. if (ModulePrivateLoc.isValid()) {
  13684. if (isMemberSpecialization)
  13685. Diag(New->getLocation(), diag::err_module_private_specialization)
  13686. << 2
  13687. << FixItHint::CreateRemoval(ModulePrivateLoc);
  13688. // __module_private__ does not apply to local classes. However, we only
  13689. // diagnose this as an error when the declaration specifiers are
  13690. // freestanding. Here, we just ignore the __module_private__.
  13691. else if (!SearchDC->isFunctionOrMethod())
  13692. New->setModulePrivate();
  13693. }
  13694. // If this is a specialization of a member class (of a class template),
  13695. // check the specialization.
  13696. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  13697. Invalid = true;
  13698. // If we're declaring or defining a tag in function prototype scope in C,
  13699. // note that this type can only be used within the function and add it to
  13700. // the list of decls to inject into the function definition scope.
  13701. if ((Name || Kind == TTK_Enum) &&
  13702. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  13703. if (getLangOpts().CPlusPlus) {
  13704. // C++ [dcl.fct]p6:
  13705. // Types shall not be defined in return or parameter types.
  13706. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  13707. Diag(Loc, diag::err_type_defined_in_param_type)
  13708. << Name;
  13709. Invalid = true;
  13710. }
  13711. } else if (!PrevDecl) {
  13712. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  13713. }
  13714. }
  13715. if (Invalid)
  13716. New->setInvalidDecl();
  13717. // Set the lexical context. If the tag has a C++ scope specifier, the
  13718. // lexical context will be different from the semantic context.
  13719. New->setLexicalDeclContext(CurContext);
  13720. // Mark this as a friend decl if applicable.
  13721. // In Microsoft mode, a friend declaration also acts as a forward
  13722. // declaration so we always pass true to setObjectOfFriendDecl to make
  13723. // the tag name visible.
  13724. if (TUK == TUK_Friend)
  13725. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  13726. // Set the access specifier.
  13727. if (!Invalid && SearchDC->isRecord())
  13728. SetMemberAccessSpecifier(New, PrevDecl, AS);
  13729. if (PrevDecl)
  13730. CheckRedeclarationModuleOwnership(New, PrevDecl);
  13731. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  13732. New->startDefinition();
  13733. ProcessDeclAttributeList(S, New, Attrs);
  13734. AddPragmaAttributes(S, New);
  13735. // If this has an identifier, add it to the scope stack.
  13736. if (TUK == TUK_Friend) {
  13737. // We might be replacing an existing declaration in the lookup tables;
  13738. // if so, borrow its access specifier.
  13739. if (PrevDecl)
  13740. New->setAccess(PrevDecl->getAccess());
  13741. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  13742. DC->makeDeclVisibleInContext(New);
  13743. if (Name) // can be null along some error paths
  13744. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  13745. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  13746. } else if (Name) {
  13747. S = getNonFieldDeclScope(S);
  13748. PushOnScopeChains(New, S, true);
  13749. } else {
  13750. CurContext->addDecl(New);
  13751. }
  13752. // If this is the C FILE type, notify the AST context.
  13753. if (IdentifierInfo *II = New->getIdentifier())
  13754. if (!New->isInvalidDecl() &&
  13755. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  13756. II->isStr("FILE"))
  13757. Context.setFILEDecl(New);
  13758. if (PrevDecl)
  13759. mergeDeclAttributes(New, PrevDecl);
  13760. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
  13761. inferGslOwnerPointerAttribute(CXXRD);
  13762. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13763. // record.
  13764. AddPushedVisibilityAttribute(New);
  13765. if (isMemberSpecialization && !New->isInvalidDecl())
  13766. CompleteMemberSpecialization(New, Previous);
  13767. OwnedDecl = true;
  13768. // In C++, don't return an invalid declaration. We can't recover well from
  13769. // the cases where we make the type anonymous.
  13770. if (Invalid && getLangOpts().CPlusPlus) {
  13771. if (New->isBeingDefined())
  13772. if (auto RD = dyn_cast<RecordDecl>(New))
  13773. RD->completeDefinition();
  13774. return nullptr;
  13775. } else if (SkipBody && SkipBody->ShouldSkip) {
  13776. return SkipBody->Previous;
  13777. } else {
  13778. return New;
  13779. }
  13780. }
  13781. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  13782. AdjustDeclIfTemplate(TagD);
  13783. TagDecl *Tag = cast<TagDecl>(TagD);
  13784. // Enter the tag context.
  13785. PushDeclContext(S, Tag);
  13786. ActOnDocumentableDecl(TagD);
  13787. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13788. // record.
  13789. AddPushedVisibilityAttribute(Tag);
  13790. }
  13791. bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
  13792. SkipBodyInfo &SkipBody) {
  13793. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  13794. return false;
  13795. // Make the previous decl visible.
  13796. makeMergedDefinitionVisible(SkipBody.Previous);
  13797. return true;
  13798. }
  13799. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  13800. assert(isa<ObjCContainerDecl>(IDecl) &&
  13801. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  13802. DeclContext *OCD = cast<DeclContext>(IDecl);
  13803. assert(getContainingDC(OCD) == CurContext &&
  13804. "The next DeclContext should be lexically contained in the current one.");
  13805. CurContext = OCD;
  13806. return IDecl;
  13807. }
  13808. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  13809. SourceLocation FinalLoc,
  13810. bool IsFinalSpelledSealed,
  13811. SourceLocation LBraceLoc) {
  13812. AdjustDeclIfTemplate(TagD);
  13813. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  13814. FieldCollector->StartClass();
  13815. if (!Record->getIdentifier())
  13816. return;
  13817. if (FinalLoc.isValid())
  13818. Record->addAttr(FinalAttr::Create(
  13819. Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
  13820. static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
  13821. // C++ [class]p2:
  13822. // [...] The class-name is also inserted into the scope of the
  13823. // class itself; this is known as the injected-class-name. For
  13824. // purposes of access checking, the injected-class-name is treated
  13825. // as if it were a public member name.
  13826. CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
  13827. Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
  13828. Record->getLocation(), Record->getIdentifier(),
  13829. /*PrevDecl=*/nullptr,
  13830. /*DelayTypeCreation=*/true);
  13831. Context.getTypeDeclType(InjectedClassName, Record);
  13832. InjectedClassName->setImplicit();
  13833. InjectedClassName->setAccess(AS_public);
  13834. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  13835. InjectedClassName->setDescribedClassTemplate(Template);
  13836. PushOnScopeChains(InjectedClassName, S);
  13837. assert(InjectedClassName->isInjectedClassName() &&
  13838. "Broken injected-class-name");
  13839. }
  13840. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  13841. SourceRange BraceRange) {
  13842. AdjustDeclIfTemplate(TagD);
  13843. TagDecl *Tag = cast<TagDecl>(TagD);
  13844. Tag->setBraceRange(BraceRange);
  13845. // Make sure we "complete" the definition even it is invalid.
  13846. if (Tag->isBeingDefined()) {
  13847. assert(Tag->isInvalidDecl() && "We should already have completed it");
  13848. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13849. RD->completeDefinition();
  13850. }
  13851. if (isa<CXXRecordDecl>(Tag)) {
  13852. FieldCollector->FinishClass();
  13853. }
  13854. // Exit this scope of this tag's definition.
  13855. PopDeclContext();
  13856. if (getCurLexicalContext()->isObjCContainer() &&
  13857. Tag->getDeclContext()->isFileContext())
  13858. Tag->setTopLevelDeclInObjCContainer();
  13859. // Notify the consumer that we've defined a tag.
  13860. if (!Tag->isInvalidDecl())
  13861. Consumer.HandleTagDeclDefinition(Tag);
  13862. }
  13863. void Sema::ActOnObjCContainerFinishDefinition() {
  13864. // Exit this scope of this interface definition.
  13865. PopDeclContext();
  13866. }
  13867. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  13868. assert(DC == CurContext && "Mismatch of container contexts");
  13869. OriginalLexicalContext = DC;
  13870. ActOnObjCContainerFinishDefinition();
  13871. }
  13872. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  13873. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  13874. OriginalLexicalContext = nullptr;
  13875. }
  13876. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  13877. AdjustDeclIfTemplate(TagD);
  13878. TagDecl *Tag = cast<TagDecl>(TagD);
  13879. Tag->setInvalidDecl();
  13880. // Make sure we "complete" the definition even it is invalid.
  13881. if (Tag->isBeingDefined()) {
  13882. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13883. RD->completeDefinition();
  13884. }
  13885. // We're undoing ActOnTagStartDefinition here, not
  13886. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  13887. // the FieldCollector.
  13888. PopDeclContext();
  13889. }
  13890. // Note that FieldName may be null for anonymous bitfields.
  13891. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  13892. IdentifierInfo *FieldName,
  13893. QualType FieldTy, bool IsMsStruct,
  13894. Expr *BitWidth, bool *ZeroWidth) {
  13895. // Default to true; that shouldn't confuse checks for emptiness
  13896. if (ZeroWidth)
  13897. *ZeroWidth = true;
  13898. // C99 6.7.2.1p4 - verify the field type.
  13899. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  13900. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  13901. // Handle incomplete types with specific error.
  13902. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  13903. return ExprError();
  13904. if (FieldName)
  13905. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  13906. << FieldName << FieldTy << BitWidth->getSourceRange();
  13907. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  13908. << FieldTy << BitWidth->getSourceRange();
  13909. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  13910. UPPC_BitFieldWidth))
  13911. return ExprError();
  13912. // If the bit-width is type- or value-dependent, don't try to check
  13913. // it now.
  13914. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  13915. return BitWidth;
  13916. llvm::APSInt Value;
  13917. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  13918. if (ICE.isInvalid())
  13919. return ICE;
  13920. BitWidth = ICE.get();
  13921. if (Value != 0 && ZeroWidth)
  13922. *ZeroWidth = false;
  13923. // Zero-width bitfield is ok for anonymous field.
  13924. if (Value == 0 && FieldName)
  13925. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  13926. if (Value.isSigned() && Value.isNegative()) {
  13927. if (FieldName)
  13928. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  13929. << FieldName << Value.toString(10);
  13930. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  13931. << Value.toString(10);
  13932. }
  13933. if (!FieldTy->isDependentType()) {
  13934. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  13935. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  13936. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  13937. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  13938. // ABI.
  13939. bool CStdConstraintViolation =
  13940. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  13941. bool MSBitfieldViolation =
  13942. Value.ugt(TypeStorageSize) &&
  13943. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  13944. if (CStdConstraintViolation || MSBitfieldViolation) {
  13945. unsigned DiagWidth =
  13946. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  13947. if (FieldName)
  13948. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  13949. << FieldName << (unsigned)Value.getZExtValue()
  13950. << !CStdConstraintViolation << DiagWidth;
  13951. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  13952. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  13953. << DiagWidth;
  13954. }
  13955. // Warn on types where the user might conceivably expect to get all
  13956. // specified bits as value bits: that's all integral types other than
  13957. // 'bool'.
  13958. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  13959. if (FieldName)
  13960. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  13961. << FieldName << (unsigned)Value.getZExtValue()
  13962. << (unsigned)TypeWidth;
  13963. else
  13964. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  13965. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  13966. }
  13967. }
  13968. return BitWidth;
  13969. }
  13970. /// ActOnField - Each field of a C struct/union is passed into this in order
  13971. /// to create a FieldDecl object for it.
  13972. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  13973. Declarator &D, Expr *BitfieldWidth) {
  13974. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  13975. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  13976. /*InitStyle=*/ICIS_NoInit, AS_public);
  13977. return Res;
  13978. }
  13979. /// HandleField - Analyze a field of a C struct or a C++ data member.
  13980. ///
  13981. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  13982. SourceLocation DeclStart,
  13983. Declarator &D, Expr *BitWidth,
  13984. InClassInitStyle InitStyle,
  13985. AccessSpecifier AS) {
  13986. if (D.isDecompositionDeclarator()) {
  13987. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  13988. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  13989. << Decomp.getSourceRange();
  13990. return nullptr;
  13991. }
  13992. IdentifierInfo *II = D.getIdentifier();
  13993. SourceLocation Loc = DeclStart;
  13994. if (II) Loc = D.getIdentifierLoc();
  13995. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13996. QualType T = TInfo->getType();
  13997. if (getLangOpts().CPlusPlus) {
  13998. CheckExtraCXXDefaultArguments(D);
  13999. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  14000. UPPC_DataMemberType)) {
  14001. D.setInvalidType();
  14002. T = Context.IntTy;
  14003. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  14004. }
  14005. }
  14006. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  14007. if (D.getDeclSpec().isInlineSpecified())
  14008. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  14009. << getLangOpts().CPlusPlus17;
  14010. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  14011. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  14012. diag::err_invalid_thread)
  14013. << DeclSpec::getSpecifierName(TSCS);
  14014. // Check to see if this name was declared as a member previously
  14015. NamedDecl *PrevDecl = nullptr;
  14016. LookupResult Previous(*this, II, Loc, LookupMemberName,
  14017. ForVisibleRedeclaration);
  14018. LookupName(Previous, S);
  14019. switch (Previous.getResultKind()) {
  14020. case LookupResult::Found:
  14021. case LookupResult::FoundUnresolvedValue:
  14022. PrevDecl = Previous.getAsSingle<NamedDecl>();
  14023. break;
  14024. case LookupResult::FoundOverloaded:
  14025. PrevDecl = Previous.getRepresentativeDecl();
  14026. break;
  14027. case LookupResult::NotFound:
  14028. case LookupResult::NotFoundInCurrentInstantiation:
  14029. case LookupResult::Ambiguous:
  14030. break;
  14031. }
  14032. Previous.suppressDiagnostics();
  14033. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  14034. // Maybe we will complain about the shadowed template parameter.
  14035. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  14036. // Just pretend that we didn't see the previous declaration.
  14037. PrevDecl = nullptr;
  14038. }
  14039. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  14040. PrevDecl = nullptr;
  14041. bool Mutable
  14042. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  14043. SourceLocation TSSL = D.getBeginLoc();
  14044. FieldDecl *NewFD
  14045. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  14046. TSSL, AS, PrevDecl, &D);
  14047. if (NewFD->isInvalidDecl())
  14048. Record->setInvalidDecl();
  14049. if (D.getDeclSpec().isModulePrivateSpecified())
  14050. NewFD->setModulePrivate();
  14051. if (NewFD->isInvalidDecl() && PrevDecl) {
  14052. // Don't introduce NewFD into scope; there's already something
  14053. // with the same name in the same scope.
  14054. } else if (II) {
  14055. PushOnScopeChains(NewFD, S);
  14056. } else
  14057. Record->addDecl(NewFD);
  14058. return NewFD;
  14059. }
  14060. /// Build a new FieldDecl and check its well-formedness.
  14061. ///
  14062. /// This routine builds a new FieldDecl given the fields name, type,
  14063. /// record, etc. \p PrevDecl should refer to any previous declaration
  14064. /// with the same name and in the same scope as the field to be
  14065. /// created.
  14066. ///
  14067. /// \returns a new FieldDecl.
  14068. ///
  14069. /// \todo The Declarator argument is a hack. It will be removed once
  14070. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  14071. TypeSourceInfo *TInfo,
  14072. RecordDecl *Record, SourceLocation Loc,
  14073. bool Mutable, Expr *BitWidth,
  14074. InClassInitStyle InitStyle,
  14075. SourceLocation TSSL,
  14076. AccessSpecifier AS, NamedDecl *PrevDecl,
  14077. Declarator *D) {
  14078. IdentifierInfo *II = Name.getAsIdentifierInfo();
  14079. bool InvalidDecl = false;
  14080. if (D) InvalidDecl = D->isInvalidType();
  14081. // If we receive a broken type, recover by assuming 'int' and
  14082. // marking this declaration as invalid.
  14083. if (T.isNull()) {
  14084. InvalidDecl = true;
  14085. T = Context.IntTy;
  14086. }
  14087. QualType EltTy = Context.getBaseElementType(T);
  14088. if (!EltTy->isDependentType()) {
  14089. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  14090. // Fields of incomplete type force their record to be invalid.
  14091. Record->setInvalidDecl();
  14092. InvalidDecl = true;
  14093. } else {
  14094. NamedDecl *Def;
  14095. EltTy->isIncompleteType(&Def);
  14096. if (Def && Def->isInvalidDecl()) {
  14097. Record->setInvalidDecl();
  14098. InvalidDecl = true;
  14099. }
  14100. }
  14101. }
  14102. // TR 18037 does not allow fields to be declared with address space
  14103. if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
  14104. T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
  14105. Diag(Loc, diag::err_field_with_address_space);
  14106. Record->setInvalidDecl();
  14107. InvalidDecl = true;
  14108. }
  14109. if (LangOpts.OpenCL) {
  14110. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  14111. // used as structure or union field: image, sampler, event or block types.
  14112. if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
  14113. T->isBlockPointerType()) {
  14114. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  14115. Record->setInvalidDecl();
  14116. InvalidDecl = true;
  14117. }
  14118. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  14119. if (BitWidth) {
  14120. Diag(Loc, diag::err_opencl_bitfields);
  14121. InvalidDecl = true;
  14122. }
  14123. }
  14124. // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
  14125. if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
  14126. T.hasQualifiers()) {
  14127. InvalidDecl = true;
  14128. Diag(Loc, diag::err_anon_bitfield_qualifiers);
  14129. }
  14130. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  14131. // than a variably modified type.
  14132. if (!InvalidDecl && T->isVariablyModifiedType()) {
  14133. bool SizeIsNegative;
  14134. llvm::APSInt Oversized;
  14135. TypeSourceInfo *FixedTInfo =
  14136. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  14137. SizeIsNegative,
  14138. Oversized);
  14139. if (FixedTInfo) {
  14140. Diag(Loc, diag::warn_illegal_constant_array_size);
  14141. TInfo = FixedTInfo;
  14142. T = FixedTInfo->getType();
  14143. } else {
  14144. if (SizeIsNegative)
  14145. Diag(Loc, diag::err_typecheck_negative_array_size);
  14146. else if (Oversized.getBoolValue())
  14147. Diag(Loc, diag::err_array_too_large)
  14148. << Oversized.toString(10);
  14149. else
  14150. Diag(Loc, diag::err_typecheck_field_variable_size);
  14151. InvalidDecl = true;
  14152. }
  14153. }
  14154. // Fields can not have abstract class types
  14155. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  14156. diag::err_abstract_type_in_decl,
  14157. AbstractFieldType))
  14158. InvalidDecl = true;
  14159. bool ZeroWidth = false;
  14160. if (InvalidDecl)
  14161. BitWidth = nullptr;
  14162. // If this is declared as a bit-field, check the bit-field.
  14163. if (BitWidth) {
  14164. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  14165. &ZeroWidth).get();
  14166. if (!BitWidth) {
  14167. InvalidDecl = true;
  14168. BitWidth = nullptr;
  14169. ZeroWidth = false;
  14170. }
  14171. }
  14172. // Check that 'mutable' is consistent with the type of the declaration.
  14173. if (!InvalidDecl && Mutable) {
  14174. unsigned DiagID = 0;
  14175. if (T->isReferenceType())
  14176. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  14177. : diag::err_mutable_reference;
  14178. else if (T.isConstQualified())
  14179. DiagID = diag::err_mutable_const;
  14180. if (DiagID) {
  14181. SourceLocation ErrLoc = Loc;
  14182. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  14183. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  14184. Diag(ErrLoc, DiagID);
  14185. if (DiagID != diag::ext_mutable_reference) {
  14186. Mutable = false;
  14187. InvalidDecl = true;
  14188. }
  14189. }
  14190. }
  14191. // C++11 [class.union]p8 (DR1460):
  14192. // At most one variant member of a union may have a
  14193. // brace-or-equal-initializer.
  14194. if (InitStyle != ICIS_NoInit)
  14195. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  14196. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  14197. BitWidth, Mutable, InitStyle);
  14198. if (InvalidDecl)
  14199. NewFD->setInvalidDecl();
  14200. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  14201. Diag(Loc, diag::err_duplicate_member) << II;
  14202. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  14203. NewFD->setInvalidDecl();
  14204. }
  14205. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  14206. if (Record->isUnion()) {
  14207. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  14208. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  14209. if (RDecl->getDefinition()) {
  14210. // C++ [class.union]p1: An object of a class with a non-trivial
  14211. // constructor, a non-trivial copy constructor, a non-trivial
  14212. // destructor, or a non-trivial copy assignment operator
  14213. // cannot be a member of a union, nor can an array of such
  14214. // objects.
  14215. if (CheckNontrivialField(NewFD))
  14216. NewFD->setInvalidDecl();
  14217. }
  14218. }
  14219. // C++ [class.union]p1: If a union contains a member of reference type,
  14220. // the program is ill-formed, except when compiling with MSVC extensions
  14221. // enabled.
  14222. if (EltTy->isReferenceType()) {
  14223. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  14224. diag::ext_union_member_of_reference_type :
  14225. diag::err_union_member_of_reference_type)
  14226. << NewFD->getDeclName() << EltTy;
  14227. if (!getLangOpts().MicrosoftExt)
  14228. NewFD->setInvalidDecl();
  14229. }
  14230. }
  14231. }
  14232. // FIXME: We need to pass in the attributes given an AST
  14233. // representation, not a parser representation.
  14234. if (D) {
  14235. // FIXME: The current scope is almost... but not entirely... correct here.
  14236. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  14237. if (NewFD->hasAttrs())
  14238. CheckAlignasUnderalignment(NewFD);
  14239. }
  14240. // In auto-retain/release, infer strong retension for fields of
  14241. // retainable type.
  14242. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  14243. NewFD->setInvalidDecl();
  14244. if (T.isObjCGCWeak())
  14245. Diag(Loc, diag::warn_attribute_weak_on_field);
  14246. NewFD->setAccess(AS);
  14247. return NewFD;
  14248. }
  14249. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  14250. assert(FD);
  14251. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  14252. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  14253. return false;
  14254. QualType EltTy = Context.getBaseElementType(FD->getType());
  14255. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  14256. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  14257. if (RDecl->getDefinition()) {
  14258. // We check for copy constructors before constructors
  14259. // because otherwise we'll never get complaints about
  14260. // copy constructors.
  14261. CXXSpecialMember member = CXXInvalid;
  14262. // We're required to check for any non-trivial constructors. Since the
  14263. // implicit default constructor is suppressed if there are any
  14264. // user-declared constructors, we just need to check that there is a
  14265. // trivial default constructor and a trivial copy constructor. (We don't
  14266. // worry about move constructors here, since this is a C++98 check.)
  14267. if (RDecl->hasNonTrivialCopyConstructor())
  14268. member = CXXCopyConstructor;
  14269. else if (!RDecl->hasTrivialDefaultConstructor())
  14270. member = CXXDefaultConstructor;
  14271. else if (RDecl->hasNonTrivialCopyAssignment())
  14272. member = CXXCopyAssignment;
  14273. else if (RDecl->hasNonTrivialDestructor())
  14274. member = CXXDestructor;
  14275. if (member != CXXInvalid) {
  14276. if (!getLangOpts().CPlusPlus11 &&
  14277. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  14278. // Objective-C++ ARC: it is an error to have a non-trivial field of
  14279. // a union. However, system headers in Objective-C programs
  14280. // occasionally have Objective-C lifetime objects within unions,
  14281. // and rather than cause the program to fail, we make those
  14282. // members unavailable.
  14283. SourceLocation Loc = FD->getLocation();
  14284. if (getSourceManager().isInSystemHeader(Loc)) {
  14285. if (!FD->hasAttr<UnavailableAttr>())
  14286. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  14287. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  14288. return false;
  14289. }
  14290. }
  14291. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  14292. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  14293. diag::err_illegal_union_or_anon_struct_member)
  14294. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  14295. DiagnoseNontrivial(RDecl, member);
  14296. return !getLangOpts().CPlusPlus11;
  14297. }
  14298. }
  14299. }
  14300. return false;
  14301. }
  14302. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  14303. /// AST enum value.
  14304. static ObjCIvarDecl::AccessControl
  14305. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  14306. switch (ivarVisibility) {
  14307. default: llvm_unreachable("Unknown visitibility kind");
  14308. case tok::objc_private: return ObjCIvarDecl::Private;
  14309. case tok::objc_public: return ObjCIvarDecl::Public;
  14310. case tok::objc_protected: return ObjCIvarDecl::Protected;
  14311. case tok::objc_package: return ObjCIvarDecl::Package;
  14312. }
  14313. }
  14314. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  14315. /// in order to create an IvarDecl object for it.
  14316. Decl *Sema::ActOnIvar(Scope *S,
  14317. SourceLocation DeclStart,
  14318. Declarator &D, Expr *BitfieldWidth,
  14319. tok::ObjCKeywordKind Visibility) {
  14320. IdentifierInfo *II = D.getIdentifier();
  14321. Expr *BitWidth = (Expr*)BitfieldWidth;
  14322. SourceLocation Loc = DeclStart;
  14323. if (II) Loc = D.getIdentifierLoc();
  14324. // FIXME: Unnamed fields can be handled in various different ways, for
  14325. // example, unnamed unions inject all members into the struct namespace!
  14326. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14327. QualType T = TInfo->getType();
  14328. if (BitWidth) {
  14329. // 6.7.2.1p3, 6.7.2.1p4
  14330. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  14331. if (!BitWidth)
  14332. D.setInvalidType();
  14333. } else {
  14334. // Not a bitfield.
  14335. // validate II.
  14336. }
  14337. if (T->isReferenceType()) {
  14338. Diag(Loc, diag::err_ivar_reference_type);
  14339. D.setInvalidType();
  14340. }
  14341. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  14342. // than a variably modified type.
  14343. else if (T->isVariablyModifiedType()) {
  14344. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  14345. D.setInvalidType();
  14346. }
  14347. // Get the visibility (access control) for this ivar.
  14348. ObjCIvarDecl::AccessControl ac =
  14349. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  14350. : ObjCIvarDecl::None;
  14351. // Must set ivar's DeclContext to its enclosing interface.
  14352. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  14353. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  14354. return nullptr;
  14355. ObjCContainerDecl *EnclosingContext;
  14356. if (ObjCImplementationDecl *IMPDecl =
  14357. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14358. if (LangOpts.ObjCRuntime.isFragile()) {
  14359. // Case of ivar declared in an implementation. Context is that of its class.
  14360. EnclosingContext = IMPDecl->getClassInterface();
  14361. assert(EnclosingContext && "Implementation has no class interface!");
  14362. }
  14363. else
  14364. EnclosingContext = EnclosingDecl;
  14365. } else {
  14366. if (ObjCCategoryDecl *CDecl =
  14367. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14368. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  14369. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  14370. return nullptr;
  14371. }
  14372. }
  14373. EnclosingContext = EnclosingDecl;
  14374. }
  14375. // Construct the decl.
  14376. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  14377. DeclStart, Loc, II, T,
  14378. TInfo, ac, (Expr *)BitfieldWidth);
  14379. if (II) {
  14380. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  14381. ForVisibleRedeclaration);
  14382. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  14383. && !isa<TagDecl>(PrevDecl)) {
  14384. Diag(Loc, diag::err_duplicate_member) << II;
  14385. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  14386. NewID->setInvalidDecl();
  14387. }
  14388. }
  14389. // Process attributes attached to the ivar.
  14390. ProcessDeclAttributes(S, NewID, D);
  14391. if (D.isInvalidType())
  14392. NewID->setInvalidDecl();
  14393. // In ARC, infer 'retaining' for ivars of retainable type.
  14394. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  14395. NewID->setInvalidDecl();
  14396. if (D.getDeclSpec().isModulePrivateSpecified())
  14397. NewID->setModulePrivate();
  14398. if (II) {
  14399. // FIXME: When interfaces are DeclContexts, we'll need to add
  14400. // these to the interface.
  14401. S->AddDecl(NewID);
  14402. IdResolver.AddDecl(NewID);
  14403. }
  14404. if (LangOpts.ObjCRuntime.isNonFragile() &&
  14405. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  14406. Diag(Loc, diag::warn_ivars_in_interface);
  14407. return NewID;
  14408. }
  14409. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  14410. /// class and class extensions. For every class \@interface and class
  14411. /// extension \@interface, if the last ivar is a bitfield of any type,
  14412. /// then add an implicit `char :0` ivar to the end of that interface.
  14413. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  14414. SmallVectorImpl<Decl *> &AllIvarDecls) {
  14415. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  14416. return;
  14417. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  14418. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  14419. if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
  14420. return;
  14421. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  14422. if (!ID) {
  14423. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  14424. if (!CD->IsClassExtension())
  14425. return;
  14426. }
  14427. // No need to add this to end of @implementation.
  14428. else
  14429. return;
  14430. }
  14431. // All conditions are met. Add a new bitfield to the tail end of ivars.
  14432. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  14433. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  14434. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  14435. DeclLoc, DeclLoc, nullptr,
  14436. Context.CharTy,
  14437. Context.getTrivialTypeSourceInfo(Context.CharTy,
  14438. DeclLoc),
  14439. ObjCIvarDecl::Private, BW,
  14440. true);
  14441. AllIvarDecls.push_back(Ivar);
  14442. }
  14443. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  14444. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  14445. SourceLocation RBrac,
  14446. const ParsedAttributesView &Attrs) {
  14447. assert(EnclosingDecl && "missing record or interface decl");
  14448. // If this is an Objective-C @implementation or category and we have
  14449. // new fields here we should reset the layout of the interface since
  14450. // it will now change.
  14451. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  14452. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  14453. switch (DC->getKind()) {
  14454. default: break;
  14455. case Decl::ObjCCategory:
  14456. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  14457. break;
  14458. case Decl::ObjCImplementation:
  14459. Context.
  14460. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  14461. break;
  14462. }
  14463. }
  14464. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  14465. CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
  14466. // Start counting up the number of named members; make sure to include
  14467. // members of anonymous structs and unions in the total.
  14468. unsigned NumNamedMembers = 0;
  14469. if (Record) {
  14470. for (const auto *I : Record->decls()) {
  14471. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  14472. if (IFD->getDeclName())
  14473. ++NumNamedMembers;
  14474. }
  14475. }
  14476. // Verify that all the fields are okay.
  14477. SmallVector<FieldDecl*, 32> RecFields;
  14478. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  14479. i != end; ++i) {
  14480. FieldDecl *FD = cast<FieldDecl>(*i);
  14481. // Get the type for the field.
  14482. const Type *FDTy = FD->getType().getTypePtr();
  14483. if (!FD->isAnonymousStructOrUnion()) {
  14484. // Remember all fields written by the user.
  14485. RecFields.push_back(FD);
  14486. }
  14487. // If the field is already invalid for some reason, don't emit more
  14488. // diagnostics about it.
  14489. if (FD->isInvalidDecl()) {
  14490. EnclosingDecl->setInvalidDecl();
  14491. continue;
  14492. }
  14493. // C99 6.7.2.1p2:
  14494. // A structure or union shall not contain a member with
  14495. // incomplete or function type (hence, a structure shall not
  14496. // contain an instance of itself, but may contain a pointer to
  14497. // an instance of itself), except that the last member of a
  14498. // structure with more than one named member may have incomplete
  14499. // array type; such a structure (and any union containing,
  14500. // possibly recursively, a member that is such a structure)
  14501. // shall not be a member of a structure or an element of an
  14502. // array.
  14503. bool IsLastField = (i + 1 == Fields.end());
  14504. if (FDTy->isFunctionType()) {
  14505. // Field declared as a function.
  14506. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  14507. << FD->getDeclName();
  14508. FD->setInvalidDecl();
  14509. EnclosingDecl->setInvalidDecl();
  14510. continue;
  14511. } else if (FDTy->isIncompleteArrayType() &&
  14512. (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
  14513. if (Record) {
  14514. // Flexible array member.
  14515. // Microsoft and g++ is more permissive regarding flexible array.
  14516. // It will accept flexible array in union and also
  14517. // as the sole element of a struct/class.
  14518. unsigned DiagID = 0;
  14519. if (!Record->isUnion() && !IsLastField) {
  14520. Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
  14521. << FD->getDeclName() << FD->getType() << Record->getTagKind();
  14522. Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
  14523. FD->setInvalidDecl();
  14524. EnclosingDecl->setInvalidDecl();
  14525. continue;
  14526. } else if (Record->isUnion())
  14527. DiagID = getLangOpts().MicrosoftExt
  14528. ? diag::ext_flexible_array_union_ms
  14529. : getLangOpts().CPlusPlus
  14530. ? diag::ext_flexible_array_union_gnu
  14531. : diag::err_flexible_array_union;
  14532. else if (NumNamedMembers < 1)
  14533. DiagID = getLangOpts().MicrosoftExt
  14534. ? diag::ext_flexible_array_empty_aggregate_ms
  14535. : getLangOpts().CPlusPlus
  14536. ? diag::ext_flexible_array_empty_aggregate_gnu
  14537. : diag::err_flexible_array_empty_aggregate;
  14538. if (DiagID)
  14539. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  14540. << Record->getTagKind();
  14541. // While the layout of types that contain virtual bases is not specified
  14542. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  14543. // virtual bases after the derived members. This would make a flexible
  14544. // array member declared at the end of an object not adjacent to the end
  14545. // of the type.
  14546. if (CXXRecord && CXXRecord->getNumVBases() != 0)
  14547. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  14548. << FD->getDeclName() << Record->getTagKind();
  14549. if (!getLangOpts().C99)
  14550. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  14551. << FD->getDeclName() << Record->getTagKind();
  14552. // If the element type has a non-trivial destructor, we would not
  14553. // implicitly destroy the elements, so disallow it for now.
  14554. //
  14555. // FIXME: GCC allows this. We should probably either implicitly delete
  14556. // the destructor of the containing class, or just allow this.
  14557. QualType BaseElem = Context.getBaseElementType(FD->getType());
  14558. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  14559. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  14560. << FD->getDeclName() << FD->getType();
  14561. FD->setInvalidDecl();
  14562. EnclosingDecl->setInvalidDecl();
  14563. continue;
  14564. }
  14565. // Okay, we have a legal flexible array member at the end of the struct.
  14566. Record->setHasFlexibleArrayMember(true);
  14567. } else {
  14568. // In ObjCContainerDecl ivars with incomplete array type are accepted,
  14569. // unless they are followed by another ivar. That check is done
  14570. // elsewhere, after synthesized ivars are known.
  14571. }
  14572. } else if (!FDTy->isDependentType() &&
  14573. RequireCompleteType(FD->getLocation(), FD->getType(),
  14574. diag::err_field_incomplete)) {
  14575. // Incomplete type
  14576. FD->setInvalidDecl();
  14577. EnclosingDecl->setInvalidDecl();
  14578. continue;
  14579. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  14580. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  14581. // A type which contains a flexible array member is considered to be a
  14582. // flexible array member.
  14583. Record->setHasFlexibleArrayMember(true);
  14584. if (!Record->isUnion()) {
  14585. // If this is a struct/class and this is not the last element, reject
  14586. // it. Note that GCC supports variable sized arrays in the middle of
  14587. // structures.
  14588. if (!IsLastField)
  14589. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  14590. << FD->getDeclName() << FD->getType();
  14591. else {
  14592. // We support flexible arrays at the end of structs in
  14593. // other structs as an extension.
  14594. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  14595. << FD->getDeclName();
  14596. }
  14597. }
  14598. }
  14599. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  14600. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  14601. diag::err_abstract_type_in_decl,
  14602. AbstractIvarType)) {
  14603. // Ivars can not have abstract class types
  14604. FD->setInvalidDecl();
  14605. }
  14606. if (Record && FDTTy->getDecl()->hasObjectMember())
  14607. Record->setHasObjectMember(true);
  14608. if (Record && FDTTy->getDecl()->hasVolatileMember())
  14609. Record->setHasVolatileMember(true);
  14610. } else if (FDTy->isObjCObjectType()) {
  14611. /// A field cannot be an Objective-c object
  14612. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  14613. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  14614. QualType T = Context.getObjCObjectPointerType(FD->getType());
  14615. FD->setType(T);
  14616. } else if (Record && Record->isUnion() &&
  14617. FD->getType().hasNonTrivialObjCLifetime() &&
  14618. getSourceManager().isInSystemHeader(FD->getLocation()) &&
  14619. !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
  14620. (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
  14621. !Context.hasDirectOwnershipQualifier(FD->getType()))) {
  14622. // For backward compatibility, fields of C unions declared in system
  14623. // headers that have non-trivial ObjC ownership qualifications are marked
  14624. // as unavailable unless the qualifier is explicit and __strong. This can
  14625. // break ABI compatibility between programs compiled with ARC and MRR, but
  14626. // is a better option than rejecting programs using those unions under
  14627. // ARC.
  14628. FD->addAttr(UnavailableAttr::CreateImplicit(
  14629. Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
  14630. FD->getLocation()));
  14631. } else if (getLangOpts().ObjC &&
  14632. getLangOpts().getGC() != LangOptions::NonGC &&
  14633. Record && !Record->hasObjectMember()) {
  14634. if (FD->getType()->isObjCObjectPointerType() ||
  14635. FD->getType().isObjCGCStrong())
  14636. Record->setHasObjectMember(true);
  14637. else if (Context.getAsArrayType(FD->getType())) {
  14638. QualType BaseType = Context.getBaseElementType(FD->getType());
  14639. if (BaseType->isRecordType() &&
  14640. BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
  14641. Record->setHasObjectMember(true);
  14642. else if (BaseType->isObjCObjectPointerType() ||
  14643. BaseType.isObjCGCStrong())
  14644. Record->setHasObjectMember(true);
  14645. }
  14646. }
  14647. if (Record && !getLangOpts().CPlusPlus &&
  14648. !shouldIgnoreForRecordTriviality(FD)) {
  14649. QualType FT = FD->getType();
  14650. if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
  14651. Record->setNonTrivialToPrimitiveDefaultInitialize(true);
  14652. if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  14653. Record->isUnion())
  14654. Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
  14655. }
  14656. QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
  14657. if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
  14658. Record->setNonTrivialToPrimitiveCopy(true);
  14659. if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
  14660. Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
  14661. }
  14662. if (FT.isDestructedType()) {
  14663. Record->setNonTrivialToPrimitiveDestroy(true);
  14664. Record->setParamDestroyedInCallee(true);
  14665. if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
  14666. Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
  14667. }
  14668. if (const auto *RT = FT->getAs<RecordType>()) {
  14669. if (RT->getDecl()->getArgPassingRestrictions() ==
  14670. RecordDecl::APK_CanNeverPassInRegs)
  14671. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14672. } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
  14673. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14674. }
  14675. if (Record && FD->getType().isVolatileQualified())
  14676. Record->setHasVolatileMember(true);
  14677. // Keep track of the number of named members.
  14678. if (FD->getIdentifier())
  14679. ++NumNamedMembers;
  14680. }
  14681. // Okay, we successfully defined 'Record'.
  14682. if (Record) {
  14683. bool Completed = false;
  14684. if (CXXRecord) {
  14685. if (!CXXRecord->isInvalidDecl()) {
  14686. // Set access bits correctly on the directly-declared conversions.
  14687. for (CXXRecordDecl::conversion_iterator
  14688. I = CXXRecord->conversion_begin(),
  14689. E = CXXRecord->conversion_end(); I != E; ++I)
  14690. I.setAccess((*I)->getAccess());
  14691. }
  14692. if (!CXXRecord->isDependentType()) {
  14693. // Add any implicitly-declared members to this class.
  14694. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  14695. if (!CXXRecord->isInvalidDecl()) {
  14696. // If we have virtual base classes, we may end up finding multiple
  14697. // final overriders for a given virtual function. Check for this
  14698. // problem now.
  14699. if (CXXRecord->getNumVBases()) {
  14700. CXXFinalOverriderMap FinalOverriders;
  14701. CXXRecord->getFinalOverriders(FinalOverriders);
  14702. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  14703. MEnd = FinalOverriders.end();
  14704. M != MEnd; ++M) {
  14705. for (OverridingMethods::iterator SO = M->second.begin(),
  14706. SOEnd = M->second.end();
  14707. SO != SOEnd; ++SO) {
  14708. assert(SO->second.size() > 0 &&
  14709. "Virtual function without overriding functions?");
  14710. if (SO->second.size() == 1)
  14711. continue;
  14712. // C++ [class.virtual]p2:
  14713. // In a derived class, if a virtual member function of a base
  14714. // class subobject has more than one final overrider the
  14715. // program is ill-formed.
  14716. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  14717. << (const NamedDecl *)M->first << Record;
  14718. Diag(M->first->getLocation(),
  14719. diag::note_overridden_virtual_function);
  14720. for (OverridingMethods::overriding_iterator
  14721. OM = SO->second.begin(),
  14722. OMEnd = SO->second.end();
  14723. OM != OMEnd; ++OM)
  14724. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  14725. << (const NamedDecl *)M->first << OM->Method->getParent();
  14726. Record->setInvalidDecl();
  14727. }
  14728. }
  14729. CXXRecord->completeDefinition(&FinalOverriders);
  14730. Completed = true;
  14731. }
  14732. }
  14733. }
  14734. }
  14735. if (!Completed)
  14736. Record->completeDefinition();
  14737. // Handle attributes before checking the layout.
  14738. ProcessDeclAttributeList(S, Record, Attrs);
  14739. // We may have deferred checking for a deleted destructor. Check now.
  14740. if (CXXRecord) {
  14741. auto *Dtor = CXXRecord->getDestructor();
  14742. if (Dtor && Dtor->isImplicit() &&
  14743. ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
  14744. CXXRecord->setImplicitDestructorIsDeleted();
  14745. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  14746. }
  14747. }
  14748. if (Record->hasAttrs()) {
  14749. CheckAlignasUnderalignment(Record);
  14750. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  14751. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  14752. IA->getRange(), IA->getBestCase(),
  14753. IA->getSemanticSpelling());
  14754. }
  14755. // Check if the structure/union declaration is a type that can have zero
  14756. // size in C. For C this is a language extension, for C++ it may cause
  14757. // compatibility problems.
  14758. bool CheckForZeroSize;
  14759. if (!getLangOpts().CPlusPlus) {
  14760. CheckForZeroSize = true;
  14761. } else {
  14762. // For C++ filter out types that cannot be referenced in C code.
  14763. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  14764. CheckForZeroSize =
  14765. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  14766. !CXXRecord->isDependentType() &&
  14767. CXXRecord->isCLike();
  14768. }
  14769. if (CheckForZeroSize) {
  14770. bool ZeroSize = true;
  14771. bool IsEmpty = true;
  14772. unsigned NonBitFields = 0;
  14773. for (RecordDecl::field_iterator I = Record->field_begin(),
  14774. E = Record->field_end();
  14775. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  14776. IsEmpty = false;
  14777. if (I->isUnnamedBitfield()) {
  14778. if (!I->isZeroLengthBitField(Context))
  14779. ZeroSize = false;
  14780. } else {
  14781. ++NonBitFields;
  14782. QualType FieldType = I->getType();
  14783. if (FieldType->isIncompleteType() ||
  14784. !Context.getTypeSizeInChars(FieldType).isZero())
  14785. ZeroSize = false;
  14786. }
  14787. }
  14788. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  14789. // allowed in C++, but warn if its declaration is inside
  14790. // extern "C" block.
  14791. if (ZeroSize) {
  14792. Diag(RecLoc, getLangOpts().CPlusPlus ?
  14793. diag::warn_zero_size_struct_union_in_extern_c :
  14794. diag::warn_zero_size_struct_union_compat)
  14795. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  14796. }
  14797. // Structs without named members are extension in C (C99 6.7.2.1p7),
  14798. // but are accepted by GCC.
  14799. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  14800. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  14801. diag::ext_no_named_members_in_struct_union)
  14802. << Record->isUnion();
  14803. }
  14804. }
  14805. } else {
  14806. ObjCIvarDecl **ClsFields =
  14807. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  14808. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  14809. ID->setEndOfDefinitionLoc(RBrac);
  14810. // Add ivar's to class's DeclContext.
  14811. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14812. ClsFields[i]->setLexicalDeclContext(ID);
  14813. ID->addDecl(ClsFields[i]);
  14814. }
  14815. // Must enforce the rule that ivars in the base classes may not be
  14816. // duplicates.
  14817. if (ID->getSuperClass())
  14818. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  14819. } else if (ObjCImplementationDecl *IMPDecl =
  14820. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14821. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  14822. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  14823. // Ivar declared in @implementation never belongs to the implementation.
  14824. // Only it is in implementation's lexical context.
  14825. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  14826. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  14827. IMPDecl->setIvarLBraceLoc(LBrac);
  14828. IMPDecl->setIvarRBraceLoc(RBrac);
  14829. } else if (ObjCCategoryDecl *CDecl =
  14830. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14831. // case of ivars in class extension; all other cases have been
  14832. // reported as errors elsewhere.
  14833. // FIXME. Class extension does not have a LocEnd field.
  14834. // CDecl->setLocEnd(RBrac);
  14835. // Add ivar's to class extension's DeclContext.
  14836. // Diagnose redeclaration of private ivars.
  14837. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  14838. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14839. if (IDecl) {
  14840. if (const ObjCIvarDecl *ClsIvar =
  14841. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14842. Diag(ClsFields[i]->getLocation(),
  14843. diag::err_duplicate_ivar_declaration);
  14844. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  14845. continue;
  14846. }
  14847. for (const auto *Ext : IDecl->known_extensions()) {
  14848. if (const ObjCIvarDecl *ClsExtIvar
  14849. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14850. Diag(ClsFields[i]->getLocation(),
  14851. diag::err_duplicate_ivar_declaration);
  14852. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  14853. continue;
  14854. }
  14855. }
  14856. }
  14857. ClsFields[i]->setLexicalDeclContext(CDecl);
  14858. CDecl->addDecl(ClsFields[i]);
  14859. }
  14860. CDecl->setIvarLBraceLoc(LBrac);
  14861. CDecl->setIvarRBraceLoc(RBrac);
  14862. }
  14863. }
  14864. }
  14865. /// Determine whether the given integral value is representable within
  14866. /// the given type T.
  14867. static bool isRepresentableIntegerValue(ASTContext &Context,
  14868. llvm::APSInt &Value,
  14869. QualType T) {
  14870. assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
  14871. "Integral type required!");
  14872. unsigned BitWidth = Context.getIntWidth(T);
  14873. if (Value.isUnsigned() || Value.isNonNegative()) {
  14874. if (T->isSignedIntegerOrEnumerationType())
  14875. --BitWidth;
  14876. return Value.getActiveBits() <= BitWidth;
  14877. }
  14878. return Value.getMinSignedBits() <= BitWidth;
  14879. }
  14880. // Given an integral type, return the next larger integral type
  14881. // (or a NULL type of no such type exists).
  14882. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  14883. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  14884. // enum checking below.
  14885. assert((T->isIntegralType(Context) ||
  14886. T->isEnumeralType()) && "Integral type required!");
  14887. const unsigned NumTypes = 4;
  14888. QualType SignedIntegralTypes[NumTypes] = {
  14889. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  14890. };
  14891. QualType UnsignedIntegralTypes[NumTypes] = {
  14892. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  14893. Context.UnsignedLongLongTy
  14894. };
  14895. unsigned BitWidth = Context.getTypeSize(T);
  14896. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  14897. : UnsignedIntegralTypes;
  14898. for (unsigned I = 0; I != NumTypes; ++I)
  14899. if (Context.getTypeSize(Types[I]) > BitWidth)
  14900. return Types[I];
  14901. return QualType();
  14902. }
  14903. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  14904. EnumConstantDecl *LastEnumConst,
  14905. SourceLocation IdLoc,
  14906. IdentifierInfo *Id,
  14907. Expr *Val) {
  14908. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  14909. llvm::APSInt EnumVal(IntWidth);
  14910. QualType EltTy;
  14911. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  14912. Val = nullptr;
  14913. if (Val)
  14914. Val = DefaultLvalueConversion(Val).get();
  14915. if (Val) {
  14916. if (Enum->isDependentType() || Val->isTypeDependent())
  14917. EltTy = Context.DependentTy;
  14918. else {
  14919. if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
  14920. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  14921. // constant-expression in the enumerator-definition shall be a converted
  14922. // constant expression of the underlying type.
  14923. EltTy = Enum->getIntegerType();
  14924. ExprResult Converted =
  14925. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  14926. CCEK_Enumerator);
  14927. if (Converted.isInvalid())
  14928. Val = nullptr;
  14929. else
  14930. Val = Converted.get();
  14931. } else if (!Val->isValueDependent() &&
  14932. !(Val = VerifyIntegerConstantExpression(Val,
  14933. &EnumVal).get())) {
  14934. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  14935. } else {
  14936. if (Enum->isComplete()) {
  14937. EltTy = Enum->getIntegerType();
  14938. // In Obj-C and Microsoft mode, require the enumeration value to be
  14939. // representable in the underlying type of the enumeration. In C++11,
  14940. // we perform a non-narrowing conversion as part of converted constant
  14941. // expression checking.
  14942. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14943. if (Context.getTargetInfo()
  14944. .getTriple()
  14945. .isWindowsMSVCEnvironment()) {
  14946. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  14947. } else {
  14948. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  14949. }
  14950. }
  14951. // Cast to the underlying type.
  14952. Val = ImpCastExprToType(Val, EltTy,
  14953. EltTy->isBooleanType() ? CK_IntegralToBoolean
  14954. : CK_IntegralCast)
  14955. .get();
  14956. } else if (getLangOpts().CPlusPlus) {
  14957. // C++11 [dcl.enum]p5:
  14958. // If the underlying type is not fixed, the type of each enumerator
  14959. // is the type of its initializing value:
  14960. // - If an initializer is specified for an enumerator, the
  14961. // initializing value has the same type as the expression.
  14962. EltTy = Val->getType();
  14963. } else {
  14964. // C99 6.7.2.2p2:
  14965. // The expression that defines the value of an enumeration constant
  14966. // shall be an integer constant expression that has a value
  14967. // representable as an int.
  14968. // Complain if the value is not representable in an int.
  14969. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  14970. Diag(IdLoc, diag::ext_enum_value_not_int)
  14971. << EnumVal.toString(10) << Val->getSourceRange()
  14972. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  14973. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  14974. // Force the type of the expression to 'int'.
  14975. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  14976. }
  14977. EltTy = Val->getType();
  14978. }
  14979. }
  14980. }
  14981. }
  14982. if (!Val) {
  14983. if (Enum->isDependentType())
  14984. EltTy = Context.DependentTy;
  14985. else if (!LastEnumConst) {
  14986. // C++0x [dcl.enum]p5:
  14987. // If the underlying type is not fixed, the type of each enumerator
  14988. // is the type of its initializing value:
  14989. // - If no initializer is specified for the first enumerator, the
  14990. // initializing value has an unspecified integral type.
  14991. //
  14992. // GCC uses 'int' for its unspecified integral type, as does
  14993. // C99 6.7.2.2p3.
  14994. if (Enum->isFixed()) {
  14995. EltTy = Enum->getIntegerType();
  14996. }
  14997. else {
  14998. EltTy = Context.IntTy;
  14999. }
  15000. } else {
  15001. // Assign the last value + 1.
  15002. EnumVal = LastEnumConst->getInitVal();
  15003. ++EnumVal;
  15004. EltTy = LastEnumConst->getType();
  15005. // Check for overflow on increment.
  15006. if (EnumVal < LastEnumConst->getInitVal()) {
  15007. // C++0x [dcl.enum]p5:
  15008. // If the underlying type is not fixed, the type of each enumerator
  15009. // is the type of its initializing value:
  15010. //
  15011. // - Otherwise the type of the initializing value is the same as
  15012. // the type of the initializing value of the preceding enumerator
  15013. // unless the incremented value is not representable in that type,
  15014. // in which case the type is an unspecified integral type
  15015. // sufficient to contain the incremented value. If no such type
  15016. // exists, the program is ill-formed.
  15017. QualType T = getNextLargerIntegralType(Context, EltTy);
  15018. if (T.isNull() || Enum->isFixed()) {
  15019. // There is no integral type larger enough to represent this
  15020. // value. Complain, then allow the value to wrap around.
  15021. EnumVal = LastEnumConst->getInitVal();
  15022. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  15023. ++EnumVal;
  15024. if (Enum->isFixed())
  15025. // When the underlying type is fixed, this is ill-formed.
  15026. Diag(IdLoc, diag::err_enumerator_wrapped)
  15027. << EnumVal.toString(10)
  15028. << EltTy;
  15029. else
  15030. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  15031. << EnumVal.toString(10);
  15032. } else {
  15033. EltTy = T;
  15034. }
  15035. // Retrieve the last enumerator's value, extent that type to the
  15036. // type that is supposed to be large enough to represent the incremented
  15037. // value, then increment.
  15038. EnumVal = LastEnumConst->getInitVal();
  15039. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  15040. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  15041. ++EnumVal;
  15042. // If we're not in C++, diagnose the overflow of enumerator values,
  15043. // which in C99 means that the enumerator value is not representable in
  15044. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  15045. // permits enumerator values that are representable in some larger
  15046. // integral type.
  15047. if (!getLangOpts().CPlusPlus && !T.isNull())
  15048. Diag(IdLoc, diag::warn_enum_value_overflow);
  15049. } else if (!getLangOpts().CPlusPlus &&
  15050. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  15051. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  15052. Diag(IdLoc, diag::ext_enum_value_not_int)
  15053. << EnumVal.toString(10) << 1;
  15054. }
  15055. }
  15056. }
  15057. if (!EltTy->isDependentType()) {
  15058. // Make the enumerator value match the signedness and size of the
  15059. // enumerator's type.
  15060. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  15061. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  15062. }
  15063. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  15064. Val, EnumVal);
  15065. }
  15066. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  15067. SourceLocation IILoc) {
  15068. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  15069. !getLangOpts().CPlusPlus)
  15070. return SkipBodyInfo();
  15071. // We have an anonymous enum definition. Look up the first enumerator to
  15072. // determine if we should merge the definition with an existing one and
  15073. // skip the body.
  15074. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  15075. forRedeclarationInCurContext());
  15076. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  15077. if (!PrevECD)
  15078. return SkipBodyInfo();
  15079. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  15080. NamedDecl *Hidden;
  15081. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  15082. SkipBodyInfo Skip;
  15083. Skip.Previous = Hidden;
  15084. return Skip;
  15085. }
  15086. return SkipBodyInfo();
  15087. }
  15088. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  15089. SourceLocation IdLoc, IdentifierInfo *Id,
  15090. const ParsedAttributesView &Attrs,
  15091. SourceLocation EqualLoc, Expr *Val) {
  15092. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  15093. EnumConstantDecl *LastEnumConst =
  15094. cast_or_null<EnumConstantDecl>(lastEnumConst);
  15095. // The scope passed in may not be a decl scope. Zip up the scope tree until
  15096. // we find one that is.
  15097. S = getNonFieldDeclScope(S);
  15098. // Verify that there isn't already something declared with this name in this
  15099. // scope.
  15100. LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
  15101. LookupName(R, S);
  15102. NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
  15103. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  15104. // Maybe we will complain about the shadowed template parameter.
  15105. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  15106. // Just pretend that we didn't see the previous declaration.
  15107. PrevDecl = nullptr;
  15108. }
  15109. // C++ [class.mem]p15:
  15110. // If T is the name of a class, then each of the following shall have a name
  15111. // different from T:
  15112. // - every enumerator of every member of class T that is an unscoped
  15113. // enumerated type
  15114. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  15115. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  15116. DeclarationNameInfo(Id, IdLoc));
  15117. EnumConstantDecl *New =
  15118. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  15119. if (!New)
  15120. return nullptr;
  15121. if (PrevDecl) {
  15122. if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
  15123. // Check for other kinds of shadowing not already handled.
  15124. CheckShadow(New, PrevDecl, R);
  15125. }
  15126. // When in C++, we may get a TagDecl with the same name; in this case the
  15127. // enum constant will 'hide' the tag.
  15128. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  15129. "Received TagDecl when not in C++!");
  15130. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  15131. if (isa<EnumConstantDecl>(PrevDecl))
  15132. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  15133. else
  15134. Diag(IdLoc, diag::err_redefinition) << Id;
  15135. notePreviousDefinition(PrevDecl, IdLoc);
  15136. return nullptr;
  15137. }
  15138. }
  15139. // Process attributes.
  15140. ProcessDeclAttributeList(S, New, Attrs);
  15141. AddPragmaAttributes(S, New);
  15142. // Register this decl in the current scope stack.
  15143. New->setAccess(TheEnumDecl->getAccess());
  15144. PushOnScopeChains(New, S);
  15145. ActOnDocumentableDecl(New);
  15146. return New;
  15147. }
  15148. // Returns true when the enum initial expression does not trigger the
  15149. // duplicate enum warning. A few common cases are exempted as follows:
  15150. // Element2 = Element1
  15151. // Element2 = Element1 + 1
  15152. // Element2 = Element1 - 1
  15153. // Where Element2 and Element1 are from the same enum.
  15154. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  15155. Expr *InitExpr = ECD->getInitExpr();
  15156. if (!InitExpr)
  15157. return true;
  15158. InitExpr = InitExpr->IgnoreImpCasts();
  15159. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  15160. if (!BO->isAdditiveOp())
  15161. return true;
  15162. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  15163. if (!IL)
  15164. return true;
  15165. if (IL->getValue() != 1)
  15166. return true;
  15167. InitExpr = BO->getLHS();
  15168. }
  15169. // This checks if the elements are from the same enum.
  15170. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  15171. if (!DRE)
  15172. return true;
  15173. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  15174. if (!EnumConstant)
  15175. return true;
  15176. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  15177. Enum)
  15178. return true;
  15179. return false;
  15180. }
  15181. // Emits a warning when an element is implicitly set a value that
  15182. // a previous element has already been set to.
  15183. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  15184. EnumDecl *Enum, QualType EnumType) {
  15185. // Avoid anonymous enums
  15186. if (!Enum->getIdentifier())
  15187. return;
  15188. // Only check for small enums.
  15189. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  15190. return;
  15191. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  15192. return;
  15193. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  15194. typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
  15195. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  15196. typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
  15197. // Use int64_t as a key to avoid needing special handling for DenseMap keys.
  15198. auto EnumConstantToKey = [](const EnumConstantDecl *D) {
  15199. llvm::APSInt Val = D->getInitVal();
  15200. return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
  15201. };
  15202. DuplicatesVector DupVector;
  15203. ValueToVectorMap EnumMap;
  15204. // Populate the EnumMap with all values represented by enum constants without
  15205. // an initializer.
  15206. for (auto *Element : Elements) {
  15207. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
  15208. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  15209. // this constant. Skip this enum since it may be ill-formed.
  15210. if (!ECD) {
  15211. return;
  15212. }
  15213. // Constants with initalizers are handled in the next loop.
  15214. if (ECD->getInitExpr())
  15215. continue;
  15216. // Duplicate values are handled in the next loop.
  15217. EnumMap.insert({EnumConstantToKey(ECD), ECD});
  15218. }
  15219. if (EnumMap.size() == 0)
  15220. return;
  15221. // Create vectors for any values that has duplicates.
  15222. for (auto *Element : Elements) {
  15223. // The last loop returned if any constant was null.
  15224. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
  15225. if (!ValidDuplicateEnum(ECD, Enum))
  15226. continue;
  15227. auto Iter = EnumMap.find(EnumConstantToKey(ECD));
  15228. if (Iter == EnumMap.end())
  15229. continue;
  15230. DeclOrVector& Entry = Iter->second;
  15231. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  15232. // Ensure constants are different.
  15233. if (D == ECD)
  15234. continue;
  15235. // Create new vector and push values onto it.
  15236. auto Vec = std::make_unique<ECDVector>();
  15237. Vec->push_back(D);
  15238. Vec->push_back(ECD);
  15239. // Update entry to point to the duplicates vector.
  15240. Entry = Vec.get();
  15241. // Store the vector somewhere we can consult later for quick emission of
  15242. // diagnostics.
  15243. DupVector.emplace_back(std::move(Vec));
  15244. continue;
  15245. }
  15246. ECDVector *Vec = Entry.get<ECDVector*>();
  15247. // Make sure constants are not added more than once.
  15248. if (*Vec->begin() == ECD)
  15249. continue;
  15250. Vec->push_back(ECD);
  15251. }
  15252. // Emit diagnostics.
  15253. for (const auto &Vec : DupVector) {
  15254. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  15255. // Emit warning for one enum constant.
  15256. auto *FirstECD = Vec->front();
  15257. S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
  15258. << FirstECD << FirstECD->getInitVal().toString(10)
  15259. << FirstECD->getSourceRange();
  15260. // Emit one note for each of the remaining enum constants with
  15261. // the same value.
  15262. for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
  15263. S.Diag(ECD->getLocation(), diag::note_duplicate_element)
  15264. << ECD << ECD->getInitVal().toString(10)
  15265. << ECD->getSourceRange();
  15266. }
  15267. }
  15268. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  15269. bool AllowMask) const {
  15270. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  15271. assert(ED->isCompleteDefinition() && "expected enum definition");
  15272. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  15273. llvm::APInt &FlagBits = R.first->second;
  15274. if (R.second) {
  15275. for (auto *E : ED->enumerators()) {
  15276. const auto &EVal = E->getInitVal();
  15277. // Only single-bit enumerators introduce new flag values.
  15278. if (EVal.isPowerOf2())
  15279. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  15280. }
  15281. }
  15282. // A value is in a flag enum if either its bits are a subset of the enum's
  15283. // flag bits (the first condition) or we are allowing masks and the same is
  15284. // true of its complement (the second condition). When masks are allowed, we
  15285. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  15286. //
  15287. // While it's true that any value could be used as a mask, the assumption is
  15288. // that a mask will have all of the insignificant bits set. Anything else is
  15289. // likely a logic error.
  15290. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  15291. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  15292. }
  15293. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  15294. Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
  15295. const ParsedAttributesView &Attrs) {
  15296. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  15297. QualType EnumType = Context.getTypeDeclType(Enum);
  15298. ProcessDeclAttributeList(S, Enum, Attrs);
  15299. if (Enum->isDependentType()) {
  15300. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  15301. EnumConstantDecl *ECD =
  15302. cast_or_null<EnumConstantDecl>(Elements[i]);
  15303. if (!ECD) continue;
  15304. ECD->setType(EnumType);
  15305. }
  15306. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  15307. return;
  15308. }
  15309. // TODO: If the result value doesn't fit in an int, it must be a long or long
  15310. // long value. ISO C does not support this, but GCC does as an extension,
  15311. // emit a warning.
  15312. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  15313. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  15314. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  15315. // Verify that all the values are okay, compute the size of the values, and
  15316. // reverse the list.
  15317. unsigned NumNegativeBits = 0;
  15318. unsigned NumPositiveBits = 0;
  15319. // Keep track of whether all elements have type int.
  15320. bool AllElementsInt = true;
  15321. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  15322. EnumConstantDecl *ECD =
  15323. cast_or_null<EnumConstantDecl>(Elements[i]);
  15324. if (!ECD) continue; // Already issued a diagnostic.
  15325. const llvm::APSInt &InitVal = ECD->getInitVal();
  15326. // Keep track of the size of positive and negative values.
  15327. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  15328. NumPositiveBits = std::max(NumPositiveBits,
  15329. (unsigned)InitVal.getActiveBits());
  15330. else
  15331. NumNegativeBits = std::max(NumNegativeBits,
  15332. (unsigned)InitVal.getMinSignedBits());
  15333. // Keep track of whether every enum element has type int (very common).
  15334. if (AllElementsInt)
  15335. AllElementsInt = ECD->getType() == Context.IntTy;
  15336. }
  15337. // Figure out the type that should be used for this enum.
  15338. QualType BestType;
  15339. unsigned BestWidth;
  15340. // C++0x N3000 [conv.prom]p3:
  15341. // An rvalue of an unscoped enumeration type whose underlying
  15342. // type is not fixed can be converted to an rvalue of the first
  15343. // of the following types that can represent all the values of
  15344. // the enumeration: int, unsigned int, long int, unsigned long
  15345. // int, long long int, or unsigned long long int.
  15346. // C99 6.4.4.3p2:
  15347. // An identifier declared as an enumeration constant has type int.
  15348. // The C99 rule is modified by a gcc extension
  15349. QualType BestPromotionType;
  15350. bool Packed = Enum->hasAttr<PackedAttr>();
  15351. // -fshort-enums is the equivalent to specifying the packed attribute on all
  15352. // enum definitions.
  15353. if (LangOpts.ShortEnums)
  15354. Packed = true;
  15355. // If the enum already has a type because it is fixed or dictated by the
  15356. // target, promote that type instead of analyzing the enumerators.
  15357. if (Enum->isComplete()) {
  15358. BestType = Enum->getIntegerType();
  15359. if (BestType->isPromotableIntegerType())
  15360. BestPromotionType = Context.getPromotedIntegerType(BestType);
  15361. else
  15362. BestPromotionType = BestType;
  15363. BestWidth = Context.getIntWidth(BestType);
  15364. }
  15365. else if (NumNegativeBits) {
  15366. // If there is a negative value, figure out the smallest integer type (of
  15367. // int/long/longlong) that fits.
  15368. // If it's packed, check also if it fits a char or a short.
  15369. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  15370. BestType = Context.SignedCharTy;
  15371. BestWidth = CharWidth;
  15372. } else if (Packed && NumNegativeBits <= ShortWidth &&
  15373. NumPositiveBits < ShortWidth) {
  15374. BestType = Context.ShortTy;
  15375. BestWidth = ShortWidth;
  15376. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  15377. BestType = Context.IntTy;
  15378. BestWidth = IntWidth;
  15379. } else {
  15380. BestWidth = Context.getTargetInfo().getLongWidth();
  15381. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  15382. BestType = Context.LongTy;
  15383. } else {
  15384. BestWidth = Context.getTargetInfo().getLongLongWidth();
  15385. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  15386. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  15387. BestType = Context.LongLongTy;
  15388. }
  15389. }
  15390. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  15391. } else {
  15392. // If there is no negative value, figure out the smallest type that fits
  15393. // all of the enumerator values.
  15394. // If it's packed, check also if it fits a char or a short.
  15395. if (Packed && NumPositiveBits <= CharWidth) {
  15396. BestType = Context.UnsignedCharTy;
  15397. BestPromotionType = Context.IntTy;
  15398. BestWidth = CharWidth;
  15399. } else if (Packed && NumPositiveBits <= ShortWidth) {
  15400. BestType = Context.UnsignedShortTy;
  15401. BestPromotionType = Context.IntTy;
  15402. BestWidth = ShortWidth;
  15403. } else if (NumPositiveBits <= IntWidth) {
  15404. BestType = Context.UnsignedIntTy;
  15405. BestWidth = IntWidth;
  15406. BestPromotionType
  15407. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15408. ? Context.UnsignedIntTy : Context.IntTy;
  15409. } else if (NumPositiveBits <=
  15410. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  15411. BestType = Context.UnsignedLongTy;
  15412. BestPromotionType
  15413. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15414. ? Context.UnsignedLongTy : Context.LongTy;
  15415. } else {
  15416. BestWidth = Context.getTargetInfo().getLongLongWidth();
  15417. assert(NumPositiveBits <= BestWidth &&
  15418. "How could an initializer get larger than ULL?");
  15419. BestType = Context.UnsignedLongLongTy;
  15420. BestPromotionType
  15421. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15422. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  15423. }
  15424. }
  15425. // Loop over all of the enumerator constants, changing their types to match
  15426. // the type of the enum if needed.
  15427. for (auto *D : Elements) {
  15428. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  15429. if (!ECD) continue; // Already issued a diagnostic.
  15430. // Standard C says the enumerators have int type, but we allow, as an
  15431. // extension, the enumerators to be larger than int size. If each
  15432. // enumerator value fits in an int, type it as an int, otherwise type it the
  15433. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  15434. // that X has type 'int', not 'unsigned'.
  15435. // Determine whether the value fits into an int.
  15436. llvm::APSInt InitVal = ECD->getInitVal();
  15437. // If it fits into an integer type, force it. Otherwise force it to match
  15438. // the enum decl type.
  15439. QualType NewTy;
  15440. unsigned NewWidth;
  15441. bool NewSign;
  15442. if (!getLangOpts().CPlusPlus &&
  15443. !Enum->isFixed() &&
  15444. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  15445. NewTy = Context.IntTy;
  15446. NewWidth = IntWidth;
  15447. NewSign = true;
  15448. } else if (ECD->getType() == BestType) {
  15449. // Already the right type!
  15450. if (getLangOpts().CPlusPlus)
  15451. // C++ [dcl.enum]p4: Following the closing brace of an
  15452. // enum-specifier, each enumerator has the type of its
  15453. // enumeration.
  15454. ECD->setType(EnumType);
  15455. continue;
  15456. } else {
  15457. NewTy = BestType;
  15458. NewWidth = BestWidth;
  15459. NewSign = BestType->isSignedIntegerOrEnumerationType();
  15460. }
  15461. // Adjust the APSInt value.
  15462. InitVal = InitVal.extOrTrunc(NewWidth);
  15463. InitVal.setIsSigned(NewSign);
  15464. ECD->setInitVal(InitVal);
  15465. // Adjust the Expr initializer and type.
  15466. if (ECD->getInitExpr() &&
  15467. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  15468. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  15469. CK_IntegralCast,
  15470. ECD->getInitExpr(),
  15471. /*base paths*/ nullptr,
  15472. VK_RValue));
  15473. if (getLangOpts().CPlusPlus)
  15474. // C++ [dcl.enum]p4: Following the closing brace of an
  15475. // enum-specifier, each enumerator has the type of its
  15476. // enumeration.
  15477. ECD->setType(EnumType);
  15478. else
  15479. ECD->setType(NewTy);
  15480. }
  15481. Enum->completeDefinition(BestType, BestPromotionType,
  15482. NumPositiveBits, NumNegativeBits);
  15483. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  15484. if (Enum->isClosedFlag()) {
  15485. for (Decl *D : Elements) {
  15486. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  15487. if (!ECD) continue; // Already issued a diagnostic.
  15488. llvm::APSInt InitVal = ECD->getInitVal();
  15489. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  15490. !IsValueInFlagEnum(Enum, InitVal, true))
  15491. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  15492. << ECD << Enum;
  15493. }
  15494. }
  15495. // Now that the enum type is defined, ensure it's not been underaligned.
  15496. if (Enum->hasAttrs())
  15497. CheckAlignasUnderalignment(Enum);
  15498. }
  15499. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  15500. SourceLocation StartLoc,
  15501. SourceLocation EndLoc) {
  15502. StringLiteral *AsmString = cast<StringLiteral>(expr);
  15503. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  15504. AsmString, StartLoc,
  15505. EndLoc);
  15506. CurContext->addDecl(New);
  15507. return New;
  15508. }
  15509. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  15510. IdentifierInfo* AliasName,
  15511. SourceLocation PragmaLoc,
  15512. SourceLocation NameLoc,
  15513. SourceLocation AliasNameLoc) {
  15514. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  15515. LookupOrdinaryName);
  15516. AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
  15517. AttributeCommonInfo::AS_Pragma);
  15518. AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
  15519. Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
  15520. // If a declaration that:
  15521. // 1) declares a function or a variable
  15522. // 2) has external linkage
  15523. // already exists, add a label attribute to it.
  15524. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15525. if (isDeclExternC(PrevDecl))
  15526. PrevDecl->addAttr(Attr);
  15527. else
  15528. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  15529. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  15530. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  15531. } else
  15532. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  15533. }
  15534. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  15535. SourceLocation PragmaLoc,
  15536. SourceLocation NameLoc) {
  15537. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  15538. if (PrevDecl) {
  15539. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
  15540. } else {
  15541. (void)WeakUndeclaredIdentifiers.insert(
  15542. std::pair<IdentifierInfo*,WeakInfo>
  15543. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  15544. }
  15545. }
  15546. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  15547. IdentifierInfo* AliasName,
  15548. SourceLocation PragmaLoc,
  15549. SourceLocation NameLoc,
  15550. SourceLocation AliasNameLoc) {
  15551. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  15552. LookupOrdinaryName);
  15553. WeakInfo W = WeakInfo(Name, NameLoc);
  15554. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15555. if (!PrevDecl->hasAttr<AliasAttr>())
  15556. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  15557. DeclApplyPragmaWeak(TUScope, ND, W);
  15558. } else {
  15559. (void)WeakUndeclaredIdentifiers.insert(
  15560. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  15561. }
  15562. }
  15563. Decl *Sema::getObjCDeclContext() const {
  15564. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  15565. }