SemaDecl.cpp 562 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601
  1. //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "TypeLocBuilder.h"
  15. #include "clang/AST/ASTConsumer.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/ASTLambda.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/CharUnits.h"
  20. #include "clang/AST/CommentDiagnostic.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/EvaluatedExprVisitor.h"
  25. #include "clang/AST/ExprCXX.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/Basic/Builtins.h"
  28. #include "clang/Basic/PartialDiagnostic.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  32. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  33. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  34. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  35. #include "clang/Parse/ParseDiagnostic.h"
  36. #include "clang/Sema/CXXFieldCollector.h"
  37. #include "clang/Sema/DeclSpec.h"
  38. #include "clang/Sema/DelayedDiagnostic.h"
  39. #include "clang/Sema/Initialization.h"
  40. #include "clang/Sema/Lookup.h"
  41. #include "clang/Sema/ParsedTemplate.h"
  42. #include "clang/Sema/Scope.h"
  43. #include "clang/Sema/ScopeInfo.h"
  44. #include "clang/Sema/Template.h"
  45. #include "llvm/ADT/SmallString.h"
  46. #include "llvm/ADT/Triple.h"
  47. #include <algorithm>
  48. #include <cstring>
  49. #include <functional>
  50. #include "clang/Sema/SemaHLSL.h" // HLSL Change
  51. using namespace clang;
  52. using namespace sema;
  53. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  54. if (OwnedType) {
  55. Decl *Group[2] = { OwnedType, Ptr };
  56. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  57. }
  58. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  59. }
  60. namespace {
  61. class TypeNameValidatorCCC : public CorrectionCandidateCallback {
  62. public:
  63. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
  64. bool AllowTemplates=false)
  65. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  66. AllowClassTemplates(AllowTemplates) {
  67. WantExpressionKeywords = false;
  68. WantCXXNamedCasts = false;
  69. WantRemainingKeywords = false;
  70. }
  71. bool ValidateCandidate(const TypoCorrection &candidate) override {
  72. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  73. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  74. bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
  75. return (IsType || AllowedTemplate) &&
  76. (AllowInvalidDecl || !ND->isInvalidDecl());
  77. }
  78. return !WantClassName && candidate.isKeyword();
  79. }
  80. private:
  81. bool AllowInvalidDecl;
  82. bool WantClassName;
  83. bool AllowClassTemplates;
  84. };
  85. }
  86. /// \brief Determine whether the token kind starts a simple-type-specifier.
  87. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  88. switch (Kind) {
  89. // FIXME: Take into account the current language when deciding whether a
  90. // token kind is a valid type specifier
  91. case tok::kw_short:
  92. case tok::kw_long:
  93. case tok::kw___int64:
  94. case tok::kw___int128:
  95. case tok::kw_signed:
  96. case tok::kw_unsigned:
  97. case tok::kw_void:
  98. case tok::kw_char:
  99. case tok::kw_int:
  100. case tok::kw_half:
  101. case tok::kw_float:
  102. case tok::kw_double:
  103. case tok::kw_wchar_t:
  104. case tok::kw_bool:
  105. case tok::kw___underlying_type:
  106. return true;
  107. case tok::annot_typename:
  108. case tok::kw_char16_t:
  109. case tok::kw_char32_t:
  110. case tok::kw_typeof:
  111. case tok::annot_decltype:
  112. case tok::kw_decltype:
  113. return getLangOpts().CPlusPlus;
  114. default:
  115. break;
  116. }
  117. return false;
  118. }
  119. namespace {
  120. enum class UnqualifiedTypeNameLookupResult {
  121. NotFound,
  122. FoundNonType,
  123. FoundType
  124. };
  125. } // namespace
  126. /// \brief Tries to perform unqualified lookup of the type decls in bases for
  127. /// dependent class.
  128. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  129. /// type decl, \a FoundType if only type decls are found.
  130. static UnqualifiedTypeNameLookupResult
  131. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  132. SourceLocation NameLoc,
  133. const CXXRecordDecl *RD) {
  134. if (!RD->hasDefinition())
  135. return UnqualifiedTypeNameLookupResult::NotFound;
  136. // Look for type decls in base classes.
  137. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  138. UnqualifiedTypeNameLookupResult::NotFound;
  139. for (const auto &Base : RD->bases()) {
  140. const CXXRecordDecl *BaseRD = nullptr;
  141. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  142. BaseRD = BaseTT->getAsCXXRecordDecl();
  143. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  144. // Look for type decls in dependent base classes that have known primary
  145. // templates.
  146. if (!TST || !TST->isDependentType())
  147. continue;
  148. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  149. if (!TD)
  150. continue;
  151. auto *BasePrimaryTemplate =
  152. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
  153. if (!BasePrimaryTemplate)
  154. continue;
  155. BaseRD = BasePrimaryTemplate;
  156. }
  157. if (BaseRD) {
  158. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  159. if (!isa<TypeDecl>(ND))
  160. return UnqualifiedTypeNameLookupResult::FoundNonType;
  161. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  162. }
  163. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  164. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  165. case UnqualifiedTypeNameLookupResult::FoundNonType:
  166. return UnqualifiedTypeNameLookupResult::FoundNonType;
  167. case UnqualifiedTypeNameLookupResult::FoundType:
  168. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  169. break;
  170. case UnqualifiedTypeNameLookupResult::NotFound:
  171. break;
  172. }
  173. }
  174. }
  175. }
  176. return FoundTypeDecl;
  177. }
  178. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  179. const IdentifierInfo &II,
  180. SourceLocation NameLoc) {
  181. // Lookup in the parent class template context, if any.
  182. const CXXRecordDecl *RD = nullptr;
  183. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  184. UnqualifiedTypeNameLookupResult::NotFound;
  185. for (DeclContext *DC = S.CurContext;
  186. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  187. DC = DC->getParent()) {
  188. // Look for type decls in dependent base classes that have known primary
  189. // templates.
  190. RD = dyn_cast<CXXRecordDecl>(DC);
  191. if (RD && RD->getDescribedClassTemplate())
  192. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  193. }
  194. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  195. return ParsedType();
  196. // We found some types in dependent base classes. Recover as if the user
  197. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  198. // lookup during template instantiation.
  199. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  200. ASTContext &Context = S.Context;
  201. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  202. cast<Type>(Context.getRecordType(RD)));
  203. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  204. CXXScopeSpec SS;
  205. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  206. TypeLocBuilder Builder;
  207. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  208. DepTL.setNameLoc(NameLoc);
  209. DepTL.setElaboratedKeywordLoc(SourceLocation());
  210. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  211. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  212. }
  213. /// \brief If the identifier refers to a type name within this scope,
  214. /// return the declaration of that type.
  215. ///
  216. /// This routine performs ordinary name lookup of the identifier II
  217. /// within the given scope, with optional C++ scope specifier SS, to
  218. /// determine whether the name refers to a type. If so, returns an
  219. /// opaque pointer (actually a QualType) corresponding to that
  220. /// type. Otherwise, returns NULL.
  221. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  222. Scope *S, CXXScopeSpec *SS,
  223. bool isClassName, bool HasTrailingDot,
  224. ParsedType ObjectTypePtr,
  225. bool IsCtorOrDtorName,
  226. bool WantNontrivialTypeSourceInfo,
  227. IdentifierInfo **CorrectedII) {
  228. // Determine where we will perform name lookup.
  229. DeclContext *LookupCtx = nullptr;
  230. if (ObjectTypePtr) {
  231. QualType ObjectType = ObjectTypePtr.get();
  232. if (ObjectType->isRecordType())
  233. LookupCtx = computeDeclContext(ObjectType);
  234. } else if (SS && SS->isNotEmpty()) {
  235. LookupCtx = computeDeclContext(*SS, false);
  236. if (!LookupCtx) {
  237. if (isDependentScopeSpecifier(*SS)) {
  238. // C++ [temp.res]p3:
  239. // A qualified-id that refers to a type and in which the
  240. // nested-name-specifier depends on a template-parameter (14.6.2)
  241. // shall be prefixed by the keyword typename to indicate that the
  242. // qualified-id denotes a type, forming an
  243. // elaborated-type-specifier (7.1.5.3).
  244. //
  245. // We therefore do not perform any name lookup if the result would
  246. // refer to a member of an unknown specialization.
  247. if (!isClassName && !IsCtorOrDtorName)
  248. return ParsedType();
  249. // We know from the grammar that this name refers to a type,
  250. // so build a dependent node to describe the type.
  251. if (WantNontrivialTypeSourceInfo)
  252. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  253. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  254. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  255. II, NameLoc);
  256. return ParsedType::make(T);
  257. }
  258. return ParsedType();
  259. }
  260. if (!LookupCtx->isDependentContext() &&
  261. RequireCompleteDeclContext(*SS, LookupCtx))
  262. return ParsedType();
  263. }
  264. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  265. // lookup for class-names.
  266. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  267. LookupOrdinaryName;
  268. LookupResult Result(*this, &II, NameLoc, Kind);
  269. if (LookupCtx) {
  270. // Perform "qualified" name lookup into the declaration context we
  271. // computed, which is either the type of the base of a member access
  272. // expression or the declaration context associated with a prior
  273. // nested-name-specifier.
  274. LookupQualifiedName(Result, LookupCtx);
  275. if (ObjectTypePtr && Result.empty()) {
  276. // C++ [basic.lookup.classref]p3:
  277. // If the unqualified-id is ~type-name, the type-name is looked up
  278. // in the context of the entire postfix-expression. If the type T of
  279. // the object expression is of a class type C, the type-name is also
  280. // looked up in the scope of class C. At least one of the lookups shall
  281. // find a name that refers to (possibly cv-qualified) T.
  282. LookupName(Result, S);
  283. }
  284. } else {
  285. // Perform unqualified name lookup.
  286. LookupName(Result, S);
  287. // For unqualified lookup in a class template in MSVC mode, look into
  288. // dependent base classes where the primary class template is known.
  289. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  290. if (ParsedType TypeInBase =
  291. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  292. return TypeInBase;
  293. }
  294. }
  295. NamedDecl *IIDecl = nullptr;
  296. switch (Result.getResultKind()) {
  297. case LookupResult::NotFound:
  298. case LookupResult::NotFoundInCurrentInstantiation:
  299. if (CorrectedII) {
  300. TypoCorrection Correction = CorrectTypo(
  301. Result.getLookupNameInfo(), Kind, S, SS,
  302. llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
  303. CTK_ErrorRecovery);
  304. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  305. TemplateTy Template;
  306. bool MemberOfUnknownSpecialization;
  307. UnqualifiedId TemplateName;
  308. TemplateName.setIdentifier(NewII, NameLoc);
  309. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  310. CXXScopeSpec NewSS, *NewSSPtr = SS;
  311. if (SS && NNS) {
  312. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  313. NewSSPtr = &NewSS;
  314. }
  315. if (Correction && (NNS || NewII != &II) &&
  316. // Ignore a correction to a template type as the to-be-corrected
  317. // identifier is not a template (typo correction for template names
  318. // is handled elsewhere).
  319. !(getLangOpts().CPlusPlus && NewSSPtr &&
  320. isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
  321. false, Template, MemberOfUnknownSpecialization))) {
  322. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  323. isClassName, HasTrailingDot, ObjectTypePtr,
  324. IsCtorOrDtorName,
  325. WantNontrivialTypeSourceInfo);
  326. if (Ty) {
  327. diagnoseTypo(Correction,
  328. PDiag(diag::err_unknown_type_or_class_name_suggest)
  329. << Result.getLookupName() << isClassName);
  330. if (SS && NNS)
  331. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  332. *CorrectedII = NewII;
  333. return Ty;
  334. }
  335. }
  336. }
  337. // If typo correction failed or was not performed, fall through
  338. case LookupResult::FoundOverloaded:
  339. case LookupResult::FoundUnresolvedValue:
  340. Result.suppressDiagnostics();
  341. return ParsedType();
  342. case LookupResult::Ambiguous:
  343. // Recover from type-hiding ambiguities by hiding the type. We'll
  344. // do the lookup again when looking for an object, and we can
  345. // diagnose the error then. If we don't do this, then the error
  346. // about hiding the type will be immediately followed by an error
  347. // that only makes sense if the identifier was treated like a type.
  348. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  349. Result.suppressDiagnostics();
  350. return ParsedType();
  351. }
  352. // Look to see if we have a type anywhere in the list of results.
  353. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  354. Res != ResEnd; ++Res) {
  355. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
  356. if (!IIDecl ||
  357. (*Res)->getLocation().getRawEncoding() <
  358. IIDecl->getLocation().getRawEncoding())
  359. IIDecl = *Res;
  360. }
  361. }
  362. if (!IIDecl) {
  363. // None of the entities we found is a type, so there is no way
  364. // to even assume that the result is a type. In this case, don't
  365. // complain about the ambiguity. The parser will either try to
  366. // perform this lookup again (e.g., as an object name), which
  367. // will produce the ambiguity, or will complain that it expected
  368. // a type name.
  369. Result.suppressDiagnostics();
  370. return ParsedType();
  371. }
  372. // We found a type within the ambiguous lookup; diagnose the
  373. // ambiguity and then return that type. This might be the right
  374. // answer, or it might not be, but it suppresses any attempt to
  375. // perform the name lookup again.
  376. break;
  377. case LookupResult::Found:
  378. IIDecl = Result.getFoundDecl();
  379. break;
  380. }
  381. assert(IIDecl && "Didn't find decl");
  382. QualType T;
  383. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  384. DiagnoseUseOfDecl(IIDecl, NameLoc);
  385. T = Context.getTypeDeclType(TD);
  386. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  387. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  388. // constructor or destructor name (in such a case, the scope specifier
  389. // will be attached to the enclosing Expr or Decl node).
  390. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
  391. if (WantNontrivialTypeSourceInfo) {
  392. // Construct a type with type-source information.
  393. TypeLocBuilder Builder;
  394. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  395. T = getElaboratedType(ETK_None, *SS, T);
  396. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  397. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  398. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  399. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  400. } else {
  401. T = getElaboratedType(ETK_None, *SS, T);
  402. }
  403. }
  404. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  405. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  406. if (!HasTrailingDot)
  407. T = Context.getObjCInterfaceType(IDecl);
  408. }
  409. if (T.isNull()) {
  410. // If it's not plausibly a type, suppress diagnostics.
  411. Result.suppressDiagnostics();
  412. return ParsedType();
  413. }
  414. return ParsedType::make(T);
  415. }
  416. // Builds a fake NNS for the given decl context.
  417. static NestedNameSpecifier *
  418. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  419. for (;; DC = DC->getLookupParent()) {
  420. DC = DC->getPrimaryContext();
  421. auto *ND = dyn_cast<NamespaceDecl>(DC);
  422. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  423. return NestedNameSpecifier::Create(Context, nullptr, ND);
  424. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  425. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  426. RD->getTypeForDecl());
  427. else if (isa<TranslationUnitDecl>(DC))
  428. return NestedNameSpecifier::GlobalSpecifier(Context);
  429. }
  430. llvm_unreachable("something isn't in TU scope?");
  431. }
  432. ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
  433. SourceLocation NameLoc) {
  434. // Accepting an undeclared identifier as a default argument for a template
  435. // type parameter is a Microsoft extension.
  436. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  437. // Build a fake DependentNameType that will perform lookup into CurContext at
  438. // instantiation time. The name specifier isn't dependent, so template
  439. // instantiation won't transform it. It will retry the lookup, however.
  440. NestedNameSpecifier *NNS =
  441. synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  442. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  443. // Build type location information. We synthesized the qualifier, so we have
  444. // to build a fake NestedNameSpecifierLoc.
  445. NestedNameSpecifierLocBuilder NNSLocBuilder;
  446. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  447. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  448. TypeLocBuilder Builder;
  449. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  450. DepTL.setNameLoc(NameLoc);
  451. DepTL.setElaboratedKeywordLoc(SourceLocation());
  452. DepTL.setQualifierLoc(QualifierLoc);
  453. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  454. }
  455. /// isTagName() - This method is called *for error recovery purposes only*
  456. /// to determine if the specified name is a valid tag name ("struct foo"). If
  457. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  458. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  459. /// cases in C where the user forgot to specify the tag.
  460. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  461. // Do a tag name lookup in this scope.
  462. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  463. LookupName(R, S, false);
  464. R.suppressDiagnostics();
  465. if (R.getResultKind() == LookupResult::Found)
  466. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  467. switch (TD->getTagKind()) {
  468. case TTK_Struct: return DeclSpec::TST_struct;
  469. case TTK_Interface: return DeclSpec::TST_interface;
  470. case TTK_Union: return DeclSpec::TST_union;
  471. case TTK_Class: return DeclSpec::TST_class;
  472. case TTK_Enum: return DeclSpec::TST_enum;
  473. }
  474. }
  475. return DeclSpec::TST_unspecified;
  476. }
  477. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  478. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  479. /// then downgrade the missing typename error to a warning.
  480. /// This is needed for MSVC compatibility; Example:
  481. /// @code
  482. /// template<class T> class A {
  483. /// public:
  484. /// typedef int TYPE;
  485. /// };
  486. /// template<class T> class B : public A<T> {
  487. /// public:
  488. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  489. /// };
  490. /// @endcode
  491. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  492. if (CurContext->isRecord()) {
  493. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  494. return true;
  495. const Type *Ty = SS->getScopeRep()->getAsType();
  496. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  497. for (const auto &Base : RD->bases())
  498. if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  499. return true;
  500. return S->isFunctionPrototypeScope();
  501. }
  502. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  503. }
  504. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  505. SourceLocation IILoc,
  506. Scope *S,
  507. CXXScopeSpec *SS,
  508. ParsedType &SuggestedType,
  509. bool AllowClassTemplates) {
  510. // We don't have anything to suggest (yet).
  511. SuggestedType = ParsedType();
  512. // There may have been a typo in the name of the type. Look up typo
  513. // results, in case we have something that we can suggest.
  514. if (TypoCorrection Corrected =
  515. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  516. llvm::make_unique<TypeNameValidatorCCC>(
  517. false, false, AllowClassTemplates),
  518. CTK_ErrorRecovery)) {
  519. if (Corrected.isKeyword()) {
  520. // We corrected to a keyword.
  521. diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
  522. II = Corrected.getCorrectionAsIdentifierInfo();
  523. } else {
  524. // We found a similarly-named type or interface; suggest that.
  525. if (!SS || !SS->isSet()) {
  526. diagnoseTypo(Corrected,
  527. PDiag(diag::err_unknown_typename_suggest) << II);
  528. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  529. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  530. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  531. II->getName().equals(CorrectedStr);
  532. diagnoseTypo(Corrected,
  533. PDiag(diag::err_unknown_nested_typename_suggest)
  534. << II << DC << DroppedSpecifier << SS->getRange());
  535. } else {
  536. llvm_unreachable("could not have corrected a typo here");
  537. }
  538. CXXScopeSpec tmpSS;
  539. if (Corrected.getCorrectionSpecifier())
  540. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  541. SourceRange(IILoc));
  542. SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
  543. IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
  544. false, ParsedType(),
  545. /*IsCtorOrDtorName=*/false,
  546. /*NonTrivialTypeSourceInfo=*/true);
  547. }
  548. return;
  549. }
  550. if (getLangOpts().CPlusPlus) {
  551. // See if II is a class template that the user forgot to pass arguments to.
  552. UnqualifiedId Name;
  553. Name.setIdentifier(II, IILoc);
  554. CXXScopeSpec EmptySS;
  555. TemplateTy TemplateResult;
  556. bool MemberOfUnknownSpecialization;
  557. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  558. Name, ParsedType(), true, TemplateResult,
  559. MemberOfUnknownSpecialization) == TNK_Type_template) {
  560. TemplateName TplName = TemplateResult.get();
  561. Diag(IILoc, diag::err_template_missing_args) << TplName;
  562. if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
  563. if (TplDecl->getLocation().isValid()) { // HLSL Change - ellide location notes for built-ins
  564. Diag(TplDecl->getLocation(), diag::note_template_decl_here)
  565. << TplDecl->getTemplateParameters()->getSourceRange();
  566. }
  567. }
  568. return;
  569. }
  570. }
  571. // FIXME: Should we move the logic that tries to recover from a missing tag
  572. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  573. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  574. Diag(IILoc, diag::err_unknown_typename) << II;
  575. else if (DeclContext *DC = computeDeclContext(*SS, false))
  576. Diag(IILoc, diag::err_typename_nested_not_found)
  577. << II << DC << SS->getRange();
  578. else if (isDependentScopeSpecifier(*SS)) {
  579. unsigned DiagID = diag::err_typename_missing;
  580. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  581. DiagID = diag::ext_typename_missing;
  582. Diag(SS->getRange().getBegin(), DiagID)
  583. << SS->getScopeRep() << II->getName()
  584. << SourceRange(SS->getRange().getBegin(), IILoc)
  585. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  586. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  587. *SS, *II, IILoc).get();
  588. } else {
  589. assert(SS && SS->isInvalid() &&
  590. "Invalid scope specifier has already been diagnosed");
  591. }
  592. }
  593. /// \brief Determine whether the given result set contains either a type name
  594. /// or
  595. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  596. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  597. NextToken.is(tok::less);
  598. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  599. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  600. return true;
  601. if (CheckTemplate && isa<TemplateDecl>(*I))
  602. return true;
  603. }
  604. return false;
  605. }
  606. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  607. Scope *S, CXXScopeSpec &SS,
  608. IdentifierInfo *&Name,
  609. SourceLocation NameLoc) {
  610. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  611. SemaRef.LookupParsedName(R, S, &SS);
  612. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  613. StringRef FixItTagName;
  614. switch (Tag->getTagKind()) {
  615. case TTK_Class:
  616. FixItTagName = "class ";
  617. break;
  618. case TTK_Enum:
  619. FixItTagName = "enum ";
  620. break;
  621. case TTK_Struct:
  622. FixItTagName = "struct ";
  623. break;
  624. case TTK_Interface:
  625. FixItTagName = "__interface ";
  626. break;
  627. case TTK_Union:
  628. FixItTagName = "union ";
  629. break;
  630. }
  631. StringRef TagName = FixItTagName.drop_back();
  632. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  633. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  634. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  635. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  636. I != IEnd; ++I)
  637. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  638. << Name << TagName;
  639. // Replace lookup results with just the tag decl.
  640. Result.clear(Sema::LookupTagName);
  641. SemaRef.LookupParsedName(Result, S, &SS);
  642. return true;
  643. }
  644. return false;
  645. }
  646. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  647. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  648. QualType T, SourceLocation NameLoc) {
  649. ASTContext &Context = S.Context;
  650. TypeLocBuilder Builder;
  651. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  652. T = S.getElaboratedType(ETK_None, SS, T);
  653. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  654. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  655. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  656. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  657. }
  658. Sema::NameClassification
  659. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  660. SourceLocation NameLoc, const Token &NextToken,
  661. bool IsAddressOfOperand,
  662. std::unique_ptr<CorrectionCandidateCallback> CCC) {
  663. DeclarationNameInfo NameInfo(Name, NameLoc);
  664. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  665. if (NextToken.is(tok::coloncolon)) {
  666. BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
  667. QualType(), false, SS, nullptr, false);
  668. }
  669. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  670. LookupParsedName(Result, S, &SS, !CurMethod);
  671. // For unqualified lookup in a class template in MSVC mode, look into
  672. // dependent base classes where the primary class template is known.
  673. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  674. if (ParsedType TypeInBase =
  675. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  676. return TypeInBase;
  677. }
  678. // Perform lookup for Objective-C instance variables (including automatically
  679. // synthesized instance variables), if we're in an Objective-C method.
  680. // FIXME: This lookup really, really needs to be folded in to the normal
  681. // unqualified lookup mechanism.
  682. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  683. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  684. if (E.get() || E.isInvalid())
  685. return E;
  686. }
  687. bool SecondTry = false;
  688. bool IsFilteredTemplateName = false;
  689. Corrected:
  690. switch (Result.getResultKind()) {
  691. case LookupResult::NotFound:
  692. // If an unqualified-id is followed by a '(', then we have a function
  693. // call.
  694. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  695. // In C++, this is an ADL-only call.
  696. // FIXME: Reference?
  697. if (getLangOpts().CPlusPlus)
  698. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  699. // C90 6.3.2.2:
  700. // If the expression that precedes the parenthesized argument list in a
  701. // function call consists solely of an identifier, and if no
  702. // declaration is visible for this identifier, the identifier is
  703. // implicitly declared exactly as if, in the innermost block containing
  704. // the function call, the declaration
  705. //
  706. // extern int identifier ();
  707. //
  708. // appeared.
  709. //
  710. // We also allow this in C99 as an extension.
  711. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  712. Result.addDecl(D);
  713. Result.resolveKind();
  714. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  715. }
  716. }
  717. // In C, we first see whether there is a tag type by the same name, in
  718. // which case it's likely that the user just forget to write "enum",
  719. // "struct", or "union".
  720. if (!getLangOpts().CPlusPlus && !SecondTry &&
  721. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  722. break;
  723. }
  724. // Perform typo correction to determine if there is another name that is
  725. // close to this name.
  726. if (!SecondTry && CCC) {
  727. SecondTry = true;
  728. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  729. Result.getLookupKind(), S,
  730. &SS, std::move(CCC),
  731. CTK_ErrorRecovery)) {
  732. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  733. unsigned QualifiedDiag = diag::err_no_member_suggest;
  734. NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
  735. NamedDecl *UnderlyingFirstDecl
  736. = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
  737. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  738. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  739. UnqualifiedDiag = diag::err_no_template_suggest;
  740. QualifiedDiag = diag::err_no_member_template_suggest;
  741. } else if (UnderlyingFirstDecl &&
  742. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  743. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  744. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  745. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  746. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  747. }
  748. if (SS.isEmpty()) {
  749. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  750. } else {// FIXME: is this even reachable? Test it.
  751. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  752. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  753. Name->getName().equals(CorrectedStr);
  754. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  755. << Name << computeDeclContext(SS, false)
  756. << DroppedSpecifier << SS.getRange());
  757. }
  758. // Update the name, so that the caller has the new name.
  759. Name = Corrected.getCorrectionAsIdentifierInfo();
  760. // Typo correction corrected to a keyword.
  761. if (Corrected.isKeyword())
  762. return Name;
  763. // Also update the LookupResult...
  764. // FIXME: This should probably go away at some point
  765. Result.clear();
  766. Result.setLookupName(Corrected.getCorrection());
  767. if (FirstDecl)
  768. Result.addDecl(FirstDecl);
  769. // If we found an Objective-C instance variable, let
  770. // LookupInObjCMethod build the appropriate expression to
  771. // reference the ivar.
  772. // FIXME: This is a gross hack.
  773. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  774. Result.clear();
  775. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  776. return E;
  777. }
  778. goto Corrected;
  779. }
  780. }
  781. // We failed to correct; just fall through and let the parser deal with it.
  782. Result.suppressDiagnostics();
  783. return NameClassification::Unknown();
  784. case LookupResult::NotFoundInCurrentInstantiation: {
  785. // We performed name lookup into the current instantiation, and there were
  786. // dependent bases, so we treat this result the same way as any other
  787. // dependent nested-name-specifier.
  788. // C++ [temp.res]p2:
  789. // A name used in a template declaration or definition and that is
  790. // dependent on a template-parameter is assumed not to name a type
  791. // unless the applicable name lookup finds a type name or the name is
  792. // qualified by the keyword typename.
  793. //
  794. // FIXME: If the next token is '<', we might want to ask the parser to
  795. // perform some heroics to see if we actually have a
  796. // template-argument-list, which would indicate a missing 'template'
  797. // keyword here.
  798. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  799. NameInfo, IsAddressOfOperand,
  800. /*TemplateArgs=*/nullptr);
  801. }
  802. case LookupResult::Found:
  803. case LookupResult::FoundOverloaded:
  804. case LookupResult::FoundUnresolvedValue:
  805. break;
  806. case LookupResult::Ambiguous:
  807. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  808. hasAnyAcceptableTemplateNames(Result)) {
  809. // C++ [temp.local]p3:
  810. // A lookup that finds an injected-class-name (10.2) can result in an
  811. // ambiguity in certain cases (for example, if it is found in more than
  812. // one base class). If all of the injected-class-names that are found
  813. // refer to specializations of the same class template, and if the name
  814. // is followed by a template-argument-list, the reference refers to the
  815. // class template itself and not a specialization thereof, and is not
  816. // ambiguous.
  817. //
  818. // This filtering can make an ambiguous result into an unambiguous one,
  819. // so try again after filtering out template names.
  820. FilterAcceptableTemplateNames(Result);
  821. if (!Result.isAmbiguous()) {
  822. IsFilteredTemplateName = true;
  823. break;
  824. }
  825. }
  826. // Diagnose the ambiguity and return an error.
  827. return NameClassification::Error();
  828. }
  829. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  830. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  831. // C++ [temp.names]p3:
  832. // After name lookup (3.4) finds that a name is a template-name or that
  833. // an operator-function-id or a literal- operator-id refers to a set of
  834. // overloaded functions any member of which is a function template if
  835. // this is followed by a <, the < is always taken as the delimiter of a
  836. // template-argument-list and never as the less-than operator.
  837. if (!IsFilteredTemplateName)
  838. FilterAcceptableTemplateNames(Result);
  839. if (!Result.empty()) {
  840. bool IsFunctionTemplate;
  841. bool IsVarTemplate;
  842. TemplateName Template;
  843. if (Result.end() - Result.begin() > 1) {
  844. IsFunctionTemplate = true;
  845. Template = Context.getOverloadedTemplateName(Result.begin(),
  846. Result.end());
  847. } else {
  848. TemplateDecl *TD
  849. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  850. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  851. IsVarTemplate = isa<VarTemplateDecl>(TD);
  852. if (SS.isSet() && !SS.isInvalid())
  853. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  854. /*TemplateKeyword=*/false,
  855. TD);
  856. else
  857. Template = TemplateName(TD);
  858. }
  859. if (IsFunctionTemplate) {
  860. // Function templates always go through overload resolution, at which
  861. // point we'll perform the various checks (e.g., accessibility) we need
  862. // to based on which function we selected.
  863. Result.suppressDiagnostics();
  864. return NameClassification::FunctionTemplate(Template);
  865. }
  866. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  867. : NameClassification::TypeTemplate(Template);
  868. }
  869. }
  870. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  871. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  872. DiagnoseUseOfDecl(Type, NameLoc);
  873. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  874. QualType T = Context.getTypeDeclType(Type);
  875. if (SS.isNotEmpty())
  876. return buildNestedType(*this, SS, T, NameLoc);
  877. return ParsedType::make(T);
  878. }
  879. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  880. if (!Class) {
  881. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  882. if (ObjCCompatibleAliasDecl *Alias =
  883. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  884. Class = Alias->getClassInterface();
  885. }
  886. if (Class) {
  887. DiagnoseUseOfDecl(Class, NameLoc);
  888. if (NextToken.is(tok::period)) {
  889. // Interface. <something> is parsed as a property reference expression.
  890. // Just return "unknown" as a fall-through for now.
  891. Result.suppressDiagnostics();
  892. return NameClassification::Unknown();
  893. }
  894. QualType T = Context.getObjCInterfaceType(Class);
  895. return ParsedType::make(T);
  896. }
  897. // We can have a type template here if we're classifying a template argument.
  898. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
  899. return NameClassification::TypeTemplate(
  900. TemplateName(cast<TemplateDecl>(FirstDecl)));
  901. // Check for a tag type hidden by a non-type decl in a few cases where it
  902. // seems likely a type is wanted instead of the non-type that was found.
  903. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  904. if ((NextToken.is(tok::identifier) ||
  905. (NextIsOp &&
  906. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  907. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  908. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  909. DiagnoseUseOfDecl(Type, NameLoc);
  910. QualType T = Context.getTypeDeclType(Type);
  911. if (SS.isNotEmpty())
  912. return buildNestedType(*this, SS, T, NameLoc);
  913. return ParsedType::make(T);
  914. }
  915. if (FirstDecl->isCXXClassMember())
  916. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  917. nullptr);
  918. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  919. return BuildDeclarationNameExpr(SS, Result, ADL);
  920. }
  921. // Determines the context to return to after temporarily entering a
  922. // context. This depends in an unnecessarily complicated way on the
  923. // exact ordering of callbacks from the parser.
  924. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  925. // Functions defined inline within classes aren't parsed until we've
  926. // finished parsing the top-level class, so the top-level class is
  927. // the context we'll need to return to.
  928. // A Lambda call operator whose parent is a class must not be treated
  929. // as an inline member function. A Lambda can be used legally
  930. // either as an in-class member initializer or a default argument. These
  931. // are parsed once the class has been marked complete and so the containing
  932. // context would be the nested class (when the lambda is defined in one);
  933. // If the class is not complete, then the lambda is being used in an
  934. // ill-formed fashion (such as to specify the width of a bit-field, or
  935. // in an array-bound) - in which case we still want to return the
  936. // lexically containing DC (which could be a nested class).
  937. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  938. DC = DC->getLexicalParent();
  939. // A function not defined within a class will always return to its
  940. // lexical context.
  941. if (!isa<CXXRecordDecl>(DC))
  942. return DC;
  943. // A C++ inline method/friend is parsed *after* the topmost class
  944. // it was declared in is fully parsed ("complete"); the topmost
  945. // class is the context we need to return to.
  946. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  947. DC = RD;
  948. // Return the declaration context of the topmost class the inline method is
  949. // declared in.
  950. return DC;
  951. }
  952. return DC->getLexicalParent();
  953. }
  954. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  955. assert(getContainingDC(DC) == CurContext &&
  956. "The next DeclContext should be lexically contained in the current one.");
  957. CurContext = DC;
  958. S->setEntity(DC);
  959. }
  960. void Sema::PopDeclContext() {
  961. assert(CurContext && "DeclContext imbalance!");
  962. CurContext = getContainingDC(CurContext);
  963. assert(CurContext && "Popped translation unit!");
  964. }
  965. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  966. Decl *D) {
  967. // Unlike PushDeclContext, the context to which we return is not necessarily
  968. // the containing DC of TD, because the new context will be some pre-existing
  969. // TagDecl definition instead of a fresh one.
  970. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  971. CurContext = cast<TagDecl>(D)->getDefinition();
  972. assert(CurContext && "skipping definition of undefined tag");
  973. S->setEntity(CurContext);
  974. return Result;
  975. }
  976. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  977. CurContext = static_cast<decltype(CurContext)>(Context);
  978. }
  979. /// EnterDeclaratorContext - Used when we must lookup names in the context
  980. /// of a declarator's nested name specifier.
  981. ///
  982. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  983. // C++0x [basic.lookup.unqual]p13:
  984. // A name used in the definition of a static data member of class
  985. // X (after the qualified-id of the static member) is looked up as
  986. // if the name was used in a member function of X.
  987. // C++0x [basic.lookup.unqual]p14:
  988. // If a variable member of a namespace is defined outside of the
  989. // scope of its namespace then any name used in the definition of
  990. // the variable member (after the declarator-id) is looked up as
  991. // if the definition of the variable member occurred in its
  992. // namespace.
  993. // Both of these imply that we should push a scope whose context
  994. // is the semantic context of the declaration. We can't use
  995. // PushDeclContext here because that context is not necessarily
  996. // lexically contained in the current context. Fortunately,
  997. // the containing scope should have the appropriate information.
  998. assert(!S->getEntity() && "scope already has entity");
  999. #ifndef NDEBUG
  1000. Scope *Ancestor = S->getParent();
  1001. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1002. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1003. #endif
  1004. CurContext = DC;
  1005. S->setEntity(DC);
  1006. }
  1007. void Sema::ExitDeclaratorContext(Scope *S) {
  1008. assert(S->getEntity() == CurContext && "Context imbalance!");
  1009. // Switch back to the lexical context. The safety of this is
  1010. // enforced by an assert in EnterDeclaratorContext.
  1011. Scope *Ancestor = S->getParent();
  1012. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1013. CurContext = Ancestor->getEntity();
  1014. // We don't need to do anything with the scope, which is going to
  1015. // disappear.
  1016. }
  1017. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1018. // We assume that the caller has already called
  1019. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1020. FunctionDecl *FD = D->getAsFunction();
  1021. if (!FD)
  1022. return;
  1023. // Same implementation as PushDeclContext, but enters the context
  1024. // from the lexical parent, rather than the top-level class.
  1025. assert(CurContext == FD->getLexicalParent() &&
  1026. "The next DeclContext should be lexically contained in the current one.");
  1027. CurContext = FD;
  1028. S->setEntity(CurContext);
  1029. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1030. ParmVarDecl *Param = FD->getParamDecl(P);
  1031. // If the parameter has an identifier, then add it to the scope
  1032. if (Param->getIdentifier()) {
  1033. S->AddDecl(Param);
  1034. IdResolver.AddDecl(Param);
  1035. }
  1036. }
  1037. }
  1038. void Sema::ActOnExitFunctionContext() {
  1039. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1040. // rather than the top-level class.
  1041. assert(CurContext && "DeclContext imbalance!");
  1042. CurContext = CurContext->getLexicalParent();
  1043. assert(CurContext && "Popped translation unit!");
  1044. }
  1045. /// \brief Determine whether we allow overloading of the function
  1046. /// PrevDecl with another declaration.
  1047. ///
  1048. /// This routine determines whether overloading is possible, not
  1049. /// whether some new function is actually an overload. It will return
  1050. /// true in C++ (where we can always provide overloads) or, as an
  1051. /// extension, in C when the previous function is already an
  1052. /// overloaded function declaration or has the "overloadable"
  1053. /// attribute.
  1054. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1055. ASTContext &Context) {
  1056. if (Context.getLangOpts().CPlusPlus)
  1057. return true;
  1058. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1059. return true;
  1060. return (Previous.getResultKind() == LookupResult::Found
  1061. && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
  1062. }
  1063. /// Add this decl to the scope shadowed decl chains.
  1064. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1065. // Move up the scope chain until we find the nearest enclosing
  1066. // non-transparent context. The declaration will be introduced into this
  1067. // scope.
  1068. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1069. S = S->getParent();
  1070. // Add scoped declarations into their context, so that they can be
  1071. // found later. Declarations without a context won't be inserted
  1072. // into any context.
  1073. if (AddToContext)
  1074. CurContext->addDecl(D);
  1075. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1076. // are function-local declarations.
  1077. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1078. !D->getDeclContext()->getRedeclContext()->Equals(
  1079. D->getLexicalDeclContext()->getRedeclContext()) &&
  1080. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1081. return;
  1082. // Template instantiations should also not be pushed into scope.
  1083. if (isa<FunctionDecl>(D) &&
  1084. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1085. return;
  1086. // If this replaces anything in the current scope,
  1087. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1088. IEnd = IdResolver.end();
  1089. for (; I != IEnd; ++I) {
  1090. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1091. S->RemoveDecl(*I);
  1092. IdResolver.RemoveDecl(*I);
  1093. // Should only need to replace one decl.
  1094. break;
  1095. }
  1096. }
  1097. S->AddDecl(D);
  1098. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1099. // Implicitly-generated labels may end up getting generated in an order that
  1100. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1101. // the label at the appropriate place in the identifier chain.
  1102. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1103. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1104. if (IDC == CurContext) {
  1105. if (!S->isDeclScope(*I))
  1106. continue;
  1107. } else if (IDC->Encloses(CurContext))
  1108. break;
  1109. }
  1110. IdResolver.InsertDeclAfter(I, D);
  1111. } else {
  1112. IdResolver.AddDecl(D);
  1113. }
  1114. }
  1115. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  1116. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  1117. TUScope->AddDecl(D);
  1118. }
  1119. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1120. bool AllowInlineNamespace) {
  1121. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1122. }
  1123. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1124. DeclContext *TargetDC = DC->getPrimaryContext();
  1125. do {
  1126. if (DeclContext *ScopeDC = S->getEntity())
  1127. if (ScopeDC->getPrimaryContext() == TargetDC)
  1128. return S;
  1129. } while ((S = S->getParent()));
  1130. return nullptr;
  1131. }
  1132. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1133. DeclContext*,
  1134. ASTContext&);
  1135. /// Filters out lookup results that don't fall within the given scope
  1136. /// as determined by isDeclInScope.
  1137. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1138. bool ConsiderLinkage,
  1139. bool AllowInlineNamespace) {
  1140. LookupResult::Filter F = R.makeFilter();
  1141. while (F.hasNext()) {
  1142. NamedDecl *D = F.next();
  1143. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1144. continue;
  1145. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1146. continue;
  1147. F.erase();
  1148. }
  1149. F.done();
  1150. }
  1151. static bool isUsingDecl(NamedDecl *D) {
  1152. return isa<UsingShadowDecl>(D) ||
  1153. isa<UnresolvedUsingTypenameDecl>(D) ||
  1154. isa<UnresolvedUsingValueDecl>(D);
  1155. }
  1156. /// Removes using shadow declarations from the lookup results.
  1157. static void RemoveUsingDecls(LookupResult &R) {
  1158. LookupResult::Filter F = R.makeFilter();
  1159. while (F.hasNext())
  1160. if (isUsingDecl(F.next()))
  1161. F.erase();
  1162. F.done();
  1163. }
  1164. /// \brief Check for this common pattern:
  1165. /// @code
  1166. /// class S {
  1167. /// S(const S&); // DO NOT IMPLEMENT
  1168. /// void operator=(const S&); // DO NOT IMPLEMENT
  1169. /// };
  1170. /// @endcode
  1171. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1172. // FIXME: Should check for private access too but access is set after we get
  1173. // the decl here.
  1174. if (D->doesThisDeclarationHaveABody())
  1175. return false;
  1176. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1177. return CD->isCopyConstructor();
  1178. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  1179. return Method->isCopyAssignmentOperator();
  1180. return false;
  1181. }
  1182. // We need this to handle
  1183. //
  1184. // typedef struct {
  1185. // void *foo() { return 0; }
  1186. // } A;
  1187. //
  1188. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1189. // for example. If 'A', foo will have external linkage. If we have '*A',
  1190. // foo will have no linkage. Since we can't know until we get to the end
  1191. // of the typedef, this function finds out if D might have non-external linkage.
  1192. // Callers should verify at the end of the TU if it D has external linkage or
  1193. // not.
  1194. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1195. const DeclContext *DC = D->getDeclContext();
  1196. while (!DC->isTranslationUnit()) {
  1197. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1198. if (!RD->hasNameForLinkage())
  1199. return true;
  1200. }
  1201. DC = DC->getParent();
  1202. }
  1203. return !D->isExternallyVisible();
  1204. }
  1205. // FIXME: This needs to be refactored; some other isInMainFile users want
  1206. // these semantics.
  1207. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1208. if (S.TUKind != TU_Complete)
  1209. return false;
  1210. return S.SourceMgr.isInMainFile(Loc);
  1211. }
  1212. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1213. assert(D);
  1214. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1215. return false;
  1216. // Ignore all entities declared within templates, and out-of-line definitions
  1217. // of members of class templates.
  1218. if (D->getDeclContext()->isDependentContext() ||
  1219. D->getLexicalDeclContext()->isDependentContext())
  1220. return false;
  1221. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1222. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1223. return false;
  1224. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1225. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1226. return false;
  1227. } else {
  1228. // 'static inline' functions are defined in headers; don't warn.
  1229. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1230. return false;
  1231. }
  1232. if (FD->doesThisDeclarationHaveABody() &&
  1233. Context.DeclMustBeEmitted(FD))
  1234. return false;
  1235. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1236. // Constants and utility variables are defined in headers with internal
  1237. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1238. // like "inline".)
  1239. if (!isMainFileLoc(*this, VD->getLocation()))
  1240. return false;
  1241. if (Context.DeclMustBeEmitted(VD))
  1242. return false;
  1243. if (VD->isStaticDataMember() &&
  1244. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1245. return false;
  1246. } else {
  1247. return false;
  1248. }
  1249. // Only warn for unused decls internal to the translation unit.
  1250. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1251. // for inline functions defined in the main source file, for instance.
  1252. return mightHaveNonExternalLinkage(D);
  1253. }
  1254. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1255. if (!D)
  1256. return;
  1257. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1258. const FunctionDecl *First = FD->getFirstDecl();
  1259. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1260. return; // First should already be in the vector.
  1261. }
  1262. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1263. const VarDecl *First = VD->getFirstDecl();
  1264. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1265. return; // First should already be in the vector.
  1266. }
  1267. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1268. UnusedFileScopedDecls.push_back(D);
  1269. }
  1270. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1271. if (D->isInvalidDecl())
  1272. return false;
  1273. if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
  1274. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1275. return false;
  1276. if (isa<LabelDecl>(D))
  1277. return true;
  1278. // Except for labels, we only care about unused decls that are local to
  1279. // functions.
  1280. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1281. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1282. // For dependent types, the diagnostic is deferred.
  1283. WithinFunction =
  1284. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1285. if (!WithinFunction)
  1286. return false;
  1287. if (isa<TypedefNameDecl>(D))
  1288. return true;
  1289. // White-list anything that isn't a local variable.
  1290. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1291. return false;
  1292. // Types of valid local variables should be complete, so this should succeed.
  1293. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1294. // White-list anything with an __attribute__((unused)) type.
  1295. QualType Ty = VD->getType();
  1296. // Only look at the outermost level of typedef.
  1297. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1298. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1299. return false;
  1300. }
  1301. // If we failed to complete the type for some reason, or if the type is
  1302. // dependent, don't diagnose the variable.
  1303. if (Ty->isIncompleteType() || Ty->isDependentType())
  1304. return false;
  1305. if (const TagType *TT = Ty->getAs<TagType>()) {
  1306. const TagDecl *Tag = TT->getDecl();
  1307. if (Tag->hasAttr<UnusedAttr>())
  1308. return false;
  1309. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1310. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1311. return false;
  1312. if (const Expr *Init = VD->getInit()) {
  1313. if (const ExprWithCleanups *Cleanups =
  1314. dyn_cast<ExprWithCleanups>(Init))
  1315. Init = Cleanups->getSubExpr();
  1316. const CXXConstructExpr *Construct =
  1317. dyn_cast<CXXConstructExpr>(Init);
  1318. if (Construct && !Construct->isElidable()) {
  1319. CXXConstructorDecl *CD = Construct->getConstructor();
  1320. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
  1321. return false;
  1322. }
  1323. }
  1324. }
  1325. }
  1326. // TODO: __attribute__((unused)) templates?
  1327. }
  1328. return true;
  1329. }
  1330. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1331. FixItHint &Hint) {
  1332. if (isa<LabelDecl>(D)) {
  1333. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1334. tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
  1335. if (AfterColon.isInvalid())
  1336. return;
  1337. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1338. getCharRange(D->getLocStart(), AfterColon));
  1339. }
  1340. return;
  1341. }
  1342. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1343. if (D->getTypeForDecl()->isDependentType())
  1344. return;
  1345. for (auto *TmpD : D->decls()) {
  1346. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1347. DiagnoseUnusedDecl(T);
  1348. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1349. DiagnoseUnusedNestedTypedefs(R);
  1350. }
  1351. }
  1352. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1353. /// unless they are marked attr(unused).
  1354. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1355. if (!ShouldDiagnoseUnusedDecl(D))
  1356. return;
  1357. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1358. // typedefs can be referenced later on, so the diagnostics are emitted
  1359. // at end-of-translation-unit.
  1360. UnusedLocalTypedefNameCandidates.insert(TD);
  1361. return;
  1362. }
  1363. FixItHint Hint;
  1364. GenerateFixForUnusedDecl(D, Context, Hint);
  1365. unsigned DiagID;
  1366. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1367. DiagID = diag::warn_unused_exception_param;
  1368. else if (isa<LabelDecl>(D))
  1369. DiagID = diag::warn_unused_label;
  1370. else
  1371. DiagID = diag::warn_unused_variable;
  1372. Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
  1373. }
  1374. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1375. // Verify that we have no forward references left. If so, there was a goto
  1376. // or address of a label taken, but no definition of it. Label fwd
  1377. // definitions are indicated with a null substmt which is also not a resolved
  1378. // MS inline assembly label name.
  1379. bool Diagnose = false;
  1380. if (L->isMSAsmLabel())
  1381. Diagnose = !L->isResolvedMSAsmLabel();
  1382. else
  1383. Diagnose = L->getStmt() == nullptr;
  1384. if (Diagnose)
  1385. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1386. }
  1387. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1388. S->mergeNRVOIntoParent();
  1389. if (S->decl_empty()) return;
  1390. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1391. "Scope shouldn't contain decls!");
  1392. for (auto *TmpD : S->decls()) {
  1393. assert(TmpD && "This decl didn't get pushed??");
  1394. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1395. NamedDecl *D = cast<NamedDecl>(TmpD);
  1396. if (!D->getDeclName()) continue;
  1397. // Diagnose unused variables in this scope.
  1398. if (!S->hasUnrecoverableErrorOccurred()) {
  1399. DiagnoseUnusedDecl(D);
  1400. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1401. DiagnoseUnusedNestedTypedefs(RD);
  1402. }
  1403. // If this was a forward reference to a label, verify it was defined.
  1404. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1405. CheckPoppedLabel(LD, *this);
  1406. // Remove this name from our lexical scope.
  1407. IdResolver.RemoveDecl(D);
  1408. }
  1409. }
  1410. /// \brief Look for an Objective-C class in the translation unit.
  1411. ///
  1412. /// \param Id The name of the Objective-C class we're looking for. If
  1413. /// typo-correction fixes this name, the Id will be updated
  1414. /// to the fixed name.
  1415. ///
  1416. /// \param IdLoc The location of the name in the translation unit.
  1417. ///
  1418. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1419. /// if there is no class with the given name.
  1420. ///
  1421. /// \returns The declaration of the named Objective-C class, or NULL if the
  1422. /// class could not be found.
  1423. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1424. SourceLocation IdLoc,
  1425. bool DoTypoCorrection) {
  1426. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1427. // creation from this context.
  1428. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1429. if (!IDecl && DoTypoCorrection) {
  1430. // Perform typo correction at the given location, but only if we
  1431. // find an Objective-C class name.
  1432. if (TypoCorrection C = CorrectTypo(
  1433. DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
  1434. llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
  1435. CTK_ErrorRecovery)) {
  1436. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1437. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1438. Id = IDecl->getIdentifier();
  1439. }
  1440. }
  1441. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1442. // This routine must always return a class definition, if any.
  1443. if (Def && Def->getDefinition())
  1444. Def = Def->getDefinition();
  1445. return Def;
  1446. }
  1447. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1448. /// from S, where a non-field would be declared. This routine copes
  1449. /// with the difference between C and C++ scoping rules in structs and
  1450. /// unions. For example, the following code is well-formed in C but
  1451. /// ill-formed in C++:
  1452. /// @code
  1453. /// struct S6 {
  1454. /// enum { BAR } e;
  1455. /// };
  1456. ///
  1457. /// void test_S6() {
  1458. /// struct S6 a;
  1459. /// a.e = BAR;
  1460. /// }
  1461. /// @endcode
  1462. /// For the declaration of BAR, this routine will return a different
  1463. /// scope. The scope S will be the scope of the unnamed enumeration
  1464. /// within S6. In C++, this routine will return the scope associated
  1465. /// with S6, because the enumeration's scope is a transparent
  1466. /// context but structures can contain non-field names. In C, this
  1467. /// routine will return the translation unit scope, since the
  1468. /// enumeration's scope is a transparent context and structures cannot
  1469. /// contain non-field names.
  1470. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1471. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1472. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1473. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1474. S = S->getParent();
  1475. return S;
  1476. }
  1477. /// \brief Looks up the declaration of "struct objc_super" and
  1478. /// saves it for later use in building builtin declaration of
  1479. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1480. /// pre-existing declaration exists no action takes place.
  1481. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1482. IdentifierInfo *II) {
  1483. if (!II->isStr("objc_msgSendSuper"))
  1484. return;
  1485. ASTContext &Context = ThisSema.Context;
  1486. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1487. SourceLocation(), Sema::LookupTagName);
  1488. ThisSema.LookupName(Result, S);
  1489. if (Result.getResultKind() == LookupResult::Found)
  1490. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1491. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1492. }
  1493. static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
  1494. switch (Error) {
  1495. case ASTContext::GE_None:
  1496. return "";
  1497. case ASTContext::GE_Missing_stdio:
  1498. return "stdio.h";
  1499. case ASTContext::GE_Missing_setjmp:
  1500. return "setjmp.h";
  1501. case ASTContext::GE_Missing_ucontext:
  1502. return "ucontext.h";
  1503. }
  1504. llvm_unreachable("unhandled error kind");
  1505. }
  1506. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1507. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1508. /// if we're creating this built-in in anticipation of redeclaring the
  1509. /// built-in.
  1510. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1511. Scope *S, bool ForRedeclaration,
  1512. SourceLocation Loc) {
  1513. LookupPredefedObjCSuperType(*this, S, II);
  1514. ASTContext::GetBuiltinTypeError Error;
  1515. QualType R = Context.GetBuiltinType(ID, Error);
  1516. if (Error) {
  1517. if (ForRedeclaration)
  1518. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1519. << getHeaderName(Error)
  1520. << Context.BuiltinInfo.GetName(ID);
  1521. return nullptr;
  1522. }
  1523. if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
  1524. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1525. << Context.BuiltinInfo.GetName(ID)
  1526. << R;
  1527. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1528. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1529. Diag(Loc, diag::note_include_header_or_declare)
  1530. << Context.BuiltinInfo.getHeaderName(ID)
  1531. << Context.BuiltinInfo.GetName(ID);
  1532. }
  1533. DeclContext *Parent = Context.getTranslationUnitDecl();
  1534. if (getLangOpts().CPlusPlus) {
  1535. LinkageSpecDecl *CLinkageDecl =
  1536. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1537. LinkageSpecDecl::lang_c, false);
  1538. CLinkageDecl->setImplicit();
  1539. Parent->addDecl(CLinkageDecl);
  1540. Parent = CLinkageDecl;
  1541. }
  1542. FunctionDecl *New = FunctionDecl::Create(Context,
  1543. Parent,
  1544. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1545. SC_Extern,
  1546. false,
  1547. R->isFunctionProtoType());
  1548. New->setImplicit();
  1549. // Create Decl objects for each parameter, adding them to the
  1550. // FunctionDecl.
  1551. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1552. SmallVector<ParmVarDecl*, 16> Params;
  1553. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1554. ParmVarDecl *parm =
  1555. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1556. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1557. SC_None, nullptr);
  1558. parm->setScopeInfo(0, i);
  1559. Params.push_back(parm);
  1560. }
  1561. New->setParams(Params);
  1562. }
  1563. AddKnownFunctionAttributes(New);
  1564. RegisterLocallyScopedExternCDecl(New, S);
  1565. // TUScope is the translation-unit scope to insert this function into.
  1566. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1567. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1568. // entirely, but we're not there yet.
  1569. DeclContext *SavedContext = CurContext;
  1570. CurContext = Parent;
  1571. PushOnScopeChains(New, TUScope);
  1572. CurContext = SavedContext;
  1573. return New;
  1574. }
  1575. /// \brief Filter out any previous declarations that the given declaration
  1576. /// should not consider because they are not permitted to conflict, e.g.,
  1577. /// because they come from hidden sub-modules and do not refer to the same
  1578. /// entity.
  1579. static void filterNonConflictingPreviousDecls(Sema &S,
  1580. NamedDecl *decl,
  1581. LookupResult &previous){
  1582. // This is only interesting when modules are enabled.
  1583. if ((!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) ||
  1584. !S.getLangOpts().ModulesHideInternalLinkage)
  1585. return;
  1586. // Empty sets are uninteresting.
  1587. if (previous.empty())
  1588. return;
  1589. LookupResult::Filter filter = previous.makeFilter();
  1590. while (filter.hasNext()) {
  1591. NamedDecl *old = filter.next();
  1592. // Non-hidden declarations are never ignored.
  1593. if (S.isVisible(old))
  1594. continue;
  1595. if (!old->isExternallyVisible())
  1596. filter.erase();
  1597. }
  1598. filter.done();
  1599. }
  1600. /// Typedef declarations don't have linkage, but they still denote the same
  1601. /// entity if their types are the same.
  1602. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1603. /// isSameEntity.
  1604. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1605. TypedefNameDecl *Decl,
  1606. LookupResult &Previous) {
  1607. // This is only interesting when modules are enabled.
  1608. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1609. return;
  1610. // Empty sets are uninteresting.
  1611. if (Previous.empty())
  1612. return;
  1613. LookupResult::Filter Filter = Previous.makeFilter();
  1614. while (Filter.hasNext()) {
  1615. NamedDecl *Old = Filter.next();
  1616. // Non-hidden declarations are never ignored.
  1617. if (S.isVisible(Old))
  1618. continue;
  1619. // Declarations of the same entity are not ignored, even if they have
  1620. // different linkages.
  1621. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1622. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1623. Decl->getUnderlyingType()))
  1624. continue;
  1625. // If both declarations give a tag declaration a typedef name for linkage
  1626. // purposes, then they declare the same entity.
  1627. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1628. Decl->getAnonDeclWithTypedefName())
  1629. continue;
  1630. }
  1631. if (!Old->isExternallyVisible())
  1632. Filter.erase();
  1633. }
  1634. Filter.done();
  1635. }
  1636. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1637. QualType OldType;
  1638. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1639. OldType = OldTypedef->getUnderlyingType();
  1640. else
  1641. OldType = Context.getTypeDeclType(Old);
  1642. QualType NewType = New->getUnderlyingType();
  1643. if (NewType->isVariablyModifiedType()) {
  1644. // Must not redefine a typedef with a variably-modified type.
  1645. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1646. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1647. << Kind << NewType;
  1648. if (Old->getLocation().isValid())
  1649. Diag(Old->getLocation(), diag::note_previous_definition);
  1650. New->setInvalidDecl();
  1651. return true;
  1652. }
  1653. if (OldType != NewType &&
  1654. !OldType->isDependentType() &&
  1655. !NewType->isDependentType() &&
  1656. !Context.hasSameType(OldType, NewType)) {
  1657. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1658. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1659. << Kind << NewType << OldType;
  1660. if (Old->getLocation().isValid())
  1661. Diag(Old->getLocation(), diag::note_previous_definition);
  1662. New->setInvalidDecl();
  1663. return true;
  1664. }
  1665. return false;
  1666. }
  1667. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1668. /// same name and scope as a previous declaration 'Old'. Figure out
  1669. /// how to resolve this situation, merging decls or emitting
  1670. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1671. ///
  1672. void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
  1673. // If the new decl is known invalid already, don't bother doing any
  1674. // merging checks.
  1675. if (New->isInvalidDecl()) return;
  1676. // Allow multiple definitions for ObjC built-in typedefs.
  1677. // FIXME: Verify the underlying types are equivalent!
  1678. if (getLangOpts().ObjC1) {
  1679. const IdentifierInfo *TypeID = New->getIdentifier();
  1680. switch (TypeID->getLength()) {
  1681. default: break;
  1682. case 2:
  1683. {
  1684. if (!TypeID->isStr("id"))
  1685. break;
  1686. QualType T = New->getUnderlyingType();
  1687. if (!T->isPointerType())
  1688. break;
  1689. if (!T->isVoidPointerType()) {
  1690. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1691. if (!PT->isStructureType())
  1692. break;
  1693. }
  1694. Context.setObjCIdRedefinitionType(T);
  1695. // Install the built-in type for 'id', ignoring the current definition.
  1696. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1697. return;
  1698. }
  1699. case 5:
  1700. if (!TypeID->isStr("Class"))
  1701. break;
  1702. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1703. // Install the built-in type for 'Class', ignoring the current definition.
  1704. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1705. return;
  1706. case 3:
  1707. if (!TypeID->isStr("SEL"))
  1708. break;
  1709. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1710. // Install the built-in type for 'SEL', ignoring the current definition.
  1711. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1712. return;
  1713. }
  1714. // Fall through - the typedef name was not a builtin type.
  1715. }
  1716. // Verify the old decl was also a type.
  1717. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1718. if (!Old) {
  1719. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1720. << New->getDeclName();
  1721. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1722. if (OldD->getLocation().isValid())
  1723. Diag(OldD->getLocation(), diag::note_previous_definition);
  1724. return New->setInvalidDecl();
  1725. }
  1726. // If the old declaration is invalid, just give up here.
  1727. if (Old->isInvalidDecl())
  1728. return New->setInvalidDecl();
  1729. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1730. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1731. auto *NewTag = New->getAnonDeclWithTypedefName();
  1732. NamedDecl *Hidden = nullptr;
  1733. if (getLangOpts().CPlusPlus && OldTag && NewTag &&
  1734. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1735. !hasVisibleDefinition(OldTag, &Hidden)) {
  1736. // There is a definition of this tag, but it is not visible. Use it
  1737. // instead of our tag.
  1738. New->setTypeForDecl(OldTD->getTypeForDecl());
  1739. if (OldTD->isModed())
  1740. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1741. OldTD->getUnderlyingType());
  1742. else
  1743. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1744. // Make the old tag definition visible.
  1745. makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
  1746. }
  1747. }
  1748. // If the typedef types are not identical, reject them in all languages and
  1749. // with any extensions enabled.
  1750. if (isIncompatibleTypedef(Old, New))
  1751. return;
  1752. // The types match. Link up the redeclaration chain and merge attributes if
  1753. // the old declaration was a typedef.
  1754. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1755. New->setPreviousDecl(Typedef);
  1756. mergeDeclAttributes(New, Old);
  1757. }
  1758. if (getLangOpts().MicrosoftExt)
  1759. return;
  1760. if (getLangOpts().CPlusPlus) {
  1761. // C++ [dcl.typedef]p2:
  1762. // In a given non-class scope, a typedef specifier can be used to
  1763. // redefine the name of any type declared in that scope to refer
  1764. // to the type to which it already refers.
  1765. if (!isa<CXXRecordDecl>(CurContext))
  1766. return;
  1767. // C++0x [dcl.typedef]p4:
  1768. // In a given class scope, a typedef specifier can be used to redefine
  1769. // any class-name declared in that scope that is not also a typedef-name
  1770. // to refer to the type to which it already refers.
  1771. //
  1772. // This wording came in via DR424, which was a correction to the
  1773. // wording in DR56, which accidentally banned code like:
  1774. //
  1775. // struct S {
  1776. // typedef struct A { } A;
  1777. // };
  1778. //
  1779. // in the C++03 standard. We implement the C++0x semantics, which
  1780. // allow the above but disallow
  1781. //
  1782. // struct S {
  1783. // typedef int I;
  1784. // typedef int I;
  1785. // };
  1786. //
  1787. // since that was the intent of DR56.
  1788. if (!isa<TypedefNameDecl>(Old))
  1789. return;
  1790. Diag(New->getLocation(), diag::err_redefinition)
  1791. << New->getDeclName();
  1792. Diag(Old->getLocation(), diag::note_previous_definition);
  1793. return New->setInvalidDecl();
  1794. }
  1795. // Modules always permit redefinition of typedefs, as does C11.
  1796. if (getLangOpts().Modules || getLangOpts().C11)
  1797. return;
  1798. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1799. // is normally mapped to an error, but can be controlled with
  1800. // -Wtypedef-redefinition. If either the original or the redefinition is
  1801. // in a system header, don't emit this for compatibility with GCC.
  1802. if (getDiagnostics().getSuppressSystemWarnings() &&
  1803. (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1804. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1805. return;
  1806. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  1807. << New->getDeclName();
  1808. Diag(Old->getLocation(), diag::note_previous_definition);
  1809. }
  1810. /// DeclhasAttr - returns true if decl Declaration already has the target
  1811. /// attribute.
  1812. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  1813. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  1814. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  1815. for (const auto *i : D->attrs())
  1816. if (i->getKind() == A->getKind()) {
  1817. if (Ann) {
  1818. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  1819. return true;
  1820. continue;
  1821. }
  1822. // FIXME: Don't hardcode this check
  1823. if (OA && isa<OwnershipAttr>(i))
  1824. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  1825. return true;
  1826. }
  1827. return false;
  1828. }
  1829. static bool isAttributeTargetADefinition(Decl *D) {
  1830. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  1831. return VD->isThisDeclarationADefinition();
  1832. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  1833. return TD->isCompleteDefinition() || TD->isBeingDefined();
  1834. return true;
  1835. }
  1836. /// Merge alignment attributes from \p Old to \p New, taking into account the
  1837. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  1838. ///
  1839. /// \return \c true if any attributes were added to \p New.
  1840. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  1841. // Look for alignas attributes on Old, and pick out whichever attribute
  1842. // specifies the strictest alignment requirement.
  1843. AlignedAttr *OldAlignasAttr = nullptr;
  1844. AlignedAttr *OldStrictestAlignAttr = nullptr;
  1845. unsigned OldAlign = 0;
  1846. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  1847. // FIXME: We have no way of representing inherited dependent alignments
  1848. // in a case like:
  1849. // template<int A, int B> struct alignas(A) X;
  1850. // template<int A, int B> struct alignas(B) X {};
  1851. // For now, we just ignore any alignas attributes which are not on the
  1852. // definition in such a case.
  1853. if (I->isAlignmentDependent())
  1854. return false;
  1855. if (I->isAlignas())
  1856. OldAlignasAttr = I;
  1857. unsigned Align = I->getAlignment(S.Context);
  1858. if (Align > OldAlign) {
  1859. OldAlign = Align;
  1860. OldStrictestAlignAttr = I;
  1861. }
  1862. }
  1863. // Look for alignas attributes on New.
  1864. AlignedAttr *NewAlignasAttr = nullptr;
  1865. unsigned NewAlign = 0;
  1866. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  1867. if (I->isAlignmentDependent())
  1868. return false;
  1869. if (I->isAlignas())
  1870. NewAlignasAttr = I;
  1871. unsigned Align = I->getAlignment(S.Context);
  1872. if (Align > NewAlign)
  1873. NewAlign = Align;
  1874. }
  1875. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  1876. // Both declarations have 'alignas' attributes. We require them to match.
  1877. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  1878. // fall short. (If two declarations both have alignas, they must both match
  1879. // every definition, and so must match each other if there is a definition.)
  1880. // If either declaration only contains 'alignas(0)' specifiers, then it
  1881. // specifies the natural alignment for the type.
  1882. if (OldAlign == 0 || NewAlign == 0) {
  1883. QualType Ty;
  1884. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  1885. Ty = VD->getType();
  1886. else
  1887. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  1888. if (OldAlign == 0)
  1889. OldAlign = S.Context.getTypeAlign(Ty);
  1890. if (NewAlign == 0)
  1891. NewAlign = S.Context.getTypeAlign(Ty);
  1892. }
  1893. if (OldAlign != NewAlign) {
  1894. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  1895. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  1896. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  1897. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  1898. }
  1899. }
  1900. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  1901. // C++11 [dcl.align]p6:
  1902. // if any declaration of an entity has an alignment-specifier,
  1903. // every defining declaration of that entity shall specify an
  1904. // equivalent alignment.
  1905. // C11 6.7.5/7:
  1906. // If the definition of an object does not have an alignment
  1907. // specifier, any other declaration of that object shall also
  1908. // have no alignment specifier.
  1909. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  1910. << OldAlignasAttr;
  1911. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  1912. << OldAlignasAttr;
  1913. }
  1914. bool AnyAdded = false;
  1915. // Ensure we have an attribute representing the strictest alignment.
  1916. if (OldAlign > NewAlign) {
  1917. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  1918. Clone->setInherited(true);
  1919. New->addAttr(Clone);
  1920. AnyAdded = true;
  1921. }
  1922. // Ensure we have an alignas attribute if the old declaration had one.
  1923. if (OldAlignasAttr && !NewAlignasAttr &&
  1924. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  1925. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  1926. Clone->setInherited(true);
  1927. New->addAttr(Clone);
  1928. AnyAdded = true;
  1929. }
  1930. return AnyAdded;
  1931. }
  1932. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  1933. const InheritableAttr *Attr, bool Override) {
  1934. InheritableAttr *NewAttr = nullptr;
  1935. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  1936. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  1937. NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
  1938. AA->getIntroduced(), AA->getDeprecated(),
  1939. AA->getObsoleted(), AA->getUnavailable(),
  1940. AA->getMessage(), Override,
  1941. AttrSpellingListIndex);
  1942. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  1943. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  1944. AttrSpellingListIndex);
  1945. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  1946. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  1947. AttrSpellingListIndex);
  1948. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  1949. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  1950. AttrSpellingListIndex);
  1951. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  1952. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  1953. AttrSpellingListIndex);
  1954. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  1955. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  1956. FA->getFormatIdx(), FA->getFirstArg(),
  1957. AttrSpellingListIndex);
  1958. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  1959. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  1960. AttrSpellingListIndex);
  1961. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  1962. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  1963. AttrSpellingListIndex,
  1964. IA->getSemanticSpelling());
  1965. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  1966. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  1967. &S.Context.Idents.get(AA->getSpelling()),
  1968. AttrSpellingListIndex);
  1969. else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  1970. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  1971. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  1972. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  1973. else if (isa<AlignedAttr>(Attr))
  1974. // AlignedAttrs are handled separately, because we need to handle all
  1975. // such attributes on a declaration at the same time.
  1976. NewAttr = nullptr;
  1977. else if (isa<DeprecatedAttr>(Attr) && Override)
  1978. NewAttr = nullptr;
  1979. else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
  1980. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  1981. if (NewAttr) {
  1982. NewAttr->setInherited(true);
  1983. D->addAttr(NewAttr);
  1984. return true;
  1985. }
  1986. return false;
  1987. }
  1988. static const Decl *getDefinition(const Decl *D) {
  1989. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  1990. return TD->getDefinition();
  1991. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1992. const VarDecl *Def = VD->getDefinition();
  1993. if (Def)
  1994. return Def;
  1995. return VD->getActingDefinition();
  1996. }
  1997. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1998. const FunctionDecl* Def;
  1999. if (FD->isDefined(Def))
  2000. return Def;
  2001. }
  2002. return nullptr;
  2003. }
  2004. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2005. for (const auto *Attribute : D->attrs())
  2006. if (Attribute->getKind() == Kind)
  2007. return true;
  2008. return false;
  2009. }
  2010. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2011. /// there are no new attributes in this declaration.
  2012. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2013. if (!New->hasAttrs())
  2014. return;
  2015. const Decl *Def = getDefinition(Old);
  2016. if (!Def || Def == New)
  2017. return;
  2018. AttrVec &NewAttributes = New->getAttrs();
  2019. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2020. const Attr *NewAttribute = NewAttributes[I];
  2021. if (isa<AliasAttr>(NewAttribute)) {
  2022. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
  2023. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
  2024. else {
  2025. VarDecl *VD = cast<VarDecl>(New);
  2026. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2027. VarDecl::TentativeDefinition
  2028. ? diag::err_alias_after_tentative
  2029. : diag::err_redefinition;
  2030. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2031. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2032. VD->setInvalidDecl();
  2033. }
  2034. ++I;
  2035. continue;
  2036. }
  2037. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2038. // Tentative definitions are only interesting for the alias check above.
  2039. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2040. ++I;
  2041. continue;
  2042. }
  2043. }
  2044. if (hasAttribute(Def, NewAttribute->getKind())) {
  2045. ++I;
  2046. continue; // regular attr merging will take care of validating this.
  2047. }
  2048. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2049. // C's _Noreturn is allowed to be added to a function after it is defined.
  2050. ++I;
  2051. continue;
  2052. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2053. if (AA->isAlignas()) {
  2054. // C++11 [dcl.align]p6:
  2055. // if any declaration of an entity has an alignment-specifier,
  2056. // every defining declaration of that entity shall specify an
  2057. // equivalent alignment.
  2058. // C11 6.7.5/7:
  2059. // If the definition of an object does not have an alignment
  2060. // specifier, any other declaration of that object shall also
  2061. // have no alignment specifier.
  2062. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2063. << AA;
  2064. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2065. << AA;
  2066. NewAttributes.erase(NewAttributes.begin() + I);
  2067. --E;
  2068. continue;
  2069. }
  2070. }
  2071. S.Diag(NewAttribute->getLocation(),
  2072. diag::warn_attribute_precede_definition);
  2073. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2074. NewAttributes.erase(NewAttributes.begin() + I);
  2075. --E;
  2076. }
  2077. }
  2078. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2079. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2080. AvailabilityMergeKind AMK) {
  2081. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2082. UsedAttr *NewAttr = OldAttr->clone(Context);
  2083. NewAttr->setInherited(true);
  2084. New->addAttr(NewAttr);
  2085. }
  2086. if (!Old->hasAttrs() && !New->hasAttrs())
  2087. return;
  2088. // attributes declared post-definition are currently ignored
  2089. checkNewAttributesAfterDef(*this, New, Old);
  2090. if (!Old->hasAttrs())
  2091. return;
  2092. bool foundAny = New->hasAttrs();
  2093. // Ensure that any moving of objects within the allocated map is done before
  2094. // we process them.
  2095. if (!foundAny) New->setAttrs(AttrVec());
  2096. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2097. bool Override = false;
  2098. // Ignore deprecated/unavailable/availability attributes if requested.
  2099. if (isa<DeprecatedAttr>(I) ||
  2100. isa<UnavailableAttr>(I) ||
  2101. isa<AvailabilityAttr>(I)) {
  2102. switch (AMK) {
  2103. case AMK_None:
  2104. continue;
  2105. case AMK_Redeclaration:
  2106. break;
  2107. case AMK_Override:
  2108. Override = true;
  2109. break;
  2110. }
  2111. }
  2112. // Already handled.
  2113. if (isa<UsedAttr>(I))
  2114. continue;
  2115. if (mergeDeclAttribute(*this, New, I, Override))
  2116. foundAny = true;
  2117. }
  2118. if (mergeAlignedAttrs(*this, New, Old))
  2119. foundAny = true;
  2120. if (!foundAny) New->dropAttrs();
  2121. }
  2122. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2123. /// to the new one.
  2124. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2125. const ParmVarDecl *oldDecl,
  2126. Sema &S) {
  2127. // C++11 [dcl.attr.depend]p2:
  2128. // The first declaration of a function shall specify the
  2129. // carries_dependency attribute for its declarator-id if any declaration
  2130. // of the function specifies the carries_dependency attribute.
  2131. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2132. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2133. S.Diag(CDA->getLocation(),
  2134. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2135. // Find the first declaration of the parameter.
  2136. // FIXME: Should we build redeclaration chains for function parameters?
  2137. const FunctionDecl *FirstFD =
  2138. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2139. const ParmVarDecl *FirstVD =
  2140. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2141. S.Diag(FirstVD->getLocation(),
  2142. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2143. }
  2144. if (!oldDecl->hasAttrs())
  2145. return;
  2146. bool foundAny = newDecl->hasAttrs();
  2147. // Ensure that any moving of objects within the allocated map is
  2148. // done before we process them.
  2149. if (!foundAny) newDecl->setAttrs(AttrVec());
  2150. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2151. if (!DeclHasAttr(newDecl, I)) {
  2152. InheritableAttr *newAttr =
  2153. cast<InheritableParamAttr>(I->clone(S.Context));
  2154. newAttr->setInherited(true);
  2155. newDecl->addAttr(newAttr);
  2156. foundAny = true;
  2157. }
  2158. }
  2159. if (!foundAny) newDecl->dropAttrs();
  2160. }
  2161. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2162. const ParmVarDecl *OldParam,
  2163. Sema &S) {
  2164. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2165. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2166. if (*Oldnullability != *Newnullability) {
  2167. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2168. << DiagNullabilityKind(
  2169. *Newnullability,
  2170. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2171. != 0))
  2172. << DiagNullabilityKind(
  2173. *Oldnullability,
  2174. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2175. != 0));
  2176. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2177. }
  2178. } else {
  2179. QualType NewT = NewParam->getType();
  2180. NewT = S.Context.getAttributedType(
  2181. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2182. NewT, NewT);
  2183. NewParam->setType(NewT);
  2184. }
  2185. }
  2186. }
  2187. namespace {
  2188. /// Used in MergeFunctionDecl to keep track of function parameters in
  2189. /// C.
  2190. struct GNUCompatibleParamWarning {
  2191. ParmVarDecl *OldParm;
  2192. ParmVarDecl *NewParm;
  2193. QualType PromotedType;
  2194. };
  2195. }
  2196. /// getSpecialMember - get the special member enum for a method.
  2197. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2198. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2199. if (Ctor->isDefaultConstructor())
  2200. return Sema::CXXDefaultConstructor;
  2201. if (Ctor->isCopyConstructor())
  2202. return Sema::CXXCopyConstructor;
  2203. if (Ctor->isMoveConstructor())
  2204. return Sema::CXXMoveConstructor;
  2205. } else if (isa<CXXDestructorDecl>(MD)) {
  2206. return Sema::CXXDestructor;
  2207. } else if (MD->isCopyAssignmentOperator()) {
  2208. return Sema::CXXCopyAssignment;
  2209. } else if (MD->isMoveAssignmentOperator()) {
  2210. return Sema::CXXMoveAssignment;
  2211. }
  2212. return Sema::CXXInvalid;
  2213. }
  2214. // Determine whether the previous declaration was a definition, implicit
  2215. // declaration, or a declaration.
  2216. template <typename T>
  2217. static std::pair<diag::kind, SourceLocation>
  2218. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2219. diag::kind PrevDiag;
  2220. SourceLocation OldLocation = Old->getLocation();
  2221. if (Old->isThisDeclarationADefinition())
  2222. PrevDiag = diag::note_previous_definition;
  2223. else if (Old->isImplicit()) {
  2224. PrevDiag = diag::note_previous_implicit_declaration;
  2225. if (OldLocation.isInvalid())
  2226. OldLocation = New->getLocation();
  2227. } else
  2228. PrevDiag = diag::note_previous_declaration;
  2229. return std::make_pair(PrevDiag, OldLocation);
  2230. }
  2231. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2232. /// only extern inline functions can be redefined, and even then only in
  2233. /// GNU89 mode.
  2234. static bool canRedefineFunction(const FunctionDecl *FD,
  2235. const LangOptions& LangOpts) {
  2236. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2237. !LangOpts.CPlusPlus &&
  2238. FD->isInlineSpecified() &&
  2239. FD->getStorageClass() == SC_Extern);
  2240. }
  2241. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2242. const AttributedType *AT = T->getAs<AttributedType>();
  2243. while (AT && !AT->isCallingConv())
  2244. AT = AT->getModifiedType()->getAs<AttributedType>();
  2245. return AT;
  2246. }
  2247. template <typename T>
  2248. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2249. const DeclContext *DC = Old->getDeclContext();
  2250. if (DC->isRecord())
  2251. return false;
  2252. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2253. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2254. return true;
  2255. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2256. return true;
  2257. return false;
  2258. }
  2259. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2260. static bool isExternC(VarTemplateDecl *) { return false; }
  2261. /// \brief Check whether a redeclaration of an entity introduced by a
  2262. /// using-declaration is valid, given that we know it's not an overload
  2263. /// (nor a hidden tag declaration).
  2264. template<typename ExpectedDecl>
  2265. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2266. ExpectedDecl *New) {
  2267. // C++11 [basic.scope.declarative]p4:
  2268. // Given a set of declarations in a single declarative region, each of
  2269. // which specifies the same unqualified name,
  2270. // -- they shall all refer to the same entity, or all refer to functions
  2271. // and function templates; or
  2272. // -- exactly one declaration shall declare a class name or enumeration
  2273. // name that is not a typedef name and the other declarations shall all
  2274. // refer to the same variable or enumerator, or all refer to functions
  2275. // and function templates; in this case the class name or enumeration
  2276. // name is hidden (3.3.10).
  2277. // C++11 [namespace.udecl]p14:
  2278. // If a function declaration in namespace scope or block scope has the
  2279. // same name and the same parameter-type-list as a function introduced
  2280. // by a using-declaration, and the declarations do not declare the same
  2281. // function, the program is ill-formed.
  2282. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2283. if (Old &&
  2284. !Old->getDeclContext()->getRedeclContext()->Equals(
  2285. New->getDeclContext()->getRedeclContext()) &&
  2286. !(isExternC(Old) && isExternC(New)))
  2287. Old = nullptr;
  2288. if (!Old) {
  2289. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2290. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2291. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2292. return true;
  2293. }
  2294. return false;
  2295. }
  2296. /// MergeFunctionDecl - We just parsed a function 'New' from
  2297. /// declarator D which has the same name and scope as a previous
  2298. /// declaration 'Old'. Figure out how to resolve this situation,
  2299. /// merging decls or emitting diagnostics as appropriate.
  2300. ///
  2301. /// In C++, New and Old must be declarations that are not
  2302. /// overloaded. Use IsOverload to determine whether New and Old are
  2303. /// overloaded, and to select the Old declaration that New should be
  2304. /// merged with.
  2305. ///
  2306. /// Returns true if there was an error, false otherwise.
  2307. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2308. Scope *S, bool MergeTypeWithOld) {
  2309. // Verify the old decl was also a function.
  2310. FunctionDecl *Old = OldD->getAsFunction();
  2311. if (!Old) {
  2312. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2313. if (New->getFriendObjectKind()) {
  2314. Diag(New->getLocation(), diag::err_using_decl_friend);
  2315. Diag(Shadow->getTargetDecl()->getLocation(),
  2316. diag::note_using_decl_target);
  2317. Diag(Shadow->getUsingDecl()->getLocation(),
  2318. diag::note_using_decl) << 0;
  2319. return true;
  2320. }
  2321. // Check whether the two declarations might declare the same function.
  2322. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2323. return true;
  2324. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2325. } else {
  2326. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2327. << New->getDeclName();
  2328. Diag(OldD->getLocation(), diag::note_previous_definition);
  2329. return true;
  2330. }
  2331. }
  2332. // If the old declaration is invalid, just give up here.
  2333. if (Old->isInvalidDecl())
  2334. return true;
  2335. diag::kind PrevDiag;
  2336. SourceLocation OldLocation;
  2337. std::tie(PrevDiag, OldLocation) =
  2338. getNoteDiagForInvalidRedeclaration(Old, New);
  2339. // Don't complain about this if we're in GNU89 mode and the old function
  2340. // is an extern inline function.
  2341. // Don't complain about specializations. They are not supposed to have
  2342. // storage classes.
  2343. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2344. New->getStorageClass() == SC_Static &&
  2345. Old->hasExternalFormalLinkage() &&
  2346. !New->getTemplateSpecializationInfo() &&
  2347. !canRedefineFunction(Old, getLangOpts())) {
  2348. if (getLangOpts().MicrosoftExt) {
  2349. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2350. Diag(OldLocation, PrevDiag);
  2351. } else {
  2352. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2353. Diag(OldLocation, PrevDiag);
  2354. return true;
  2355. }
  2356. }
  2357. // If a function is first declared with a calling convention, but is later
  2358. // declared or defined without one, all following decls assume the calling
  2359. // convention of the first.
  2360. //
  2361. // It's OK if a function is first declared without a calling convention,
  2362. // but is later declared or defined with the default calling convention.
  2363. //
  2364. // To test if either decl has an explicit calling convention, we look for
  2365. // AttributedType sugar nodes on the type as written. If they are missing or
  2366. // were canonicalized away, we assume the calling convention was implicit.
  2367. //
  2368. // Note also that we DO NOT return at this point, because we still have
  2369. // other tests to run.
  2370. QualType OldQType = Context.getCanonicalType(Old->getType());
  2371. QualType NewQType = Context.getCanonicalType(New->getType());
  2372. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2373. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2374. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2375. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2376. bool RequiresAdjustment = false;
  2377. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2378. FunctionDecl *First = Old->getFirstDecl();
  2379. const FunctionType *FT =
  2380. First->getType().getCanonicalType()->castAs<FunctionType>();
  2381. FunctionType::ExtInfo FI = FT->getExtInfo();
  2382. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2383. if (!NewCCExplicit) {
  2384. // Inherit the CC from the previous declaration if it was specified
  2385. // there but not here.
  2386. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2387. RequiresAdjustment = true;
  2388. } else {
  2389. // Calling conventions aren't compatible, so complain.
  2390. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2391. Diag(New->getLocation(), diag::err_cconv_change)
  2392. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2393. << !FirstCCExplicit
  2394. << (!FirstCCExplicit ? "" :
  2395. FunctionType::getNameForCallConv(FI.getCC()));
  2396. // Put the note on the first decl, since it is the one that matters.
  2397. Diag(First->getLocation(), diag::note_previous_declaration);
  2398. return true;
  2399. }
  2400. }
  2401. // FIXME: diagnose the other way around?
  2402. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2403. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2404. RequiresAdjustment = true;
  2405. }
  2406. // Merge regparm attribute.
  2407. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2408. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2409. if (NewTypeInfo.getHasRegParm()) {
  2410. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2411. << NewType->getRegParmType()
  2412. << OldType->getRegParmType();
  2413. Diag(OldLocation, diag::note_previous_declaration);
  2414. return true;
  2415. }
  2416. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2417. RequiresAdjustment = true;
  2418. }
  2419. // Merge ns_returns_retained attribute.
  2420. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2421. if (NewTypeInfo.getProducesResult()) {
  2422. Diag(New->getLocation(), diag::err_returns_retained_mismatch);
  2423. Diag(OldLocation, diag::note_previous_declaration);
  2424. return true;
  2425. }
  2426. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2427. RequiresAdjustment = true;
  2428. }
  2429. if (RequiresAdjustment) {
  2430. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2431. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2432. New->setType(QualType(AdjustedType, 0));
  2433. NewQType = Context.getCanonicalType(New->getType());
  2434. NewType = cast<FunctionType>(NewQType);
  2435. }
  2436. // If this redeclaration makes the function inline, we may need to add it to
  2437. // UndefinedButUsed.
  2438. if (!Old->isInlined() && New->isInlined() &&
  2439. !New->hasAttr<GNUInlineAttr>() &&
  2440. !getLangOpts().GNUInline &&
  2441. Old->isUsed(false) &&
  2442. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2443. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2444. SourceLocation()));
  2445. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2446. // about it.
  2447. if (New->hasAttr<GNUInlineAttr>() &&
  2448. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2449. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2450. }
  2451. if (getLangOpts().CPlusPlus) {
  2452. // (C++98 13.1p2):
  2453. // Certain function declarations cannot be overloaded:
  2454. // -- Function declarations that differ only in the return type
  2455. // cannot be overloaded.
  2456. // Go back to the type source info to compare the declared return types,
  2457. // per C++1y [dcl.type.auto]p13:
  2458. // Redeclarations or specializations of a function or function template
  2459. // with a declared return type that uses a placeholder type shall also
  2460. // use that placeholder, not a deduced type.
  2461. QualType OldDeclaredReturnType =
  2462. (Old->getTypeSourceInfo()
  2463. ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2464. : OldType)->getReturnType();
  2465. QualType NewDeclaredReturnType =
  2466. (New->getTypeSourceInfo()
  2467. ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2468. : NewType)->getReturnType();
  2469. QualType ResQT;
  2470. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2471. !((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2472. New->isLocalExternDecl())) {
  2473. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2474. OldDeclaredReturnType->isObjCObjectPointerType())
  2475. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2476. if (ResQT.isNull()) {
  2477. if (New->isCXXClassMember() && New->isOutOfLine())
  2478. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  2479. << New << New->getReturnTypeSourceRange();
  2480. else
  2481. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  2482. << New->getReturnTypeSourceRange();
  2483. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  2484. << Old->getReturnTypeSourceRange();
  2485. return true;
  2486. }
  2487. else
  2488. NewQType = ResQT;
  2489. }
  2490. QualType OldReturnType = OldType->getReturnType();
  2491. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2492. if (OldReturnType != NewReturnType) {
  2493. // If this function has a deduced return type and has already been
  2494. // defined, copy the deduced value from the old declaration.
  2495. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2496. if (OldAT && OldAT->isDeduced()) {
  2497. New->setType(
  2498. SubstAutoType(New->getType(),
  2499. OldAT->isDependentType() ? Context.DependentTy
  2500. : OldAT->getDeducedType()));
  2501. NewQType = Context.getCanonicalType(
  2502. SubstAutoType(NewQType,
  2503. OldAT->isDependentType() ? Context.DependentTy
  2504. : OldAT->getDeducedType()));
  2505. }
  2506. }
  2507. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2508. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2509. if (OldMethod && NewMethod) {
  2510. // Preserve triviality.
  2511. NewMethod->setTrivial(OldMethod->isTrivial());
  2512. // MSVC allows explicit template specialization at class scope:
  2513. // 2 CXXMethodDecls referring to the same function will be injected.
  2514. // We don't want a redeclaration error.
  2515. bool IsClassScopeExplicitSpecialization =
  2516. OldMethod->isFunctionTemplateSpecialization() &&
  2517. NewMethod->isFunctionTemplateSpecialization();
  2518. bool isFriend = NewMethod->getFriendObjectKind();
  2519. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2520. !IsClassScopeExplicitSpecialization) {
  2521. // -- Member function declarations with the same name and the
  2522. // same parameter types cannot be overloaded if any of them
  2523. // is a static member function declaration.
  2524. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2525. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2526. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2527. return true;
  2528. }
  2529. // C++ [class.mem]p1:
  2530. // [...] A member shall not be declared twice in the
  2531. // member-specification, except that a nested class or member
  2532. // class template can be declared and then later defined.
  2533. if (ActiveTemplateInstantiations.empty()) {
  2534. unsigned NewDiag;
  2535. if (isa<CXXConstructorDecl>(OldMethod))
  2536. NewDiag = diag::err_constructor_redeclared;
  2537. else if (isa<CXXDestructorDecl>(NewMethod))
  2538. NewDiag = diag::err_destructor_redeclared;
  2539. else if (isa<CXXConversionDecl>(NewMethod))
  2540. NewDiag = diag::err_conv_function_redeclared;
  2541. else
  2542. NewDiag = diag::err_member_redeclared;
  2543. Diag(New->getLocation(), NewDiag);
  2544. } else {
  2545. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2546. << New << New->getType();
  2547. }
  2548. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2549. return true;
  2550. // Complain if this is an explicit declaration of a special
  2551. // member that was initially declared implicitly.
  2552. //
  2553. // As an exception, it's okay to befriend such methods in order
  2554. // to permit the implicit constructor/destructor/operator calls.
  2555. } else if (OldMethod->isImplicit()) {
  2556. if (isFriend) {
  2557. NewMethod->setImplicit();
  2558. } else {
  2559. Diag(NewMethod->getLocation(),
  2560. diag::err_definition_of_implicitly_declared_member)
  2561. << New << getSpecialMember(OldMethod);
  2562. return true;
  2563. }
  2564. } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
  2565. Diag(NewMethod->getLocation(),
  2566. diag::err_definition_of_explicitly_defaulted_member)
  2567. << getSpecialMember(OldMethod);
  2568. return true;
  2569. }
  2570. }
  2571. // C++11 [dcl.attr.noreturn]p1:
  2572. // The first declaration of a function shall specify the noreturn
  2573. // attribute if any declaration of that function specifies the noreturn
  2574. // attribute.
  2575. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  2576. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  2577. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  2578. Diag(Old->getFirstDecl()->getLocation(),
  2579. diag::note_noreturn_missing_first_decl);
  2580. }
  2581. // C++11 [dcl.attr.depend]p2:
  2582. // The first declaration of a function shall specify the
  2583. // carries_dependency attribute for its declarator-id if any declaration
  2584. // of the function specifies the carries_dependency attribute.
  2585. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  2586. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  2587. Diag(CDA->getLocation(),
  2588. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  2589. Diag(Old->getFirstDecl()->getLocation(),
  2590. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  2591. }
  2592. // (C++98 8.3.5p3):
  2593. // All declarations for a function shall agree exactly in both the
  2594. // return type and the parameter-type-list.
  2595. // We also want to respect all the extended bits except noreturn.
  2596. // noreturn should now match unless the old type info didn't have it.
  2597. QualType OldQTypeForComparison = OldQType;
  2598. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  2599. assert(OldQType == QualType(OldType, 0));
  2600. const FunctionType *OldTypeForComparison
  2601. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  2602. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  2603. assert(OldQTypeForComparison.isCanonical());
  2604. }
  2605. if (haveIncompatibleLanguageLinkages(Old, New)) {
  2606. // As a special case, retain the language linkage from previous
  2607. // declarations of a friend function as an extension.
  2608. //
  2609. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  2610. // and is useful because there's otherwise no way to specify language
  2611. // linkage within class scope.
  2612. //
  2613. // Check cautiously as the friend object kind isn't yet complete.
  2614. if (New->getFriendObjectKind() != Decl::FOK_None) {
  2615. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  2616. Diag(OldLocation, PrevDiag);
  2617. } else {
  2618. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  2619. Diag(OldLocation, PrevDiag);
  2620. return true;
  2621. }
  2622. }
  2623. if (OldQTypeForComparison == NewQType)
  2624. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2625. if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2626. New->isLocalExternDecl()) {
  2627. // It's OK if we couldn't merge types for a local function declaraton
  2628. // if either the old or new type is dependent. We'll merge the types
  2629. // when we instantiate the function.
  2630. return false;
  2631. }
  2632. // Fall through for conflicting redeclarations and redefinitions.
  2633. }
  2634. // C: Function types need to be compatible, not identical. This handles
  2635. // duplicate function decls like "void f(int); void f(enum X);" properly.
  2636. if (!getLangOpts().CPlusPlus &&
  2637. Context.typesAreCompatible(OldQType, NewQType)) {
  2638. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  2639. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  2640. const FunctionProtoType *OldProto = nullptr;
  2641. #if 1 // HLSL Change Starts - commenting this out rather than fixing for inout semantics - N/A for HLSL
  2642. assert(!(MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  2643. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) &&
  2644. "else fn with no prototype found");
  2645. (void)OldFuncType;
  2646. (void)NewFuncType;
  2647. (void)OldProto;
  2648. #else
  2649. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  2650. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  2651. // The old declaration provided a function prototype, but the
  2652. // new declaration does not. Merge in the prototype.
  2653. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  2654. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  2655. NewQType =
  2656. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  2657. OldProto->getExtProtoInfo());
  2658. New->setType(NewQType);
  2659. New->setHasInheritedPrototype();
  2660. // Synthesize parameters with the same types.
  2661. SmallVector<ParmVarDecl*, 16> Params;
  2662. for (const auto &ParamType : OldProto->param_types()) {
  2663. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  2664. SourceLocation(), nullptr,
  2665. ParamType, /*TInfo=*/nullptr,
  2666. SC_None, nullptr);
  2667. Param->setScopeInfo(0, Params.size());
  2668. Param->setImplicit();
  2669. Params.push_back(Param);
  2670. }
  2671. New->setParams(Params);
  2672. }
  2673. #endif // HLSL Change Ends
  2674. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2675. }
  2676. #if 0 // HLSL Change Starts - commenting this out rather than fixing for inout semantics - N/A for HLSL
  2677. // GNU C permits a K&R definition to follow a prototype declaration
  2678. // if the declared types of the parameters in the K&R definition
  2679. // match the types in the prototype declaration, even when the
  2680. // promoted types of the parameters from the K&R definition differ
  2681. // from the types in the prototype. GCC then keeps the types from
  2682. // the prototype.
  2683. //
  2684. // If a variadic prototype is followed by a non-variadic K&R definition,
  2685. // the K&R definition becomes variadic. This is sort of an edge case, but
  2686. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  2687. // C99 6.9.1p8.
  2688. if (!getLangOpts().CPlusPlus &&
  2689. Old->hasPrototype() && !New->hasPrototype() &&
  2690. New->getType()->getAs<FunctionProtoType>() &&
  2691. Old->getNumParams() == New->getNumParams()) {
  2692. SmallVector<QualType, 16> ArgTypes;
  2693. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  2694. const FunctionProtoType *OldProto
  2695. = Old->getType()->getAs<FunctionProtoType>();
  2696. const FunctionProtoType *NewProto
  2697. = New->getType()->getAs<FunctionProtoType>();
  2698. // Determine whether this is the GNU C extension.
  2699. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  2700. NewProto->getReturnType());
  2701. bool LooseCompatible = !MergedReturn.isNull();
  2702. for (unsigned Idx = 0, End = Old->getNumParams();
  2703. LooseCompatible && Idx != End; ++Idx) {
  2704. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  2705. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  2706. if (Context.typesAreCompatible(OldParm->getType(),
  2707. NewProto->getParamType(Idx))) {
  2708. ArgTypes.push_back(NewParm->getType());
  2709. } else if (Context.typesAreCompatible(OldParm->getType(),
  2710. NewParm->getType(),
  2711. /*CompareUnqualified=*/true)) {
  2712. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  2713. NewProto->getParamType(Idx) };
  2714. Warnings.push_back(Warn);
  2715. ArgTypes.push_back(NewParm->getType());
  2716. } else
  2717. LooseCompatible = false;
  2718. }
  2719. if (LooseCompatible) {
  2720. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  2721. Diag(Warnings[Warn].NewParm->getLocation(),
  2722. diag::ext_param_promoted_not_compatible_with_prototype)
  2723. << Warnings[Warn].PromotedType
  2724. << Warnings[Warn].OldParm->getType();
  2725. if (Warnings[Warn].OldParm->getLocation().isValid())
  2726. Diag(Warnings[Warn].OldParm->getLocation(),
  2727. diag::note_previous_declaration);
  2728. }
  2729. if (MergeTypeWithOld)
  2730. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  2731. OldProto->getExtProtoInfo()));
  2732. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2733. }
  2734. // Fall through to diagnose conflicting types.
  2735. }
  2736. #endif // HLSL Change Ends
  2737. // A function that has already been declared has been redeclared or
  2738. // defined with a different type; show an appropriate diagnostic.
  2739. // If the previous declaration was an implicitly-generated builtin
  2740. // declaration, then at the very least we should use a specialized note.
  2741. unsigned BuiltinID;
  2742. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  2743. // If it's actually a library-defined builtin function like 'malloc'
  2744. // or 'printf', just warn about the incompatible redeclaration.
  2745. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  2746. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  2747. Diag(OldLocation, diag::note_previous_builtin_declaration)
  2748. << Old << Old->getType();
  2749. // If this is a global redeclaration, just forget hereafter
  2750. // about the "builtin-ness" of the function.
  2751. //
  2752. // Doing this for local extern declarations is problematic. If
  2753. // the builtin declaration remains visible, a second invalid
  2754. // local declaration will produce a hard error; if it doesn't
  2755. // remain visible, a single bogus local redeclaration (which is
  2756. // actually only a warning) could break all the downstream code.
  2757. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  2758. New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
  2759. return false;
  2760. }
  2761. PrevDiag = diag::note_previous_builtin_declaration;
  2762. }
  2763. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  2764. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2765. return true;
  2766. }
  2767. /// \brief Completes the merge of two function declarations that are
  2768. /// known to be compatible.
  2769. ///
  2770. /// This routine handles the merging of attributes and other
  2771. /// properties of function declarations from the old declaration to
  2772. /// the new declaration, once we know that New is in fact a
  2773. /// redeclaration of Old.
  2774. ///
  2775. /// \returns false
  2776. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  2777. Scope *S, bool MergeTypeWithOld) {
  2778. // Merge the attributes
  2779. mergeDeclAttributes(New, Old);
  2780. // Merge "pure" flag.
  2781. if (Old->isPure())
  2782. New->setPure();
  2783. // Merge "used" flag.
  2784. if (Old->getMostRecentDecl()->isUsed(false))
  2785. New->setIsUsed();
  2786. // Merge attributes from the parameters. These can mismatch with K&R
  2787. // declarations.
  2788. if (New->getNumParams() == Old->getNumParams())
  2789. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  2790. ParmVarDecl *NewParam = New->getParamDecl(i);
  2791. ParmVarDecl *OldParam = Old->getParamDecl(i);
  2792. mergeParamDeclAttributes(NewParam, OldParam, *this);
  2793. mergeParamDeclTypes(NewParam, OldParam, *this);
  2794. }
  2795. if (getLangOpts().CPlusPlus)
  2796. return MergeCXXFunctionDecl(New, Old, S);
  2797. // Merge the function types so the we get the composite types for the return
  2798. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  2799. // was visible.
  2800. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  2801. if (!Merged.isNull() && MergeTypeWithOld)
  2802. New->setType(Merged);
  2803. return false;
  2804. }
  2805. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  2806. ObjCMethodDecl *oldMethod) {
  2807. // Merge the attributes, including deprecated/unavailable
  2808. AvailabilityMergeKind MergeKind =
  2809. isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  2810. : AMK_Override;
  2811. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  2812. // Merge attributes from the parameters.
  2813. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  2814. oe = oldMethod->param_end();
  2815. for (ObjCMethodDecl::param_iterator
  2816. ni = newMethod->param_begin(), ne = newMethod->param_end();
  2817. ni != ne && oi != oe; ++ni, ++oi)
  2818. mergeParamDeclAttributes(*ni, *oi, *this);
  2819. CheckObjCMethodOverride(newMethod, oldMethod);
  2820. }
  2821. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  2822. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  2823. /// emitting diagnostics as appropriate.
  2824. ///
  2825. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  2826. /// to here in AddInitializerToDecl. We can't check them before the initializer
  2827. /// is attached.
  2828. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  2829. bool MergeTypeWithOld, ShadowMergeState& MergeState) { // HLSL Change - add merge state
  2830. if (New->isInvalidDecl() || Old->isInvalidDecl())
  2831. return;
  2832. QualType MergedT;
  2833. if (getLangOpts().CPlusPlus) {
  2834. if (New->getType()->isUndeducedType()) {
  2835. // We don't know what the new type is until the initializer is attached.
  2836. return;
  2837. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  2838. // These could still be something that needs exception specs checked.
  2839. return MergeVarDeclExceptionSpecs(New, Old);
  2840. }
  2841. // C++ [basic.link]p10:
  2842. // [...] the types specified by all declarations referring to a given
  2843. // object or function shall be identical, except that declarations for an
  2844. // array object can specify array types that differ by the presence or
  2845. // absence of a major array bound (8.3.4).
  2846. else if (Old->getType()->isIncompleteArrayType() &&
  2847. New->getType()->isArrayType()) {
  2848. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  2849. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  2850. if (Context.hasSameType(OldArray->getElementType(),
  2851. NewArray->getElementType()))
  2852. MergedT = New->getType();
  2853. } else if (Old->getType()->isArrayType() &&
  2854. New->getType()->isIncompleteArrayType()) {
  2855. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  2856. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  2857. if (Context.hasSameType(OldArray->getElementType(),
  2858. NewArray->getElementType()))
  2859. MergedT = Old->getType();
  2860. } else if (New->getType()->isObjCObjectPointerType() &&
  2861. Old->getType()->isObjCObjectPointerType()) {
  2862. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  2863. Old->getType());
  2864. }
  2865. } else {
  2866. // C 6.2.7p2:
  2867. // All declarations that refer to the same object or function shall have
  2868. // compatible type.
  2869. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  2870. }
  2871. if (MergedT.isNull()) {
  2872. // It's OK if we couldn't merge types if either type is dependent, for a
  2873. // block-scope variable. In other cases (static data members of class
  2874. // templates, variable templates, ...), we require the types to be
  2875. // equivalent.
  2876. // FIXME: The C++ standard doesn't say anything about this.
  2877. if ((New->getType()->isDependentType() ||
  2878. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  2879. // If the old type was dependent, we can't merge with it, so the new type
  2880. // becomes dependent for now. We'll reproduce the original type when we
  2881. // instantiate the TypeSourceInfo for the variable.
  2882. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  2883. New->setType(Context.DependentTy);
  2884. return;
  2885. }
  2886. // FIXME: Even if this merging succeeds, some other non-visible declaration
  2887. // of this variable might have an incompatible type. For instance:
  2888. //
  2889. // extern int arr[];
  2890. // void f() { extern int arr[2]; }
  2891. // void g() { extern int arr[3]; }
  2892. //
  2893. // Neither C nor C++ requires a diagnostic for this, but we should still try
  2894. // to diagnose it.
  2895. // HLSL Change Starts
  2896. if (MergeState == ShadowMergeState_Disallowed) {
  2897. Diag(New->getLocation(), New->isThisDeclarationADefinition()
  2898. ? diag::err_redefinition_different_type
  2899. : diag::err_redeclaration_different_type)
  2900. << New->getDeclName() << New->getType() << Old->getType();
  2901. diag::kind PrevDiag;
  2902. SourceLocation OldLocation;
  2903. std::tie(PrevDiag, OldLocation) =
  2904. getNoteDiagForInvalidRedeclaration(Old, New);
  2905. Diag(OldLocation, PrevDiag);
  2906. return New->setInvalidDecl();
  2907. }
  2908. else if (MergeState == ShadowMergeState_Possible) {
  2909. Diag(New->getLocation(), diag::warn_hlsl_for_redefinition_different_type)
  2910. << New->getDeclName() << New->getType() << Old->getType();
  2911. Diag(Old->getLocation(), diag::note_previous_definition);
  2912. MergeState = ShadowMergeState_Effective;
  2913. MergeTypeWithOld = false;
  2914. }
  2915. // HLSL Change Ends
  2916. }
  2917. // Don't actually update the type on the new declaration if the old
  2918. // declaration was an extern declaration in a different scope.
  2919. if (MergeTypeWithOld)
  2920. New->setType(MergedT);
  2921. }
  2922. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  2923. LookupResult &Previous) {
  2924. // C11 6.2.7p4:
  2925. // For an identifier with internal or external linkage declared
  2926. // in a scope in which a prior declaration of that identifier is
  2927. // visible, if the prior declaration specifies internal or
  2928. // external linkage, the type of the identifier at the later
  2929. // declaration becomes the composite type.
  2930. //
  2931. // If the variable isn't visible, we do not merge with its type.
  2932. if (Previous.isShadowed())
  2933. return false;
  2934. if (S.getLangOpts().CPlusPlus) {
  2935. // C++11 [dcl.array]p3:
  2936. // If there is a preceding declaration of the entity in the same
  2937. // scope in which the bound was specified, an omitted array bound
  2938. // is taken to be the same as in that earlier declaration.
  2939. return NewVD->isPreviousDeclInSameBlockScope() ||
  2940. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  2941. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  2942. } else {
  2943. // If the old declaration was function-local, don't merge with its
  2944. // type unless we're in the same function.
  2945. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  2946. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  2947. }
  2948. }
  2949. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  2950. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  2951. /// situation, merging decls or emitting diagnostics as appropriate.
  2952. ///
  2953. /// Tentative definition rules (C99 6.9.2p2) are checked by
  2954. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  2955. /// definitions here, since the initializer hasn't been attached.
  2956. ///
  2957. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous, ShadowMergeState& MergeState) { // HLSL Change - add merge state
  2958. // If the new decl is already invalid, don't do any other checking.
  2959. if (New->isInvalidDecl())
  2960. return;
  2961. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  2962. // Verify the old decl was also a variable or variable template.
  2963. VarDecl *Old = nullptr;
  2964. VarTemplateDecl *OldTemplate = nullptr;
  2965. if (Previous.isSingleResult()) {
  2966. if (NewTemplate) {
  2967. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  2968. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  2969. if (auto *Shadow =
  2970. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  2971. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  2972. return New->setInvalidDecl();
  2973. } else {
  2974. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  2975. if (auto *Shadow =
  2976. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  2977. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  2978. return New->setInvalidDecl();
  2979. }
  2980. }
  2981. if (!Old) {
  2982. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2983. << New->getDeclName();
  2984. Diag(Previous.getRepresentativeDecl()->getLocation(),
  2985. diag::note_previous_definition);
  2986. return New->setInvalidDecl();
  2987. }
  2988. if (!shouldLinkPossiblyHiddenDecl(Old, New))
  2989. return;
  2990. // Ensure the template parameters are compatible.
  2991. if (NewTemplate &&
  2992. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  2993. OldTemplate->getTemplateParameters(),
  2994. /*Complain=*/true, TPL_TemplateMatch))
  2995. return;
  2996. // C++ [class.mem]p1:
  2997. // A member shall not be declared twice in the member-specification [...]
  2998. //
  2999. // Here, we need only consider static data members.
  3000. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3001. Diag(New->getLocation(), diag::err_duplicate_member)
  3002. << New->getIdentifier();
  3003. Diag(Old->getLocation(), diag::note_previous_declaration);
  3004. New->setInvalidDecl();
  3005. }
  3006. mergeDeclAttributes(New, Old);
  3007. // Warn if an already-declared variable is made a weak_import in a subsequent
  3008. // declaration
  3009. if (New->hasAttr<WeakImportAttr>() &&
  3010. Old->getStorageClass() == SC_None &&
  3011. !Old->hasAttr<WeakImportAttr>()) {
  3012. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3013. Diag(Old->getLocation(), diag::note_previous_definition);
  3014. // Remove weak_import attribute on new declaration.
  3015. New->dropAttr<WeakImportAttr>();
  3016. }
  3017. // Merge the types.
  3018. VarDecl *MostRecent = Old->getMostRecentDecl();
  3019. if (MostRecent != Old) {
  3020. MergeVarDeclTypes(New, MostRecent,
  3021. mergeTypeWithPrevious(*this, New, MostRecent, Previous), MergeState); // HLSL Change - add MergeState
  3022. if (New->isInvalidDecl())
  3023. return;
  3024. }
  3025. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous), MergeState); // HLSL Change - add MergeState
  3026. if (New->isInvalidDecl())
  3027. return;
  3028. diag::kind PrevDiag;
  3029. SourceLocation OldLocation;
  3030. std::tie(PrevDiag, OldLocation) =
  3031. getNoteDiagForInvalidRedeclaration(Old, New);
  3032. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3033. if (New->getStorageClass() == SC_Static &&
  3034. !New->isStaticDataMember() &&
  3035. Old->hasExternalFormalLinkage()) {
  3036. if (getLangOpts().MicrosoftExt) {
  3037. Diag(New->getLocation(), diag::ext_static_non_static)
  3038. << New->getDeclName();
  3039. Diag(OldLocation, PrevDiag);
  3040. } else {
  3041. Diag(New->getLocation(), diag::err_static_non_static)
  3042. << New->getDeclName();
  3043. Diag(OldLocation, PrevDiag);
  3044. return New->setInvalidDecl();
  3045. }
  3046. }
  3047. // C99 6.2.2p4:
  3048. // For an identifier declared with the storage-class specifier
  3049. // extern in a scope in which a prior declaration of that
  3050. // identifier is visible,23) if the prior declaration specifies
  3051. // internal or external linkage, the linkage of the identifier at
  3052. // the later declaration is the same as the linkage specified at
  3053. // the prior declaration. If no prior declaration is visible, or
  3054. // if the prior declaration specifies no linkage, then the
  3055. // identifier has external linkage.
  3056. if (New->hasExternalStorage() && Old->hasLinkage())
  3057. /* Okay */;
  3058. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3059. !New->isStaticDataMember() &&
  3060. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3061. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3062. Diag(OldLocation, PrevDiag);
  3063. return New->setInvalidDecl();
  3064. }
  3065. // Check if extern is followed by non-extern and vice-versa.
  3066. if (New->hasExternalStorage() &&
  3067. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3068. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3069. Diag(OldLocation, PrevDiag);
  3070. return New->setInvalidDecl();
  3071. }
  3072. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3073. !New->hasExternalStorage()) {
  3074. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3075. Diag(OldLocation, PrevDiag);
  3076. return New->setInvalidDecl();
  3077. }
  3078. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3079. // FIXME: The test for external storage here seems wrong? We still
  3080. // need to check for mismatches.
  3081. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3082. // Don't complain about out-of-line definitions of static members.
  3083. !(Old->getLexicalDeclContext()->isRecord() &&
  3084. !New->getLexicalDeclContext()->isRecord())) {
  3085. // HLSL Change Starts
  3086. if (MergeState == ShadowMergeState_Disallowed) {
  3087. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3088. Diag(OldLocation, PrevDiag);
  3089. return New->setInvalidDecl();
  3090. } else if (MergeState == ShadowMergeState_Possible) {
  3091. Diag(New->getLocation(), diag::warn_hlsl_for_redefinition)
  3092. << New->getDeclName();
  3093. Diag(Old->getLocation(), diag::note_previous_definition);
  3094. MergeState = ShadowMergeState_Effective;
  3095. }
  3096. // HLSL Change Ends
  3097. }
  3098. if (New->getTLSKind() != Old->getTLSKind()) {
  3099. if (!Old->getTLSKind()) {
  3100. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3101. Diag(OldLocation, PrevDiag);
  3102. } else if (!New->getTLSKind()) {
  3103. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3104. Diag(OldLocation, PrevDiag);
  3105. } else {
  3106. // Do not allow redeclaration to change the variable between requiring
  3107. // static and dynamic initialization.
  3108. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3109. // declaration to determine the kind. Do we need to be compatible here?
  3110. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3111. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3112. Diag(OldLocation, PrevDiag);
  3113. }
  3114. }
  3115. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3116. VarDecl *Def;
  3117. if (getLangOpts().CPlusPlus &&
  3118. New->isThisDeclarationADefinition() == VarDecl::Definition &&
  3119. (Def = Old->getDefinition())) {
  3120. NamedDecl *Hidden = nullptr;
  3121. if (!hasVisibleDefinition(Def, &Hidden) &&
  3122. (New->getFormalLinkage() == InternalLinkage ||
  3123. New->getDescribedVarTemplate() ||
  3124. New->getNumTemplateParameterLists() ||
  3125. New->getDeclContext()->isDependentContext())) {
  3126. // The previous definition is hidden, and multiple definitions are
  3127. // permitted (in separate TUs). Form another definition of it.
  3128. } else {
  3129. // HLSL Change Starts
  3130. if (MergeState == ShadowMergeState_Disallowed) {
  3131. Diag(New->getLocation(), diag::err_redefinition) << New;
  3132. Diag(Def->getLocation(), diag::note_previous_definition);
  3133. New->setInvalidDecl();
  3134. return;
  3135. }
  3136. else if (MergeState == ShadowMergeState_Possible) {
  3137. Diag(New->getLocation(), diag::warn_hlsl_for_redefinition) << New->getDeclName();
  3138. Diag(Old->getLocation(), diag::note_previous_definition);
  3139. MergeState = ShadowMergeState_Effective;
  3140. }
  3141. // HLSL Change Ends
  3142. }
  3143. }
  3144. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3145. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3146. Diag(OldLocation, PrevDiag);
  3147. New->setInvalidDecl();
  3148. return;
  3149. }
  3150. if (MergeState != ShadowMergeState_Effective) { // HLSL Change - avoid merging when shadowing
  3151. // Merge "used" flag.
  3152. if (Old->getMostRecentDecl()->isUsed(false))
  3153. New->setIsUsed();
  3154. // Keep a chain of previous declarations.
  3155. New->setPreviousDecl(Old);
  3156. if (NewTemplate)
  3157. NewTemplate->setPreviousDecl(OldTemplate);
  3158. // Inherit access appropriately.
  3159. New->setAccess(Old->getAccess());
  3160. if (NewTemplate)
  3161. NewTemplate->setAccess(New->getAccess());
  3162. } // HLSL Change - close block conditional on shadow merge state
  3163. }
  3164. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3165. /// no declarator (e.g. "struct foo;") is parsed.
  3166. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  3167. DeclSpec &DS) {
  3168. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
  3169. }
  3170. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3171. // disambiguate entities defined in different scopes.
  3172. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3173. // compatibility.
  3174. // We will pick our mangling number depending on which version of MSVC is being
  3175. // targeted.
  3176. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3177. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3178. ? S->getMSCurManglingNumber()
  3179. : S->getMSLastManglingNumber();
  3180. }
  3181. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3182. if (!Context.getLangOpts().CPlusPlus)
  3183. return;
  3184. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3185. // If this tag is the direct child of a class, number it if
  3186. // it is anonymous.
  3187. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3188. return;
  3189. MangleNumberingContext &MCtx =
  3190. Context.getManglingNumberContext(Tag->getParent());
  3191. Context.setManglingNumber(
  3192. Tag, MCtx.getManglingNumber(
  3193. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3194. return;
  3195. }
  3196. // If this tag isn't a direct child of a class, number it if it is local.
  3197. Decl *ManglingContextDecl;
  3198. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3199. Tag->getDeclContext(), ManglingContextDecl)) {
  3200. Context.setManglingNumber(
  3201. Tag, MCtx->getManglingNumber(
  3202. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3203. }
  3204. }
  3205. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3206. TypedefNameDecl *NewTD) {
  3207. // Do nothing if the tag is not anonymous or already has an
  3208. // associated typedef (from an earlier typedef in this decl group).
  3209. if (TagFromDeclSpec->getIdentifier())
  3210. return;
  3211. if (TagFromDeclSpec->getTypedefNameForAnonDecl())
  3212. return;
  3213. // A well-formed anonymous tag must always be a TUK_Definition.
  3214. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3215. // The type must match the tag exactly; no qualifiers allowed.
  3216. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3217. Context.getTagDeclType(TagFromDeclSpec)))
  3218. return;
  3219. // If we've already computed linkage for the anonymous tag, then
  3220. // adding a typedef name for the anonymous decl can change that
  3221. // linkage, which might be a serious problem. Diagnose this as
  3222. // unsupported and ignore the typedef name. TODO: we should
  3223. // pursue this as a language defect and establish a formal rule
  3224. // for how to handle it.
  3225. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3226. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3227. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3228. tagLoc = getLocForEndOfToken(tagLoc);
  3229. llvm::SmallString<40> textToInsert;
  3230. textToInsert += ' ';
  3231. textToInsert += NewTD->getIdentifier()->getName();
  3232. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3233. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3234. return;
  3235. }
  3236. // Otherwise, set this is the anon-decl typedef for the tag.
  3237. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3238. }
  3239. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3240. switch (T) {
  3241. case DeclSpec::TST_class:
  3242. return 0;
  3243. case DeclSpec::TST_struct:
  3244. return 1;
  3245. case DeclSpec::TST_interface:
  3246. return 2;
  3247. case DeclSpec::TST_union:
  3248. return 3;
  3249. case DeclSpec::TST_enum:
  3250. return 4;
  3251. default:
  3252. llvm_unreachable("unexpected type specifier");
  3253. }
  3254. }
  3255. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3256. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3257. /// parameters to cope with template friend declarations.
  3258. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  3259. DeclSpec &DS,
  3260. MultiTemplateParamsArg TemplateParams,
  3261. bool IsExplicitInstantiation) {
  3262. Decl *TagD = nullptr;
  3263. TagDecl *Tag = nullptr;
  3264. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3265. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3266. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3267. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3268. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3269. TagD = DS.getRepAsDecl();
  3270. if (!TagD) // We probably had an error
  3271. return nullptr;
  3272. // Note that the above type specs guarantee that the
  3273. // type rep is a Decl, whereas in many of the others
  3274. // it's a Type.
  3275. if (isa<TagDecl>(TagD))
  3276. Tag = cast<TagDecl>(TagD);
  3277. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3278. Tag = CTD->getTemplatedDecl();
  3279. }
  3280. if (Tag) {
  3281. handleTagNumbering(Tag, S);
  3282. Tag->setFreeStanding();
  3283. if (Tag->isInvalidDecl())
  3284. return Tag;
  3285. }
  3286. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3287. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3288. // or incomplete types shall not be restrict-qualified."
  3289. if (TypeQuals & DeclSpec::TQ_restrict)
  3290. Diag(DS.getRestrictSpecLoc(),
  3291. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3292. << DS.getSourceRange();
  3293. }
  3294. if (DS.isConstexprSpecified()) {
  3295. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3296. // and definitions of functions and variables.
  3297. if (Tag)
  3298. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3299. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
  3300. else
  3301. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  3302. // Don't emit warnings after this error.
  3303. return TagD;
  3304. }
  3305. DiagnoseFunctionSpecifiers(DS);
  3306. if (DS.isFriendSpecified()) {
  3307. // If we're dealing with a decl but not a TagDecl, assume that
  3308. // whatever routines created it handled the friendship aspect.
  3309. if (TagD && !Tag)
  3310. return nullptr;
  3311. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3312. }
  3313. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3314. bool IsExplicitSpecialization =
  3315. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3316. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3317. !IsExplicitInstantiation && !IsExplicitSpecialization) {
  3318. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3319. // nested-name-specifier unless it is an explicit instantiation
  3320. // or an explicit specialization.
  3321. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3322. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3323. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3324. return nullptr;
  3325. }
  3326. // Track whether this decl-specifier declares anything.
  3327. bool DeclaresAnything = true;
  3328. // Handle anonymous struct definitions.
  3329. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3330. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3331. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3332. if (getLangOpts().CPlusPlus ||
  3333. Record->getDeclContext()->isRecord())
  3334. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3335. Context.getPrintingPolicy());
  3336. DeclaresAnything = false;
  3337. }
  3338. }
  3339. // C11 6.7.2.1p2:
  3340. // A struct-declaration that does not declare an anonymous structure or
  3341. // anonymous union shall contain a struct-declarator-list.
  3342. //
  3343. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3344. // did not permit a struct-declaration without a struct-declarator-list.
  3345. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3346. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3347. // Check for Microsoft C extension: anonymous struct/union member.
  3348. // Handle 2 kinds of anonymous struct/union:
  3349. // struct STRUCT;
  3350. // union UNION;
  3351. // and
  3352. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3353. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3354. if ((Tag && Tag->getDeclName()) ||
  3355. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3356. RecordDecl *Record = nullptr;
  3357. if (Tag)
  3358. Record = dyn_cast<RecordDecl>(Tag);
  3359. else if (const RecordType *RT =
  3360. DS.getRepAsType().get()->getAsStructureType())
  3361. Record = RT->getDecl();
  3362. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3363. Record = UT->getDecl();
  3364. if (Record && getLangOpts().MicrosoftExt) {
  3365. Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
  3366. << Record->isUnion() << DS.getSourceRange();
  3367. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3368. }
  3369. DeclaresAnything = false;
  3370. }
  3371. }
  3372. // Skip all the checks below if we have a type error.
  3373. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3374. (TagD && TagD->isInvalidDecl()))
  3375. return TagD;
  3376. if (getLangOpts().CPlusPlus &&
  3377. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3378. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3379. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3380. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3381. DeclaresAnything = false;
  3382. if (!DS.isMissingDeclaratorOk()) {
  3383. // Customize diagnostic for a typedef missing a name.
  3384. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3385. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  3386. << DS.getSourceRange();
  3387. else
  3388. DeclaresAnything = false;
  3389. }
  3390. if (DS.isModulePrivateSpecified() &&
  3391. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3392. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3393. << Tag->getTagKind()
  3394. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3395. ActOnDocumentableDecl(TagD);
  3396. // C 6.7/2:
  3397. // A declaration [...] shall declare at least a declarator [...], a tag,
  3398. // or the members of an enumeration.
  3399. // C++ [dcl.dcl]p3:
  3400. // [If there are no declarators], and except for the declaration of an
  3401. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3402. // names into the program, or shall redeclare a name introduced by a
  3403. // previous declaration.
  3404. if (!DeclaresAnything) {
  3405. // In C, we allow this as a (popular) extension / bug. Don't bother
  3406. // producing further diagnostics for redundant qualifiers after this.
  3407. Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
  3408. return TagD;
  3409. }
  3410. // C++ [dcl.stc]p1:
  3411. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3412. // init-declarator-list of the declaration shall not be empty.
  3413. // C++ [dcl.fct.spec]p1:
  3414. // If a cv-qualifier appears in a decl-specifier-seq, the
  3415. // init-declarator-list of the declaration shall not be empty.
  3416. //
  3417. // Spurious qualifiers here appear to be valid in C.
  3418. unsigned DiagID = diag::warn_standalone_specifier;
  3419. if (getLangOpts().CPlusPlus)
  3420. DiagID = diag::ext_standalone_specifier;
  3421. // Note that a linkage-specification sets a storage class, but
  3422. // 'extern "C" struct foo;' is actually valid and not theoretically
  3423. // useless.
  3424. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3425. if (SCS == DeclSpec::SCS_mutable)
  3426. // Since mutable is not a viable storage class specifier in C, there is
  3427. // no reason to treat it as an extension. Instead, diagnose as an error.
  3428. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3429. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3430. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3431. << DeclSpec::getSpecifierName(SCS);
  3432. }
  3433. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3434. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3435. << DeclSpec::getSpecifierName(TSCS);
  3436. if (DS.getTypeQualifiers()) {
  3437. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3438. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3439. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3440. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3441. // Restrict is covered above.
  3442. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3443. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3444. }
  3445. // Warn about ignored type attributes, for example:
  3446. // __attribute__((aligned)) struct A;
  3447. // Attributes should be placed after tag to apply to type declaration.
  3448. if (!DS.getAttributes().empty()) {
  3449. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3450. if (TypeSpecType == DeclSpec::TST_class ||
  3451. TypeSpecType == DeclSpec::TST_struct ||
  3452. TypeSpecType == DeclSpec::TST_interface ||
  3453. TypeSpecType == DeclSpec::TST_union ||
  3454. TypeSpecType == DeclSpec::TST_enum) {
  3455. for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
  3456. attrs = attrs->getNext())
  3457. Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
  3458. << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3459. }
  3460. }
  3461. return TagD;
  3462. }
  3463. /// We are trying to inject an anonymous member into the given scope;
  3464. /// check if there's an existing declaration that can't be overloaded.
  3465. ///
  3466. /// \return true if this is a forbidden redeclaration
  3467. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3468. Scope *S,
  3469. DeclContext *Owner,
  3470. DeclarationName Name,
  3471. SourceLocation NameLoc,
  3472. unsigned diagnostic) {
  3473. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  3474. Sema::ForRedeclaration);
  3475. if (!SemaRef.LookupName(R, S)) return false;
  3476. if (R.getAsSingle<TagDecl>())
  3477. return false;
  3478. // Pick a representative declaration.
  3479. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  3480. assert(PrevDecl && "Expected a non-null Decl");
  3481. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  3482. return false;
  3483. SemaRef.Diag(NameLoc, diagnostic) << Name;
  3484. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  3485. return true;
  3486. }
  3487. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  3488. /// anonymous struct or union AnonRecord into the owning context Owner
  3489. /// and scope S. This routine will be invoked just after we realize
  3490. /// that an unnamed union or struct is actually an anonymous union or
  3491. /// struct, e.g.,
  3492. ///
  3493. /// @code
  3494. /// union {
  3495. /// int i;
  3496. /// float f;
  3497. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  3498. /// // f into the surrounding scope.x
  3499. /// @endcode
  3500. ///
  3501. /// This routine is recursive, injecting the names of nested anonymous
  3502. /// structs/unions into the owning context and scope as well.
  3503. static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
  3504. DeclContext *Owner,
  3505. RecordDecl *AnonRecord,
  3506. AccessSpecifier AS,
  3507. SmallVectorImpl<NamedDecl *> &Chaining,
  3508. bool MSAnonStruct) {
  3509. unsigned diagKind
  3510. = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
  3511. : diag::err_anonymous_struct_member_redecl;
  3512. bool Invalid = false;
  3513. // Look every FieldDecl and IndirectFieldDecl with a name.
  3514. for (auto *D : AnonRecord->decls()) {
  3515. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  3516. cast<NamedDecl>(D)->getDeclName()) {
  3517. ValueDecl *VD = cast<ValueDecl>(D);
  3518. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  3519. VD->getLocation(), diagKind)) {
  3520. // C++ [class.union]p2:
  3521. // The names of the members of an anonymous union shall be
  3522. // distinct from the names of any other entity in the
  3523. // scope in which the anonymous union is declared.
  3524. Invalid = true;
  3525. } else {
  3526. // C++ [class.union]p2:
  3527. // For the purpose of name lookup, after the anonymous union
  3528. // definition, the members of the anonymous union are
  3529. // considered to have been defined in the scope in which the
  3530. // anonymous union is declared.
  3531. unsigned OldChainingSize = Chaining.size();
  3532. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  3533. Chaining.append(IF->chain_begin(), IF->chain_end());
  3534. else
  3535. Chaining.push_back(VD);
  3536. assert(Chaining.size() >= 2);
  3537. NamedDecl **NamedChain =
  3538. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  3539. for (unsigned i = 0; i < Chaining.size(); i++)
  3540. NamedChain[i] = Chaining[i];
  3541. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  3542. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  3543. VD->getType(), NamedChain, Chaining.size());
  3544. for (const auto *Attr : VD->attrs())
  3545. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  3546. IndirectField->setAccess(AS);
  3547. IndirectField->setImplicit();
  3548. SemaRef.PushOnScopeChains(IndirectField, S);
  3549. // That includes picking up the appropriate access specifier.
  3550. if (AS != AS_none) IndirectField->setAccess(AS);
  3551. Chaining.resize(OldChainingSize);
  3552. }
  3553. }
  3554. }
  3555. return Invalid;
  3556. }
  3557. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  3558. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  3559. /// illegal input values are mapped to SC_None.
  3560. static StorageClass
  3561. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  3562. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  3563. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  3564. "Parser allowed 'typedef' as storage class VarDecl.");
  3565. switch (StorageClassSpec) {
  3566. case DeclSpec::SCS_unspecified: return SC_None;
  3567. case DeclSpec::SCS_extern:
  3568. if (DS.isExternInLinkageSpec())
  3569. return SC_None;
  3570. return SC_Extern;
  3571. case DeclSpec::SCS_static: return SC_Static;
  3572. case DeclSpec::SCS_auto: return SC_Auto;
  3573. case DeclSpec::SCS_register: return SC_Register;
  3574. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  3575. // Illegal SCSs map to None: error reporting is up to the caller.
  3576. case DeclSpec::SCS_mutable: // Fall through.
  3577. case DeclSpec::SCS_typedef: return SC_None;
  3578. }
  3579. llvm_unreachable("unknown storage class specifier");
  3580. }
  3581. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  3582. assert(Record->hasInClassInitializer());
  3583. for (const auto *I : Record->decls()) {
  3584. const auto *FD = dyn_cast<FieldDecl>(I);
  3585. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  3586. FD = IFD->getAnonField();
  3587. if (FD && FD->hasInClassInitializer())
  3588. return FD->getLocation();
  3589. }
  3590. llvm_unreachable("couldn't find in-class initializer");
  3591. }
  3592. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3593. SourceLocation DefaultInitLoc) {
  3594. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3595. return;
  3596. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  3597. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  3598. }
  3599. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3600. CXXRecordDecl *AnonUnion) {
  3601. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3602. return;
  3603. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  3604. }
  3605. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  3606. /// anonymous structure or union. Anonymous unions are a C++ feature
  3607. /// (C++ [class.union]) and a C11 feature; anonymous structures
  3608. /// are a C11 feature and GNU C++ extension.
  3609. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  3610. AccessSpecifier AS,
  3611. RecordDecl *Record,
  3612. const PrintingPolicy &Policy) {
  3613. DeclContext *Owner = Record->getDeclContext();
  3614. // Diagnose whether this anonymous struct/union is an extension.
  3615. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  3616. Diag(Record->getLocation(), diag::ext_anonymous_union);
  3617. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  3618. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  3619. else if (!Record->isUnion() && !getLangOpts().C11)
  3620. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  3621. // C and C++ require different kinds of checks for anonymous
  3622. // structs/unions.
  3623. bool Invalid = false;
  3624. if (getLangOpts().CPlusPlus) {
  3625. const char *PrevSpec = nullptr;
  3626. unsigned DiagID;
  3627. if (Record->isUnion()) {
  3628. // C++ [class.union]p6:
  3629. // Anonymous unions declared in a named namespace or in the
  3630. // global namespace shall be declared static.
  3631. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  3632. (isa<TranslationUnitDecl>(Owner) ||
  3633. (isa<NamespaceDecl>(Owner) &&
  3634. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  3635. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  3636. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  3637. // Recover by adding 'static'.
  3638. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  3639. PrevSpec, DiagID, Policy);
  3640. }
  3641. // C++ [class.union]p6:
  3642. // A storage class is not allowed in a declaration of an
  3643. // anonymous union in a class scope.
  3644. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  3645. isa<RecordDecl>(Owner)) {
  3646. Diag(DS.getStorageClassSpecLoc(),
  3647. diag::err_anonymous_union_with_storage_spec)
  3648. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  3649. // Recover by removing the storage specifier.
  3650. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  3651. SourceLocation(),
  3652. PrevSpec, DiagID, Context.getPrintingPolicy());
  3653. }
  3654. }
  3655. // Ignore const/volatile/restrict qualifiers.
  3656. if (DS.getTypeQualifiers()) {
  3657. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3658. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  3659. << Record->isUnion() << "const"
  3660. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  3661. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3662. Diag(DS.getVolatileSpecLoc(),
  3663. diag::ext_anonymous_struct_union_qualified)
  3664. << Record->isUnion() << "volatile"
  3665. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  3666. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  3667. Diag(DS.getRestrictSpecLoc(),
  3668. diag::ext_anonymous_struct_union_qualified)
  3669. << Record->isUnion() << "restrict"
  3670. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  3671. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3672. Diag(DS.getAtomicSpecLoc(),
  3673. diag::ext_anonymous_struct_union_qualified)
  3674. << Record->isUnion() << "_Atomic"
  3675. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  3676. DS.ClearTypeQualifiers();
  3677. }
  3678. // C++ [class.union]p2:
  3679. // The member-specification of an anonymous union shall only
  3680. // define non-static data members. [Note: nested types and
  3681. // functions cannot be declared within an anonymous union. ]
  3682. for (auto *Mem : Record->decls()) {
  3683. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  3684. // C++ [class.union]p3:
  3685. // An anonymous union shall not have private or protected
  3686. // members (clause 11).
  3687. assert(FD->getAccess() != AS_none);
  3688. if (FD->getAccess() != AS_public) {
  3689. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  3690. << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
  3691. Invalid = true;
  3692. }
  3693. // C++ [class.union]p1
  3694. // An object of a class with a non-trivial constructor, a non-trivial
  3695. // copy constructor, a non-trivial destructor, or a non-trivial copy
  3696. // assignment operator cannot be a member of a union, nor can an
  3697. // array of such objects.
  3698. if (CheckNontrivialField(FD))
  3699. Invalid = true;
  3700. } else if (Mem->isImplicit()) {
  3701. // Any implicit members are fine.
  3702. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  3703. // This is a type that showed up in an
  3704. // elaborated-type-specifier inside the anonymous struct or
  3705. // union, but which actually declares a type outside of the
  3706. // anonymous struct or union. It's okay.
  3707. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  3708. if (!MemRecord->isAnonymousStructOrUnion() &&
  3709. MemRecord->getDeclName()) {
  3710. // Visual C++ allows type definition in anonymous struct or union.
  3711. if (getLangOpts().MicrosoftExt)
  3712. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  3713. << (int)Record->isUnion();
  3714. else {
  3715. // This is a nested type declaration.
  3716. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  3717. << (int)Record->isUnion();
  3718. Invalid = true;
  3719. }
  3720. } else {
  3721. // This is an anonymous type definition within another anonymous type.
  3722. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  3723. // not part of standard C++.
  3724. Diag(MemRecord->getLocation(),
  3725. diag::ext_anonymous_record_with_anonymous_type)
  3726. << (int)Record->isUnion();
  3727. }
  3728. } else if (isa<AccessSpecDecl>(Mem)) {
  3729. // Any access specifier is fine.
  3730. } else if (isa<StaticAssertDecl>(Mem)) {
  3731. // In C++1z, static_assert declarations are also fine.
  3732. } else {
  3733. // We have something that isn't a non-static data
  3734. // member. Complain about it.
  3735. unsigned DK = diag::err_anonymous_record_bad_member;
  3736. if (isa<TypeDecl>(Mem))
  3737. DK = diag::err_anonymous_record_with_type;
  3738. else if (isa<FunctionDecl>(Mem))
  3739. DK = diag::err_anonymous_record_with_function;
  3740. else if (isa<VarDecl>(Mem))
  3741. DK = diag::err_anonymous_record_with_static;
  3742. // Visual C++ allows type definition in anonymous struct or union.
  3743. if (getLangOpts().MicrosoftExt &&
  3744. DK == diag::err_anonymous_record_with_type)
  3745. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  3746. << (int)Record->isUnion();
  3747. else {
  3748. Diag(Mem->getLocation(), DK)
  3749. << (int)Record->isUnion();
  3750. Invalid = true;
  3751. }
  3752. }
  3753. }
  3754. // C++11 [class.union]p8 (DR1460):
  3755. // At most one variant member of a union may have a
  3756. // brace-or-equal-initializer.
  3757. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  3758. Owner->isRecord())
  3759. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  3760. cast<CXXRecordDecl>(Record));
  3761. }
  3762. if (!Record->isUnion() && !Owner->isRecord()) {
  3763. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  3764. << (int)getLangOpts().CPlusPlus;
  3765. Invalid = true;
  3766. }
  3767. // Mock up a declarator.
  3768. Declarator Dc(DS, Declarator::MemberContext);
  3769. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  3770. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  3771. // Create a declaration for this anonymous struct/union.
  3772. NamedDecl *Anon = nullptr;
  3773. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  3774. Anon = FieldDecl::Create(Context, OwningClass,
  3775. DS.getLocStart(),
  3776. Record->getLocation(),
  3777. /*IdentifierInfo=*/nullptr,
  3778. Context.getTypeDeclType(Record),
  3779. TInfo,
  3780. /*BitWidth=*/nullptr, /*Mutable=*/false,
  3781. /*InitStyle=*/ICIS_NoInit);
  3782. Anon->setAccess(AS);
  3783. if (getLangOpts().CPlusPlus)
  3784. FieldCollector->Add(cast<FieldDecl>(Anon));
  3785. } else {
  3786. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  3787. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  3788. if (SCSpec == DeclSpec::SCS_mutable) {
  3789. // mutable can only appear on non-static class members, so it's always
  3790. // an error here
  3791. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  3792. Invalid = true;
  3793. SC = SC_None;
  3794. }
  3795. Anon = VarDecl::Create(Context, Owner,
  3796. DS.getLocStart(),
  3797. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  3798. Context.getTypeDeclType(Record),
  3799. TInfo, SC);
  3800. // Default-initialize the implicit variable. This initialization will be
  3801. // trivial in almost all cases, except if a union member has an in-class
  3802. // initializer:
  3803. // union { int n = 0; };
  3804. ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
  3805. }
  3806. Anon->setImplicit();
  3807. // Mark this as an anonymous struct/union type.
  3808. Record->setAnonymousStructOrUnion(true);
  3809. // Add the anonymous struct/union object to the current
  3810. // context. We'll be referencing this object when we refer to one of
  3811. // its members.
  3812. Owner->addDecl(Anon);
  3813. // Inject the members of the anonymous struct/union into the owning
  3814. // context and into the identifier resolver chain for name lookup
  3815. // purposes.
  3816. SmallVector<NamedDecl*, 2> Chain;
  3817. Chain.push_back(Anon);
  3818. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
  3819. Chain, false))
  3820. Invalid = true;
  3821. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  3822. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  3823. Decl *ManglingContextDecl;
  3824. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3825. NewVD->getDeclContext(), ManglingContextDecl)) {
  3826. Context.setManglingNumber(
  3827. NewVD, MCtx->getManglingNumber(
  3828. NewVD, getMSManglingNumber(getLangOpts(), S)));
  3829. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  3830. }
  3831. }
  3832. }
  3833. if (Invalid)
  3834. Anon->setInvalidDecl();
  3835. return Anon;
  3836. }
  3837. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  3838. /// Microsoft C anonymous structure.
  3839. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  3840. /// Example:
  3841. ///
  3842. /// struct A { int a; };
  3843. /// struct B { struct A; int b; };
  3844. ///
  3845. /// void foo() {
  3846. /// B var;
  3847. /// var.a = 3;
  3848. /// }
  3849. ///
  3850. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  3851. RecordDecl *Record) {
  3852. assert(Record && "expected a record!");
  3853. // Mock up a declarator.
  3854. Declarator Dc(DS, Declarator::TypeNameContext);
  3855. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  3856. assert(TInfo && "couldn't build declarator info for anonymous struct");
  3857. auto *ParentDecl = cast<RecordDecl>(CurContext);
  3858. QualType RecTy = Context.getTypeDeclType(Record);
  3859. // Create a declaration for this anonymous struct.
  3860. NamedDecl *Anon = FieldDecl::Create(Context,
  3861. ParentDecl,
  3862. DS.getLocStart(),
  3863. DS.getLocStart(),
  3864. /*IdentifierInfo=*/nullptr,
  3865. RecTy,
  3866. TInfo,
  3867. /*BitWidth=*/nullptr, /*Mutable=*/false,
  3868. /*InitStyle=*/ICIS_NoInit);
  3869. Anon->setImplicit();
  3870. // Add the anonymous struct object to the current context.
  3871. CurContext->addDecl(Anon);
  3872. // Inject the members of the anonymous struct into the current
  3873. // context and into the identifier resolver chain for name lookup
  3874. // purposes.
  3875. SmallVector<NamedDecl*, 2> Chain;
  3876. Chain.push_back(Anon);
  3877. RecordDecl *RecordDef = Record->getDefinition();
  3878. if (RequireCompleteType(Anon->getLocation(), RecTy,
  3879. diag::err_field_incomplete) ||
  3880. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  3881. AS_none, Chain, true)) {
  3882. Anon->setInvalidDecl();
  3883. ParentDecl->setInvalidDecl();
  3884. }
  3885. return Anon;
  3886. }
  3887. /// GetNameForDeclarator - Determine the full declaration name for the
  3888. /// given Declarator.
  3889. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  3890. return GetNameFromUnqualifiedId(D.getName());
  3891. }
  3892. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  3893. DeclarationNameInfo
  3894. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  3895. DeclarationNameInfo NameInfo;
  3896. NameInfo.setLoc(Name.StartLocation);
  3897. switch (Name.getKind()) {
  3898. case UnqualifiedId::IK_ImplicitSelfParam:
  3899. case UnqualifiedId::IK_Identifier:
  3900. NameInfo.setName(Name.Identifier);
  3901. NameInfo.setLoc(Name.StartLocation);
  3902. return NameInfo;
  3903. case UnqualifiedId::IK_OperatorFunctionId:
  3904. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  3905. Name.OperatorFunctionId.Operator));
  3906. NameInfo.setLoc(Name.StartLocation);
  3907. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  3908. = Name.OperatorFunctionId.SymbolLocations[0];
  3909. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  3910. = Name.EndLocation.getRawEncoding();
  3911. return NameInfo;
  3912. case UnqualifiedId::IK_LiteralOperatorId:
  3913. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  3914. Name.Identifier));
  3915. NameInfo.setLoc(Name.StartLocation);
  3916. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  3917. return NameInfo;
  3918. case UnqualifiedId::IK_ConversionFunctionId: {
  3919. TypeSourceInfo *TInfo;
  3920. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  3921. if (Ty.isNull())
  3922. return DeclarationNameInfo();
  3923. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  3924. Context.getCanonicalType(Ty)));
  3925. NameInfo.setLoc(Name.StartLocation);
  3926. NameInfo.setNamedTypeInfo(TInfo);
  3927. return NameInfo;
  3928. }
  3929. case UnqualifiedId::IK_ConstructorName: {
  3930. TypeSourceInfo *TInfo;
  3931. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  3932. if (Ty.isNull())
  3933. return DeclarationNameInfo();
  3934. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  3935. Context.getCanonicalType(Ty)));
  3936. NameInfo.setLoc(Name.StartLocation);
  3937. NameInfo.setNamedTypeInfo(TInfo);
  3938. return NameInfo;
  3939. }
  3940. case UnqualifiedId::IK_ConstructorTemplateId: {
  3941. // In well-formed code, we can only have a constructor
  3942. // template-id that refers to the current context, so go there
  3943. // to find the actual type being constructed.
  3944. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  3945. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  3946. return DeclarationNameInfo();
  3947. // Determine the type of the class being constructed.
  3948. QualType CurClassType = Context.getTypeDeclType(CurClass);
  3949. // FIXME: Check two things: that the template-id names the same type as
  3950. // CurClassType, and that the template-id does not occur when the name
  3951. // was qualified.
  3952. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  3953. Context.getCanonicalType(CurClassType)));
  3954. NameInfo.setLoc(Name.StartLocation);
  3955. // FIXME: should we retrieve TypeSourceInfo?
  3956. NameInfo.setNamedTypeInfo(nullptr);
  3957. return NameInfo;
  3958. }
  3959. case UnqualifiedId::IK_DestructorName: {
  3960. TypeSourceInfo *TInfo;
  3961. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  3962. if (Ty.isNull())
  3963. return DeclarationNameInfo();
  3964. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  3965. Context.getCanonicalType(Ty)));
  3966. NameInfo.setLoc(Name.StartLocation);
  3967. NameInfo.setNamedTypeInfo(TInfo);
  3968. return NameInfo;
  3969. }
  3970. case UnqualifiedId::IK_TemplateId: {
  3971. TemplateName TName = Name.TemplateId->Template.get();
  3972. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  3973. return Context.getNameForTemplate(TName, TNameLoc);
  3974. }
  3975. } // switch (Name.getKind())
  3976. llvm_unreachable("Unknown name kind");
  3977. }
  3978. static QualType getCoreType(QualType Ty) {
  3979. do {
  3980. if (Ty->isPointerType() || Ty->isReferenceType())
  3981. Ty = Ty->getPointeeType();
  3982. else if (Ty->isArrayType())
  3983. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  3984. else
  3985. return Ty.withoutLocalFastQualifiers();
  3986. } while (true);
  3987. }
  3988. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  3989. /// and Definition have "nearly" matching parameters. This heuristic is
  3990. /// used to improve diagnostics in the case where an out-of-line function
  3991. /// definition doesn't match any declaration within the class or namespace.
  3992. /// Also sets Params to the list of indices to the parameters that differ
  3993. /// between the declaration and the definition. If hasSimilarParameters
  3994. /// returns true and Params is empty, then all of the parameters match.
  3995. static bool hasSimilarParameters(ASTContext &Context,
  3996. FunctionDecl *Declaration,
  3997. FunctionDecl *Definition,
  3998. SmallVectorImpl<unsigned> &Params) {
  3999. Params.clear();
  4000. if (Declaration->param_size() != Definition->param_size())
  4001. return false;
  4002. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4003. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4004. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4005. // The parameter types are identical
  4006. if (Context.hasSameType(DefParamTy, DeclParamTy))
  4007. continue;
  4008. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4009. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4010. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4011. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4012. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4013. (DeclTyName && DeclTyName == DefTyName))
  4014. Params.push_back(Idx);
  4015. else // The two parameters aren't even close
  4016. return false;
  4017. }
  4018. return true;
  4019. }
  4020. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4021. /// declarator needs to be rebuilt in the current instantiation.
  4022. /// Any bits of declarator which appear before the name are valid for
  4023. /// consideration here. That's specifically the type in the decl spec
  4024. /// and the base type in any member-pointer chunks.
  4025. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4026. DeclarationName Name) {
  4027. // The types we specifically need to rebuild are:
  4028. // - typenames, typeofs, and decltypes
  4029. // - types which will become injected class names
  4030. // Of course, we also need to rebuild any type referencing such a
  4031. // type. It's safest to just say "dependent", but we call out a
  4032. // few cases here.
  4033. DeclSpec &DS = D.getMutableDeclSpec();
  4034. switch (DS.getTypeSpecType()) {
  4035. case DeclSpec::TST_typename:
  4036. case DeclSpec::TST_typeofType:
  4037. case DeclSpec::TST_underlyingType:
  4038. case DeclSpec::TST_atomic: {
  4039. // Grab the type from the parser.
  4040. TypeSourceInfo *TSI = nullptr;
  4041. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4042. if (T.isNull() || !T->isDependentType()) break;
  4043. // Make sure there's a type source info. This isn't really much
  4044. // of a waste; most dependent types should have type source info
  4045. // attached already.
  4046. if (!TSI)
  4047. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4048. // Rebuild the type in the current instantiation.
  4049. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4050. if (!TSI) return true;
  4051. // Store the new type back in the decl spec.
  4052. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4053. DS.UpdateTypeRep(LocType);
  4054. break;
  4055. }
  4056. case DeclSpec::TST_decltype:
  4057. case DeclSpec::TST_typeofExpr: {
  4058. Expr *E = DS.getRepAsExpr();
  4059. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4060. if (Result.isInvalid()) return true;
  4061. DS.UpdateExprRep(Result.get());
  4062. break;
  4063. }
  4064. default:
  4065. // Nothing to do for these decl specs.
  4066. break;
  4067. }
  4068. // It doesn't matter what order we do this in.
  4069. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4070. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4071. // The only type information in the declarator which can come
  4072. // before the declaration name is the base type of a member
  4073. // pointer.
  4074. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4075. continue;
  4076. // Rebuild the scope specifier in-place.
  4077. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4078. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4079. return true;
  4080. }
  4081. return false;
  4082. }
  4083. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4084. D.setFunctionDefinitionKind(FDK_Declaration);
  4085. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4086. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4087. Dcl && Dcl->getDeclContext()->isFileContext())
  4088. Dcl->setTopLevelDeclInObjCContainer();
  4089. return Dcl;
  4090. }
  4091. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4092. /// If T is the name of a class, then each of the following shall have a
  4093. /// name different from T:
  4094. /// - every static data member of class T;
  4095. /// - every member function of class T
  4096. /// - every member of class T that is itself a type;
  4097. /// \returns true if the declaration name violates these rules.
  4098. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4099. DeclarationNameInfo NameInfo) {
  4100. DeclarationName Name = NameInfo.getName();
  4101. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  4102. if (Record->getIdentifier() && Record->getDeclName() == Name) {
  4103. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4104. return true;
  4105. }
  4106. return false;
  4107. }
  4108. /// \brief Diagnose a declaration whose declarator-id has the given
  4109. /// nested-name-specifier.
  4110. ///
  4111. /// \param SS The nested-name-specifier of the declarator-id.
  4112. ///
  4113. /// \param DC The declaration context to which the nested-name-specifier
  4114. /// resolves.
  4115. ///
  4116. /// \param Name The name of the entity being declared.
  4117. ///
  4118. /// \param Loc The location of the name of the entity being declared.
  4119. ///
  4120. /// \returns true if we cannot safely recover from this error, false otherwise.
  4121. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4122. DeclarationName Name,
  4123. SourceLocation Loc) {
  4124. DeclContext *Cur = CurContext;
  4125. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4126. Cur = Cur->getParent();
  4127. // If the user provided a superfluous scope specifier that refers back to the
  4128. // class in which the entity is already declared, diagnose and ignore it.
  4129. //
  4130. // class X {
  4131. // void X::f();
  4132. // };
  4133. //
  4134. // Note, it was once ill-formed to give redundant qualification in all
  4135. // contexts, but that rule was removed by DR482.
  4136. if (Cur->Equals(DC)) {
  4137. if (Cur->isRecord()) {
  4138. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4139. : diag::err_member_extra_qualification)
  4140. << Name << FixItHint::CreateRemoval(SS.getRange());
  4141. SS.clear();
  4142. } else {
  4143. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4144. }
  4145. return false;
  4146. }
  4147. // Check whether the qualifying scope encloses the scope of the original
  4148. // declaration.
  4149. if (!Cur->Encloses(DC)) {
  4150. if (Cur->isRecord())
  4151. Diag(Loc, diag::err_member_qualification)
  4152. << Name << SS.getRange();
  4153. else if (isa<TranslationUnitDecl>(DC))
  4154. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4155. << Name << SS.getRange();
  4156. else if (isa<FunctionDecl>(Cur))
  4157. Diag(Loc, diag::err_invalid_declarator_in_function)
  4158. << Name << SS.getRange();
  4159. else if (isa<BlockDecl>(Cur))
  4160. Diag(Loc, diag::err_invalid_declarator_in_block)
  4161. << Name << SS.getRange();
  4162. else
  4163. Diag(Loc, diag::err_invalid_declarator_scope)
  4164. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4165. return true;
  4166. }
  4167. if (Cur->isRecord()) {
  4168. // Cannot qualify members within a class.
  4169. Diag(Loc, diag::err_member_qualification)
  4170. << Name << SS.getRange();
  4171. SS.clear();
  4172. // C++ constructors and destructors with incorrect scopes can break
  4173. // our AST invariants by having the wrong underlying types. If
  4174. // that's the case, then drop this declaration entirely.
  4175. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4176. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4177. !Context.hasSameType(Name.getCXXNameType(),
  4178. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4179. return true;
  4180. return false;
  4181. }
  4182. // C++11 [dcl.meaning]p1:
  4183. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4184. // not begin with a decltype-specifer"
  4185. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4186. while (SpecLoc.getPrefix())
  4187. SpecLoc = SpecLoc.getPrefix();
  4188. if (dyn_cast_or_null<DecltypeType>(
  4189. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4190. Diag(Loc, diag::err_decltype_in_declarator)
  4191. << SpecLoc.getTypeLoc().getSourceRange();
  4192. return false;
  4193. }
  4194. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4195. MultiTemplateParamsArg TemplateParamLists) {
  4196. // TODO: consider using NameInfo for diagnostic.
  4197. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4198. DeclarationName Name = NameInfo.getName();
  4199. // All of these full declarators require an identifier. If it doesn't have
  4200. // one, the ParsedFreeStandingDeclSpec action should be used.
  4201. if (!Name) {
  4202. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4203. Diag(D.getDeclSpec().getLocStart(),
  4204. diag::err_declarator_need_ident)
  4205. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4206. return nullptr;
  4207. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4208. return nullptr;
  4209. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4210. // we find one that is.
  4211. ShadowMergeState MergeState = S->isForDeclScope() ?
  4212. ShadowMergeState_Possible : ShadowMergeState_Disallowed; // HLSL Change - check on original scope
  4213. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4214. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4215. S = S->getParent();
  4216. DeclContext *DC = CurContext;
  4217. if (D.getCXXScopeSpec().isInvalid())
  4218. D.setInvalidType();
  4219. else if (D.getCXXScopeSpec().isSet()) {
  4220. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4221. UPPC_DeclarationQualifier))
  4222. return nullptr;
  4223. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4224. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4225. if (!DC || isa<EnumDecl>(DC)) {
  4226. // If we could not compute the declaration context, it's because the
  4227. // declaration context is dependent but does not refer to a class,
  4228. // class template, or class template partial specialization. Complain
  4229. // and return early, to avoid the coming semantic disaster.
  4230. Diag(D.getIdentifierLoc(),
  4231. diag::err_template_qualified_declarator_no_match)
  4232. << D.getCXXScopeSpec().getScopeRep()
  4233. << D.getCXXScopeSpec().getRange();
  4234. return nullptr;
  4235. }
  4236. bool IsDependentContext = DC->isDependentContext();
  4237. if (!IsDependentContext &&
  4238. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4239. return nullptr;
  4240. // If a class is incomplete, do not parse entities inside it.
  4241. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4242. Diag(D.getIdentifierLoc(),
  4243. diag::err_member_def_undefined_record)
  4244. << Name << DC << D.getCXXScopeSpec().getRange();
  4245. return nullptr;
  4246. }
  4247. if (!D.getDeclSpec().isFriendSpecified()) {
  4248. if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
  4249. Name, D.getIdentifierLoc())) {
  4250. if (DC->isRecord())
  4251. return nullptr;
  4252. D.setInvalidType();
  4253. }
  4254. }
  4255. // Check whether we need to rebuild the type of the given
  4256. // declaration in the current instantiation.
  4257. if (EnteringContext && IsDependentContext &&
  4258. TemplateParamLists.size() != 0) {
  4259. ContextRAII SavedContext(*this, DC);
  4260. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4261. D.setInvalidType();
  4262. }
  4263. }
  4264. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4265. QualType R = TInfo->getType();
  4266. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4267. // If this is a typedef, we'll end up spewing multiple diagnostics.
  4268. // Just return early; it's safer. If this is a function, let the
  4269. // "constructor cannot have a return type" diagnostic handle it.
  4270. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4271. return nullptr;
  4272. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4273. UPPC_DeclarationType))
  4274. D.setInvalidType();
  4275. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4276. ForRedeclaration);
  4277. // See if this is a redefinition of a variable in the same scope.
  4278. if (!D.getCXXScopeSpec().isSet()) {
  4279. bool IsLinkageLookup = false;
  4280. bool CreateBuiltins = false;
  4281. // If the declaration we're planning to build will be a function
  4282. // or object with linkage, then look for another declaration with
  4283. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4284. //
  4285. // If the declaration we're planning to build will be declared with
  4286. // external linkage in the translation unit, create any builtin with
  4287. // the same name.
  4288. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4289. /* Do nothing*/;
  4290. else if (CurContext->isFunctionOrMethod() &&
  4291. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4292. R->isFunctionType())) {
  4293. IsLinkageLookup = true;
  4294. CreateBuiltins =
  4295. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4296. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4297. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4298. CreateBuiltins = true;
  4299. if (IsLinkageLookup)
  4300. Previous.clear(LookupRedeclarationWithLinkage);
  4301. LookupName(Previous, S, CreateBuiltins);
  4302. } else { // Something like "int foo::x;"
  4303. LookupQualifiedName(Previous, DC);
  4304. // C++ [dcl.meaning]p1:
  4305. // When the declarator-id is qualified, the declaration shall refer to a
  4306. // previously declared member of the class or namespace to which the
  4307. // qualifier refers (or, in the case of a namespace, of an element of the
  4308. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4309. // thereof; [...]
  4310. //
  4311. // Note that we already checked the context above, and that we do not have
  4312. // enough information to make sure that Previous contains the declaration
  4313. // we want to match. For example, given:
  4314. //
  4315. // class X {
  4316. // void f();
  4317. // void f(float);
  4318. // };
  4319. //
  4320. // void X::f(int) { } // ill-formed
  4321. //
  4322. // In this case, Previous will point to the overload set
  4323. // containing the two f's declared in X, but neither of them
  4324. // matches.
  4325. // C++ [dcl.meaning]p1:
  4326. // [...] the member shall not merely have been introduced by a
  4327. // using-declaration in the scope of the class or namespace nominated by
  4328. // the nested-name-specifier of the declarator-id.
  4329. RemoveUsingDecls(Previous);
  4330. }
  4331. if (Previous.isSingleResult() &&
  4332. Previous.getFoundDecl()->isTemplateParameter()) {
  4333. // Maybe we will complain about the shadowed template parameter.
  4334. if (!D.isInvalidType())
  4335. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4336. Previous.getFoundDecl());
  4337. // Just pretend that we didn't see the previous declaration.
  4338. Previous.clear();
  4339. }
  4340. // In C++, the previous declaration we find might be a tag type
  4341. // (class or enum). In this case, the new declaration will hide the
  4342. // tag type. Note that this does does not apply if we're declaring a
  4343. // typedef (C++ [dcl.typedef]p4).
  4344. if (Previous.isSingleTagDecl() &&
  4345. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
  4346. Previous.clear();
  4347. // Check that there are no default arguments other than in the parameters
  4348. // of a function declaration (C++ only).
  4349. if (getLangOpts().CPlusPlus)
  4350. CheckExtraCXXDefaultArguments(D);
  4351. // HLSL Change Starts
  4352. if (getLangOpts().HLSL) {
  4353. const bool IsParameterFalse = false;
  4354. if (!DiagnoseHLSLDecl(D, DC, TInfo, IsParameterFalse)) {
  4355. assert(D.isInvalidType() && "otherwise DiagnoseHLSLDecl failed but "
  4356. "didn't invalidate declaration");
  4357. return 0;
  4358. }
  4359. }
  4360. // HLSL Change Ends
  4361. NamedDecl *New;
  4362. bool AddToScope = true;
  4363. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4364. if (TemplateParamLists.size()) {
  4365. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4366. return nullptr;
  4367. }
  4368. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4369. } else if (R->isFunctionType()) {
  4370. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4371. TemplateParamLists,
  4372. AddToScope);
  4373. } else {
  4374. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4375. AddToScope, MergeState); // HLSL Change - add merge state
  4376. }
  4377. if (!New)
  4378. return nullptr;
  4379. TransferUnusualAttributes(D, New); // HLSL Change
  4380. // If this has an identifier and is not an invalid redeclaration or
  4381. // function template specialization, add it to the scope stack.
  4382. if (New->getDeclName() && AddToScope &&
  4383. !(D.isRedeclaration() && New->isInvalidDecl())) {
  4384. // Only make a locally-scoped extern declaration visible if it is the first
  4385. // declaration of this entity. Qualified lookup for such an entity should
  4386. // only find this declaration if there is no visible declaration of it.
  4387. bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
  4388. PushOnScopeChains(New, S, AddToContext);
  4389. if (!AddToContext)
  4390. CurContext->addHiddenDecl(New);
  4391. }
  4392. return New;
  4393. }
  4394. /// Helper method to turn variable array types into constant array
  4395. /// types in certain situations which would otherwise be errors (for
  4396. /// GCC compatibility).
  4397. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4398. ASTContext &Context,
  4399. bool &SizeIsNegative,
  4400. llvm::APSInt &Oversized) {
  4401. // This method tries to turn a variable array into a constant
  4402. // array even when the size isn't an ICE. This is necessary
  4403. // for compatibility with code that depends on gcc's buggy
  4404. // constant expression folding, like struct {char x[(int)(char*)2];}
  4405. SizeIsNegative = false;
  4406. Oversized = 0;
  4407. if (T->isDependentType())
  4408. return QualType();
  4409. QualifierCollector Qs;
  4410. const Type *Ty = Qs.strip(T);
  4411. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4412. QualType Pointee = PTy->getPointeeType();
  4413. QualType FixedType =
  4414. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4415. Oversized);
  4416. if (FixedType.isNull()) return FixedType;
  4417. FixedType = Context.getPointerType(FixedType);
  4418. return Qs.apply(Context, FixedType);
  4419. }
  4420. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4421. QualType Inner = PTy->getInnerType();
  4422. QualType FixedType =
  4423. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4424. Oversized);
  4425. if (FixedType.isNull()) return FixedType;
  4426. FixedType = Context.getParenType(FixedType);
  4427. return Qs.apply(Context, FixedType);
  4428. }
  4429. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4430. if (!VLATy)
  4431. return QualType();
  4432. // FIXME: We should probably handle this case
  4433. if (VLATy->getElementType()->isVariablyModifiedType())
  4434. return QualType();
  4435. llvm::APSInt Res;
  4436. if (!VLATy->getSizeExpr() ||
  4437. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  4438. return QualType();
  4439. // Check whether the array size is negative.
  4440. if (Res.isSigned() && Res.isNegative()) {
  4441. SizeIsNegative = true;
  4442. return QualType();
  4443. }
  4444. // Check whether the array is too large to be addressed.
  4445. unsigned ActiveSizeBits
  4446. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4447. Res);
  4448. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4449. Oversized = Res;
  4450. return QualType();
  4451. }
  4452. return Context.getConstantArrayType(VLATy->getElementType(),
  4453. Res, ArrayType::Normal, 0);
  4454. }
  4455. static void
  4456. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4457. SrcTL = SrcTL.getUnqualifiedLoc();
  4458. DstTL = DstTL.getUnqualifiedLoc();
  4459. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4460. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4461. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  4462. DstPTL.getPointeeLoc());
  4463. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  4464. return;
  4465. }
  4466. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  4467. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  4468. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  4469. DstPTL.getInnerLoc());
  4470. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  4471. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  4472. return;
  4473. }
  4474. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  4475. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  4476. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  4477. TypeLoc DstElemTL = DstATL.getElementLoc();
  4478. DstElemTL.initializeFullCopy(SrcElemTL);
  4479. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  4480. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  4481. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  4482. }
  4483. /// Helper method to turn variable array types into constant array
  4484. /// types in certain situations which would otherwise be errors (for
  4485. /// GCC compatibility).
  4486. static TypeSourceInfo*
  4487. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  4488. ASTContext &Context,
  4489. bool &SizeIsNegative,
  4490. llvm::APSInt &Oversized) {
  4491. QualType FixedTy
  4492. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  4493. SizeIsNegative, Oversized);
  4494. if (FixedTy.isNull())
  4495. return nullptr;
  4496. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  4497. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  4498. FixedTInfo->getTypeLoc());
  4499. return FixedTInfo;
  4500. }
  4501. /// \brief Register the given locally-scoped extern "C" declaration so
  4502. /// that it can be found later for redeclarations. We include any extern "C"
  4503. /// declaration that is not visible in the translation unit here, not just
  4504. /// function-scope declarations.
  4505. void
  4506. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  4507. if (!getLangOpts().CPlusPlus &&
  4508. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  4509. // Don't need to track declarations in the TU in C.
  4510. return;
  4511. // Note that we have a locally-scoped external with this name.
  4512. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  4513. }
  4514. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  4515. // FIXME: We can have multiple results via __attribute__((overloadable)).
  4516. auto Result = Context.getExternCContextDecl()->lookup(Name);
  4517. return Result.empty() ? nullptr : *Result.begin();
  4518. }
  4519. /// \brief Diagnose function specifiers on a declaration of an identifier that
  4520. /// does not identify a function.
  4521. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  4522. // FIXME: We should probably indicate the identifier in question to avoid
  4523. // confusion for constructs like "inline int a(), b;"
  4524. if (DS.isInlineSpecified())
  4525. Diag(DS.getInlineSpecLoc(),
  4526. diag::err_inline_non_function);
  4527. if (DS.isVirtualSpecified())
  4528. Diag(DS.getVirtualSpecLoc(),
  4529. diag::err_virtual_non_function);
  4530. if (DS.isExplicitSpecified())
  4531. Diag(DS.getExplicitSpecLoc(),
  4532. diag::err_explicit_non_function);
  4533. if (DS.isNoreturnSpecified())
  4534. Diag(DS.getNoreturnSpecLoc(),
  4535. diag::err_noreturn_non_function);
  4536. }
  4537. NamedDecl*
  4538. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  4539. TypeSourceInfo *TInfo, LookupResult &Previous) {
  4540. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  4541. if (D.getCXXScopeSpec().isSet()) {
  4542. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  4543. << D.getCXXScopeSpec().getRange();
  4544. D.setInvalidType();
  4545. // Pretend we didn't see the scope specifier.
  4546. DC = CurContext;
  4547. Previous.clear();
  4548. }
  4549. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  4550. if (D.getDeclSpec().isConstexprSpecified())
  4551. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  4552. << 1;
  4553. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  4554. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  4555. << D.getName().getSourceRange();
  4556. return nullptr;
  4557. }
  4558. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  4559. if (!NewTD) return nullptr;
  4560. // Handle attributes prior to checking for duplicates in MergeVarDecl
  4561. ProcessDeclAttributes(S, NewTD, D);
  4562. CheckTypedefForVariablyModifiedType(S, NewTD);
  4563. bool Redeclaration = D.isRedeclaration();
  4564. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  4565. D.setRedeclaration(Redeclaration);
  4566. return ND;
  4567. }
  4568. void
  4569. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  4570. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  4571. // then it shall have block scope.
  4572. // Note that variably modified types must be fixed before merging the decl so
  4573. // that redeclarations will match.
  4574. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  4575. QualType T = TInfo->getType();
  4576. if (T->isVariablyModifiedType()) {
  4577. getCurFunction()->setHasBranchProtectedScope();
  4578. if (S->getFnParent() == nullptr) {
  4579. bool SizeIsNegative;
  4580. llvm::APSInt Oversized;
  4581. TypeSourceInfo *FixedTInfo =
  4582. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  4583. SizeIsNegative,
  4584. Oversized);
  4585. if (FixedTInfo) {
  4586. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  4587. NewTD->setTypeSourceInfo(FixedTInfo);
  4588. } else {
  4589. if (SizeIsNegative)
  4590. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  4591. else if (T->isVariableArrayType())
  4592. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  4593. else if (Oversized.getBoolValue())
  4594. Diag(NewTD->getLocation(), diag::err_array_too_large)
  4595. << Oversized.toString(10);
  4596. else
  4597. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  4598. NewTD->setInvalidDecl();
  4599. }
  4600. }
  4601. }
  4602. }
  4603. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  4604. /// declares a typedef-name, either using the 'typedef' type specifier or via
  4605. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  4606. NamedDecl*
  4607. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  4608. LookupResult &Previous, bool &Redeclaration) {
  4609. // Merge the decl with the existing one if appropriate. If the decl is
  4610. // in an outer scope, it isn't the same thing.
  4611. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  4612. /*AllowInlineNamespace*/false);
  4613. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  4614. if (!Previous.empty()) {
  4615. Redeclaration = true;
  4616. MergeTypedefNameDecl(NewTD, Previous);
  4617. }
  4618. // If this is the C FILE type, notify the AST context.
  4619. if (IdentifierInfo *II = NewTD->getIdentifier())
  4620. if (!NewTD->isInvalidDecl() &&
  4621. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  4622. if (II->isStr("FILE"))
  4623. Context.setFILEDecl(NewTD);
  4624. else if (II->isStr("jmp_buf"))
  4625. Context.setjmp_bufDecl(NewTD);
  4626. else if (II->isStr("sigjmp_buf"))
  4627. Context.setsigjmp_bufDecl(NewTD);
  4628. else if (II->isStr("ucontext_t"))
  4629. Context.setucontext_tDecl(NewTD);
  4630. }
  4631. return NewTD;
  4632. }
  4633. /// \brief Determines whether the given declaration is an out-of-scope
  4634. /// previous declaration.
  4635. ///
  4636. /// This routine should be invoked when name lookup has found a
  4637. /// previous declaration (PrevDecl) that is not in the scope where a
  4638. /// new declaration by the same name is being introduced. If the new
  4639. /// declaration occurs in a local scope, previous declarations with
  4640. /// linkage may still be considered previous declarations (C99
  4641. /// 6.2.2p4-5, C++ [basic.link]p6).
  4642. ///
  4643. /// \param PrevDecl the previous declaration found by name
  4644. /// lookup
  4645. ///
  4646. /// \param DC the context in which the new declaration is being
  4647. /// declared.
  4648. ///
  4649. /// \returns true if PrevDecl is an out-of-scope previous declaration
  4650. /// for a new delcaration with the same name.
  4651. static bool
  4652. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  4653. ASTContext &Context) {
  4654. if (!PrevDecl)
  4655. return false;
  4656. if (!PrevDecl->hasLinkage())
  4657. return false;
  4658. if (Context.getLangOpts().CPlusPlus) {
  4659. // C++ [basic.link]p6:
  4660. // If there is a visible declaration of an entity with linkage
  4661. // having the same name and type, ignoring entities declared
  4662. // outside the innermost enclosing namespace scope, the block
  4663. // scope declaration declares that same entity and receives the
  4664. // linkage of the previous declaration.
  4665. DeclContext *OuterContext = DC->getRedeclContext();
  4666. if (!OuterContext->isFunctionOrMethod())
  4667. // This rule only applies to block-scope declarations.
  4668. return false;
  4669. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  4670. if (PrevOuterContext->isRecord())
  4671. // We found a member function: ignore it.
  4672. return false;
  4673. // Find the innermost enclosing namespace for the new and
  4674. // previous declarations.
  4675. OuterContext = OuterContext->getEnclosingNamespaceContext();
  4676. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  4677. // The previous declaration is in a different namespace, so it
  4678. // isn't the same function.
  4679. if (!OuterContext->Equals(PrevOuterContext))
  4680. return false;
  4681. }
  4682. return true;
  4683. }
  4684. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  4685. CXXScopeSpec &SS = D.getCXXScopeSpec();
  4686. if (!SS.isSet()) return;
  4687. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  4688. }
  4689. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  4690. QualType type = decl->getType();
  4691. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  4692. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  4693. // Various kinds of declaration aren't allowed to be __autoreleasing.
  4694. unsigned kind = -1U;
  4695. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4696. if (var->hasAttr<BlocksAttr>())
  4697. kind = 0; // __block
  4698. else if (!var->hasLocalStorage())
  4699. kind = 1; // global
  4700. } else if (isa<ObjCIvarDecl>(decl)) {
  4701. kind = 3; // ivar
  4702. } else if (isa<FieldDecl>(decl)) {
  4703. kind = 2; // field
  4704. }
  4705. if (kind != -1U) {
  4706. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  4707. << kind;
  4708. }
  4709. } else if (lifetime == Qualifiers::OCL_None) {
  4710. // Try to infer lifetime.
  4711. if (!type->isObjCLifetimeType())
  4712. return false;
  4713. lifetime = type->getObjCARCImplicitLifetime();
  4714. type = Context.getLifetimeQualifiedType(type, lifetime);
  4715. decl->setType(type);
  4716. }
  4717. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4718. // Thread-local variables cannot have lifetime.
  4719. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  4720. var->getTLSKind()) {
  4721. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  4722. << var->getType();
  4723. return true;
  4724. }
  4725. }
  4726. return false;
  4727. }
  4728. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  4729. // Ensure that an auto decl is deduced otherwise the checks below might cache
  4730. // the wrong linkage.
  4731. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  4732. // 'weak' only applies to declarations with external linkage.
  4733. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  4734. if (!ND.isExternallyVisible()) {
  4735. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  4736. ND.dropAttr<WeakAttr>();
  4737. }
  4738. }
  4739. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  4740. if (ND.isExternallyVisible()) {
  4741. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  4742. ND.dropAttr<WeakRefAttr>();
  4743. ND.dropAttr<AliasAttr>();
  4744. }
  4745. }
  4746. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  4747. if (VD->hasInit()) {
  4748. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  4749. assert(VD->isThisDeclarationADefinition() &&
  4750. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  4751. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
  4752. VD->dropAttr<AliasAttr>();
  4753. }
  4754. }
  4755. }
  4756. // 'selectany' only applies to externally visible variable declarations.
  4757. // It does not apply to functions.
  4758. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  4759. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  4760. S.Diag(Attr->getLocation(),
  4761. diag::err_attribute_selectany_non_extern_data);
  4762. ND.dropAttr<SelectAnyAttr>();
  4763. }
  4764. }
  4765. // dll attributes require external linkage.
  4766. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  4767. if (!ND.isExternallyVisible()) {
  4768. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  4769. << &ND << Attr;
  4770. ND.setInvalidDecl();
  4771. }
  4772. }
  4773. }
  4774. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  4775. NamedDecl *NewDecl,
  4776. bool IsSpecialization) {
  4777. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
  4778. OldDecl = OldTD->getTemplatedDecl();
  4779. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
  4780. NewDecl = NewTD->getTemplatedDecl();
  4781. if (!OldDecl || !NewDecl)
  4782. return;
  4783. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  4784. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  4785. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  4786. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  4787. // dllimport and dllexport are inheritable attributes so we have to exclude
  4788. // inherited attribute instances.
  4789. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  4790. (NewExportAttr && !NewExportAttr->isInherited());
  4791. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  4792. // the only exception being explicit specializations.
  4793. // Implicitly generated declarations are also excluded for now because there
  4794. // is no other way to switch these to use dllimport or dllexport.
  4795. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  4796. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  4797. // Allow with a warning for free functions and global variables.
  4798. bool JustWarn = false;
  4799. if (!OldDecl->isCXXClassMember()) {
  4800. auto *VD = dyn_cast<VarDecl>(OldDecl);
  4801. if (VD && !VD->getDescribedVarTemplate())
  4802. JustWarn = true;
  4803. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  4804. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  4805. JustWarn = true;
  4806. }
  4807. // We cannot change a declaration that's been used because IR has already
  4808. // been emitted. Dllimported functions will still work though (modulo
  4809. // address equality) as they can use the thunk.
  4810. if (OldDecl->isUsed())
  4811. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  4812. JustWarn = false;
  4813. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  4814. : diag::err_attribute_dll_redeclaration;
  4815. S.Diag(NewDecl->getLocation(), DiagID)
  4816. << NewDecl
  4817. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  4818. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  4819. if (!JustWarn) {
  4820. NewDecl->setInvalidDecl();
  4821. return;
  4822. }
  4823. }
  4824. // A redeclaration is not allowed to drop a dllimport attribute, the only
  4825. // exceptions being inline function definitions, local extern declarations,
  4826. // and qualified friend declarations.
  4827. // NB: MSVC converts such a declaration to dllexport.
  4828. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  4829. if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
  4830. // Ignore static data because out-of-line definitions are diagnosed
  4831. // separately.
  4832. IsStaticDataMember = VD->isStaticDataMember();
  4833. else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  4834. IsInline = FD->isInlined();
  4835. IsQualifiedFriend = FD->getQualifier() &&
  4836. FD->getFriendObjectKind() == Decl::FOK_Declared;
  4837. }
  4838. if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
  4839. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  4840. S.Diag(NewDecl->getLocation(),
  4841. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  4842. << NewDecl << OldImportAttr;
  4843. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  4844. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  4845. OldDecl->dropAttr<DLLImportAttr>();
  4846. NewDecl->dropAttr<DLLImportAttr>();
  4847. } else if (IsInline && OldImportAttr &&
  4848. !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  4849. // In MinGW, seeing a function declared inline drops the dllimport attribute.
  4850. OldDecl->dropAttr<DLLImportAttr>();
  4851. NewDecl->dropAttr<DLLImportAttr>();
  4852. S.Diag(NewDecl->getLocation(),
  4853. diag::warn_dllimport_dropped_from_inline_function)
  4854. << NewDecl << OldImportAttr;
  4855. }
  4856. }
  4857. /// Given that we are within the definition of the given function,
  4858. /// will that definition behave like C99's 'inline', where the
  4859. /// definition is discarded except for optimization purposes?
  4860. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  4861. // Try to avoid calling GetGVALinkageForFunction.
  4862. // All cases of this require the 'inline' keyword.
  4863. if (!FD->isInlined()) return false;
  4864. // This is only possible in C++ with the gnu_inline attribute.
  4865. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  4866. return false;
  4867. // Okay, go ahead and call the relatively-more-expensive function.
  4868. #ifndef NDEBUG
  4869. // AST quite reasonably asserts that it's working on a function
  4870. // definition. We don't really have a way to tell it that we're
  4871. // currently defining the function, so just lie to it in +Asserts
  4872. // builds. This is an awful hack.
  4873. FD->setLazyBody(1);
  4874. #endif
  4875. bool isC99Inline =
  4876. S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  4877. #ifndef NDEBUG
  4878. FD->setLazyBody(0);
  4879. #endif
  4880. return isC99Inline;
  4881. }
  4882. /// Determine whether a variable is extern "C" prior to attaching
  4883. /// an initializer. We can't just call isExternC() here, because that
  4884. /// will also compute and cache whether the declaration is externally
  4885. /// visible, which might change when we attach the initializer.
  4886. ///
  4887. /// This can only be used if the declaration is known to not be a
  4888. /// redeclaration of an internal linkage declaration.
  4889. ///
  4890. /// For instance:
  4891. ///
  4892. /// auto x = []{};
  4893. ///
  4894. /// Attaching the initializer here makes this declaration not externally
  4895. /// visible, because its type has internal linkage.
  4896. ///
  4897. /// FIXME: This is a hack.
  4898. template<typename T>
  4899. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  4900. if (S.getLangOpts().CPlusPlus) {
  4901. // In C++, the overloadable attribute negates the effects of extern "C".
  4902. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  4903. return false;
  4904. }
  4905. return D->isExternC();
  4906. }
  4907. static bool shouldConsiderLinkage(const VarDecl *VD) {
  4908. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  4909. if (DC->isFunctionOrMethod())
  4910. return VD->hasExternalStorage();
  4911. if (DC->isFileContext())
  4912. return true;
  4913. if (DC->isRecord())
  4914. return false;
  4915. llvm_unreachable("Unexpected context");
  4916. }
  4917. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  4918. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  4919. if (DC->isFileContext() || DC->isFunctionOrMethod())
  4920. return true;
  4921. if (DC->isRecord())
  4922. return false;
  4923. llvm_unreachable("Unexpected context");
  4924. }
  4925. static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
  4926. AttributeList::Kind Kind) {
  4927. for (const AttributeList *L = AttrList; L; L = L->getNext())
  4928. if (L->getKind() == Kind)
  4929. return true;
  4930. return false;
  4931. }
  4932. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  4933. AttributeList::Kind Kind) {
  4934. // Check decl attributes on the DeclSpec.
  4935. if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
  4936. return true;
  4937. // Walk the declarator structure, checking decl attributes that were in a type
  4938. // position to the decl itself.
  4939. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  4940. if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
  4941. return true;
  4942. }
  4943. // Finally, check attributes on the decl itself.
  4944. return hasParsedAttr(S, PD.getAttributes(), Kind);
  4945. }
  4946. /// Adjust the \c DeclContext for a function or variable that might be a
  4947. /// function-local external declaration.
  4948. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  4949. if (!DC->isFunctionOrMethod())
  4950. return false;
  4951. // If this is a local extern function or variable declared within a function
  4952. // template, don't add it into the enclosing namespace scope until it is
  4953. // instantiated; it might have a dependent type right now.
  4954. if (DC->isDependentContext())
  4955. return true;
  4956. // C++11 [basic.link]p7:
  4957. // When a block scope declaration of an entity with linkage is not found to
  4958. // refer to some other declaration, then that entity is a member of the
  4959. // innermost enclosing namespace.
  4960. //
  4961. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  4962. // semantically-enclosing namespace, not a lexically-enclosing one.
  4963. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  4964. DC = DC->getParent();
  4965. return true;
  4966. }
  4967. /// \brief Returns true if given declaration is TU-scoped and externally
  4968. /// visible.
  4969. static bool isDeclTUScopedExternallyVisible(const Decl *D) {
  4970. if (auto *FD = dyn_cast<FunctionDecl>(D))
  4971. return (FD->getDeclContext()->isTranslationUnit() || FD->isExternC()) &&
  4972. FD->hasExternalFormalLinkage();
  4973. else if (auto *VD = dyn_cast<VarDecl>(D))
  4974. return (VD->getDeclContext()->isTranslationUnit() || VD->isExternC()) &&
  4975. VD->hasExternalFormalLinkage();
  4976. llvm_unreachable("Unknown type of decl!");
  4977. }
  4978. NamedDecl *
  4979. Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  4980. TypeSourceInfo *TInfo, LookupResult &Previous,
  4981. MultiTemplateParamsArg TemplateParamLists,
  4982. bool &AddToScope, ShadowMergeState MergeState) { // HLSL Change - add merge state
  4983. QualType R = TInfo->getType();
  4984. DeclarationName Name = GetNameForDeclarator(D).getName();
  4985. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  4986. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  4987. // dllimport globals without explicit storage class are treated as extern. We
  4988. // have to change the storage class this early to get the right DeclContext.
  4989. if (SC == SC_None && !DC->isRecord() &&
  4990. hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
  4991. !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
  4992. SC = SC_Extern;
  4993. DeclContext *OriginalDC = DC;
  4994. bool IsLocalExternDecl = SC == SC_Extern &&
  4995. adjustContextForLocalExternDecl(DC);
  4996. if (getLangOpts().OpenCL) {
  4997. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  4998. QualType NR = R;
  4999. while (NR->isPointerType()) {
  5000. if (NR->isFunctionPointerType()) {
  5001. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
  5002. D.setInvalidType();
  5003. break;
  5004. }
  5005. NR = NR->getPointeeType();
  5006. }
  5007. if (!getOpenCLOptions().cl_khr_fp16) {
  5008. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5009. // half array type (unless the cl_khr_fp16 extension is enabled).
  5010. if (Context.getBaseElementType(R)->isHalfType()) {
  5011. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5012. D.setInvalidType();
  5013. }
  5014. }
  5015. }
  5016. if (SCSpec == DeclSpec::SCS_mutable) {
  5017. // mutable can only appear on non-static class members, so it's always
  5018. // an error here
  5019. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5020. D.setInvalidType();
  5021. SC = SC_None;
  5022. }
  5023. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5024. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5025. D.getDeclSpec().getStorageClassSpecLoc())) {
  5026. // In C++11, the 'register' storage class specifier is deprecated.
  5027. // Suppress the warning in system macros, it's used in macros in some
  5028. // popular C system headers, such as in glibc's htonl() macro.
  5029. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5030. diag::warn_deprecated_register)
  5031. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5032. }
  5033. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5034. if (!II) {
  5035. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
  5036. << Name;
  5037. return nullptr;
  5038. }
  5039. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5040. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5041. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5042. // appear in the declaration specifiers in an external declaration.
  5043. // Global Register+Asm is a GNU extension we support.
  5044. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5045. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5046. D.setInvalidType();
  5047. }
  5048. }
  5049. if (getLangOpts().OpenCL) {
  5050. // Set up the special work-group-local storage class for variables in the
  5051. // OpenCL __local address space.
  5052. if (R.getAddressSpace() == LangAS::opencl_local) {
  5053. SC = SC_OpenCLWorkGroupLocal;
  5054. }
  5055. // OpenCL v1.2 s6.9.b p4:
  5056. // The sampler type cannot be used with the __local and __global address
  5057. // space qualifiers.
  5058. if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
  5059. R.getAddressSpace() == LangAS::opencl_global)) {
  5060. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5061. }
  5062. // OpenCL 1.2 spec, p6.9 r:
  5063. // The event type cannot be used to declare a program scope variable.
  5064. // The event type cannot be used with the __local, __constant and __global
  5065. // address space qualifiers.
  5066. if (R->isEventT()) {
  5067. if (S->getParent() == nullptr) {
  5068. Diag(D.getLocStart(), diag::err_event_t_global_var);
  5069. D.setInvalidType();
  5070. }
  5071. if (R.getAddressSpace()) {
  5072. Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
  5073. D.setInvalidType();
  5074. }
  5075. }
  5076. }
  5077. bool IsExplicitSpecialization = false;
  5078. bool IsVariableTemplateSpecialization = false;
  5079. bool IsPartialSpecialization = false;
  5080. bool IsVariableTemplate = false;
  5081. VarDecl *NewVD = nullptr;
  5082. VarTemplateDecl *NewTemplate = nullptr;
  5083. TemplateParameterList *TemplateParams = nullptr;
  5084. if (!getLangOpts().CPlusPlus) {
  5085. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5086. D.getIdentifierLoc(), II,
  5087. R, TInfo, SC);
  5088. if (D.isInvalidType())
  5089. NewVD->setInvalidDecl();
  5090. } else {
  5091. bool Invalid = false;
  5092. if (DC->isRecord() && !CurContext->isRecord()) {
  5093. // This is an out-of-line definition of a static data member.
  5094. switch (SC) {
  5095. case SC_None:
  5096. break;
  5097. case SC_Static:
  5098. if (!getLangOpts().HLSL) // HLSL Change: We had to set SC_Static for
  5099. // static data member to distinguish it from
  5100. // global constant variable.
  5101. // So we ignore this warning.
  5102. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5103. diag::err_static_out_of_line)
  5104. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5105. break;
  5106. case SC_Auto:
  5107. case SC_Register:
  5108. case SC_Extern:
  5109. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5110. // to names of variables declared in a block or to function parameters.
  5111. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5112. // of class members
  5113. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5114. diag::err_storage_class_for_static_member)
  5115. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5116. break;
  5117. case SC_PrivateExtern:
  5118. llvm_unreachable("C storage class in c++!");
  5119. case SC_OpenCLWorkGroupLocal:
  5120. llvm_unreachable("OpenCL storage class in c++!");
  5121. }
  5122. }
  5123. if (SC == SC_Static && CurContext->isRecord()) {
  5124. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5125. if (RD->isLocalClass())
  5126. Diag(D.getIdentifierLoc(),
  5127. diag::err_static_data_member_not_allowed_in_local_class)
  5128. << Name << RD->getDeclName();
  5129. // C++98 [class.union]p1: If a union contains a static data member,
  5130. // the program is ill-formed. C++11 drops this restriction.
  5131. if (RD->isUnion())
  5132. Diag(D.getIdentifierLoc(),
  5133. getLangOpts().CPlusPlus11
  5134. ? diag::warn_cxx98_compat_static_data_member_in_union
  5135. : diag::ext_static_data_member_in_union) << Name;
  5136. // We conservatively disallow static data members in anonymous structs.
  5137. else if (!RD->getDeclName())
  5138. Diag(D.getIdentifierLoc(),
  5139. diag::err_static_data_member_not_allowed_in_anon_struct)
  5140. << Name << RD->isUnion();
  5141. }
  5142. }
  5143. // Match up the template parameter lists with the scope specifier, then
  5144. // determine whether we have a template or a template specialization.
  5145. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5146. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  5147. D.getCXXScopeSpec(),
  5148. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  5149. ? D.getName().TemplateId
  5150. : nullptr,
  5151. TemplateParamLists,
  5152. /*never a friend*/ false, IsExplicitSpecialization, Invalid);
  5153. if (TemplateParams) {
  5154. if (!TemplateParams->size() &&
  5155. D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  5156. // There is an extraneous 'template<>' for this variable. Complain
  5157. // about it, but allow the declaration of the variable.
  5158. Diag(TemplateParams->getTemplateLoc(),
  5159. diag::err_template_variable_noparams)
  5160. << II
  5161. << SourceRange(TemplateParams->getTemplateLoc(),
  5162. TemplateParams->getRAngleLoc());
  5163. TemplateParams = nullptr;
  5164. } else {
  5165. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  5166. // This is an explicit specialization or a partial specialization.
  5167. // FIXME: Check that we can declare a specialization here.
  5168. IsVariableTemplateSpecialization = true;
  5169. IsPartialSpecialization = TemplateParams->size() > 0;
  5170. } else { // if (TemplateParams->size() > 0)
  5171. // This is a template declaration.
  5172. IsVariableTemplate = true;
  5173. // Check that we can declare a template here.
  5174. if (CheckTemplateDeclScope(S, TemplateParams))
  5175. return nullptr;
  5176. // Only C++1y supports variable templates (N3651).
  5177. Diag(D.getIdentifierLoc(),
  5178. getLangOpts().CPlusPlus14
  5179. ? diag::warn_cxx11_compat_variable_template
  5180. : diag::ext_variable_template);
  5181. }
  5182. }
  5183. } else {
  5184. assert(
  5185. (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
  5186. "should have a 'template<>' for this decl");
  5187. }
  5188. if (IsVariableTemplateSpecialization) {
  5189. SourceLocation TemplateKWLoc =
  5190. TemplateParamLists.size() > 0
  5191. ? TemplateParamLists[0]->getTemplateLoc()
  5192. : SourceLocation();
  5193. DeclResult Res = ActOnVarTemplateSpecialization(
  5194. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5195. IsPartialSpecialization);
  5196. if (Res.isInvalid())
  5197. return nullptr;
  5198. NewVD = cast<VarDecl>(Res.get());
  5199. AddToScope = false;
  5200. } else
  5201. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5202. D.getIdentifierLoc(), II, R, TInfo, SC);
  5203. // If this is supposed to be a variable template, create it as such.
  5204. if (IsVariableTemplate) {
  5205. NewTemplate =
  5206. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5207. TemplateParams, NewVD);
  5208. NewVD->setDescribedVarTemplate(NewTemplate);
  5209. }
  5210. // If this decl has an auto type in need of deduction, make a note of the
  5211. // Decl so we can diagnose uses of it in its own initializer.
  5212. if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
  5213. ParsingInitForAutoVars.insert(NewVD);
  5214. if (D.isInvalidType() || Invalid) {
  5215. NewVD->setInvalidDecl();
  5216. if (NewTemplate)
  5217. NewTemplate->setInvalidDecl();
  5218. }
  5219. SetNestedNameSpecifier(NewVD, D);
  5220. // If we have any template parameter lists that don't directly belong to
  5221. // the variable (matching the scope specifier), store them.
  5222. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5223. if (TemplateParamLists.size() > VDTemplateParamLists)
  5224. NewVD->setTemplateParameterListsInfo(
  5225. Context, TemplateParamLists.size() - VDTemplateParamLists,
  5226. TemplateParamLists.data());
  5227. if (D.getDeclSpec().isConstexprSpecified())
  5228. NewVD->setConstexpr(true);
  5229. }
  5230. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5231. // lexical context will be different from the semantic context.
  5232. NewVD->setLexicalDeclContext(CurContext);
  5233. if (NewTemplate)
  5234. NewTemplate->setLexicalDeclContext(CurContext);
  5235. if (IsLocalExternDecl)
  5236. NewVD->setLocalExternDecl();
  5237. bool EmitTLSUnsupportedError = false;
  5238. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5239. // C++11 [dcl.stc]p4:
  5240. // When thread_local is applied to a variable of block scope the
  5241. // storage-class-specifier static is implied if it does not appear
  5242. // explicitly.
  5243. // Core issue: 'static' is not implied if the variable is declared
  5244. // 'extern'.
  5245. if (NewVD->hasLocalStorage() &&
  5246. (SCSpec != DeclSpec::SCS_unspecified ||
  5247. TSCS != DeclSpec::TSCS_thread_local ||
  5248. !DC->isFunctionOrMethod()))
  5249. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5250. diag::err_thread_non_global)
  5251. << DeclSpec::getSpecifierName(TSCS);
  5252. else if (!Context.getTargetInfo().isTLSSupported()) {
  5253. if (getLangOpts().CUDA) {
  5254. // Postpone error emission until we've collected attributes required to
  5255. // figure out whether it's a host or device variable and whether the
  5256. // error should be ignored.
  5257. EmitTLSUnsupportedError = true;
  5258. // We still need to mark the variable as TLS so it shows up in AST with
  5259. // proper storage class for other tools to use even if we're not going
  5260. // to emit any code for it.
  5261. NewVD->setTSCSpec(TSCS);
  5262. } else
  5263. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5264. diag::err_thread_unsupported);
  5265. } else
  5266. NewVD->setTSCSpec(TSCS);
  5267. }
  5268. // C99 6.7.4p3
  5269. // An inline definition of a function with external linkage shall
  5270. // not contain a definition of a modifiable object with static or
  5271. // thread storage duration...
  5272. // We only apply this when the function is required to be defined
  5273. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5274. // that a local variable with thread storage duration still has to
  5275. // be marked 'static'. Also note that it's possible to get these
  5276. // semantics in C++ using __attribute__((gnu_inline)).
  5277. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5278. !NewVD->getType().isConstQualified()) {
  5279. FunctionDecl *CurFD = getCurFunctionDecl();
  5280. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5281. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5282. diag::warn_static_local_in_extern_inline);
  5283. MaybeSuggestAddingStaticToDecl(CurFD);
  5284. }
  5285. }
  5286. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5287. if (IsVariableTemplateSpecialization)
  5288. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5289. << (IsPartialSpecialization ? 1 : 0)
  5290. << FixItHint::CreateRemoval(
  5291. D.getDeclSpec().getModulePrivateSpecLoc());
  5292. else if (IsExplicitSpecialization)
  5293. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5294. << 2
  5295. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5296. else if (NewVD->hasLocalStorage())
  5297. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5298. << 0 << NewVD->getDeclName()
  5299. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5300. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5301. else {
  5302. NewVD->setModulePrivate();
  5303. if (NewTemplate)
  5304. NewTemplate->setModulePrivate();
  5305. }
  5306. }
  5307. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5308. ProcessDeclAttributes(S, NewVD, D);
  5309. if (getLangOpts().CUDA) {
  5310. if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
  5311. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5312. diag::err_thread_unsupported);
  5313. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  5314. // storage [duration]."
  5315. if (SC == SC_None && S->getFnParent() != nullptr &&
  5316. (NewVD->hasAttr<CUDASharedAttr>() ||
  5317. NewVD->hasAttr<CUDAConstantAttr>())) {
  5318. NewVD->setStorageClass(SC_Static);
  5319. }
  5320. }
  5321. // Ensure that dllimport globals without explicit storage class are treated as
  5322. // extern. The storage class is set above using parsed attributes. Now we can
  5323. // check the VarDecl itself.
  5324. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  5325. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  5326. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  5327. // In auto-retain/release, infer strong retension for variables of
  5328. // retainable type.
  5329. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  5330. NewVD->setInvalidDecl();
  5331. // Handle GNU asm-label extension (encoded as an attribute).
  5332. if (Expr *E = (Expr*)D.getAsmLabel()) {
  5333. // The parser guarantees this is a string.
  5334. StringLiteral *SE = cast<StringLiteral>(E);
  5335. StringRef Label = SE->getString();
  5336. if (S->getFnParent() != nullptr) {
  5337. switch (SC) {
  5338. case SC_None:
  5339. case SC_Auto:
  5340. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  5341. break;
  5342. case SC_Register:
  5343. // Local Named register
  5344. if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
  5345. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5346. break;
  5347. case SC_Static:
  5348. case SC_Extern:
  5349. case SC_PrivateExtern:
  5350. case SC_OpenCLWorkGroupLocal:
  5351. break;
  5352. }
  5353. } else if (SC == SC_Register) {
  5354. // Global Named register
  5355. if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
  5356. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5357. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  5358. Diag(D.getLocStart(), diag::err_asm_bad_register_type);
  5359. NewVD->setInvalidDecl(true);
  5360. }
  5361. }
  5362. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  5363. Context, Label, 0));
  5364. } else if (!ExtnameUndeclaredIdentifiers.empty() &&
  5365. isDeclTUScopedExternallyVisible(NewVD)) {
  5366. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  5367. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  5368. if (I != ExtnameUndeclaredIdentifiers.end()) {
  5369. NewVD->addAttr(I->second);
  5370. ExtnameUndeclaredIdentifiers.erase(I);
  5371. }
  5372. }
  5373. // Diagnose shadowed variables before filtering for scope.
  5374. if (D.getCXXScopeSpec().isEmpty())
  5375. CheckShadow(S, NewVD, Previous);
  5376. // Don't consider existing declarations that are in a different
  5377. // scope and are out-of-semantic-context declarations (if the new
  5378. // declaration has linkage).
  5379. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  5380. D.getCXXScopeSpec().isNotEmpty() ||
  5381. IsExplicitSpecialization ||
  5382. IsVariableTemplateSpecialization);
  5383. // Check whether the previous declaration is in the same block scope. This
  5384. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  5385. if (getLangOpts().CPlusPlus &&
  5386. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  5387. NewVD->setPreviousDeclInSameBlockScope(
  5388. Previous.isSingleResult() && !Previous.isShadowed() &&
  5389. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  5390. if (!getLangOpts().CPlusPlus) {
  5391. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  5392. } else {
  5393. // If this is an explicit specialization of a static data member, check it.
  5394. if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
  5395. CheckMemberSpecialization(NewVD, Previous))
  5396. NewVD->setInvalidDecl();
  5397. // Merge the decl with the existing one if appropriate.
  5398. if (!Previous.empty()) {
  5399. if (Previous.isSingleResult() &&
  5400. isa<FieldDecl>(Previous.getFoundDecl()) &&
  5401. D.getCXXScopeSpec().isSet()) {
  5402. // The user tried to define a non-static data member
  5403. // out-of-line (C++ [dcl.meaning]p1).
  5404. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  5405. << D.getCXXScopeSpec().getRange();
  5406. Previous.clear();
  5407. NewVD->setInvalidDecl();
  5408. }
  5409. } else if (D.getCXXScopeSpec().isSet()) {
  5410. // No previous declaration in the qualifying scope.
  5411. Diag(D.getIdentifierLoc(), diag::err_no_member)
  5412. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  5413. << D.getCXXScopeSpec().getRange();
  5414. NewVD->setInvalidDecl();
  5415. }
  5416. if (!IsVariableTemplateSpecialization)
  5417. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous, MergeState)); // HLSL Change - add merge state
  5418. if (NewTemplate) {
  5419. VarTemplateDecl *PrevVarTemplate =
  5420. NewVD->getPreviousDecl()
  5421. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  5422. : nullptr;
  5423. // Check the template parameter list of this declaration, possibly
  5424. // merging in the template parameter list from the previous variable
  5425. // template declaration.
  5426. if (CheckTemplateParameterList(
  5427. TemplateParams,
  5428. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  5429. : nullptr,
  5430. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  5431. DC->isDependentContext())
  5432. ? TPC_ClassTemplateMember
  5433. : TPC_VarTemplate))
  5434. NewVD->setInvalidDecl();
  5435. // If we are providing an explicit specialization of a static variable
  5436. // template, make a note of that.
  5437. if (PrevVarTemplate &&
  5438. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  5439. PrevVarTemplate->setMemberSpecialization();
  5440. }
  5441. }
  5442. ProcessPragmaWeak(S, NewVD);
  5443. // If this is the first declaration of an extern C variable, update
  5444. // the map of such variables.
  5445. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  5446. isIncompleteDeclExternC(*this, NewVD))
  5447. RegisterLocallyScopedExternCDecl(NewVD, S);
  5448. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  5449. Decl *ManglingContextDecl;
  5450. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  5451. NewVD->getDeclContext(), ManglingContextDecl)) {
  5452. Context.setManglingNumber(
  5453. NewVD, MCtx->getManglingNumber(
  5454. NewVD, getMSManglingNumber(getLangOpts(), S)));
  5455. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  5456. }
  5457. }
  5458. if (D.isRedeclaration() && !Previous.empty()) {
  5459. checkDLLAttributeRedeclaration(
  5460. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
  5461. IsExplicitSpecialization);
  5462. }
  5463. if (NewTemplate) {
  5464. if (NewVD->isInvalidDecl())
  5465. NewTemplate->setInvalidDecl();
  5466. ActOnDocumentableDecl(NewTemplate);
  5467. return NewTemplate;
  5468. }
  5469. return NewVD;
  5470. }
  5471. /// \brief Diagnose variable or built-in function shadowing. Implements
  5472. /// -Wshadow.
  5473. ///
  5474. /// This method is called whenever a VarDecl is added to a "useful"
  5475. /// scope.
  5476. ///
  5477. /// \param S the scope in which the shadowing name is being declared
  5478. /// \param R the lookup of the name
  5479. ///
  5480. void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
  5481. // Return if warning is ignored.
  5482. if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
  5483. return;
  5484. // Don't diagnose declarations at file scope.
  5485. if (D->hasGlobalStorage())
  5486. return;
  5487. DeclContext *NewDC = D->getDeclContext();
  5488. // Only diagnose if we're shadowing an unambiguous field or variable.
  5489. if (R.getResultKind() != LookupResult::Found)
  5490. return;
  5491. NamedDecl* ShadowedDecl = R.getFoundDecl();
  5492. if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
  5493. return;
  5494. // Fields are not shadowed by variables in C++ static methods.
  5495. if (isa<FieldDecl>(ShadowedDecl))
  5496. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  5497. if (MD->isStatic())
  5498. return;
  5499. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  5500. if (shadowedVar->isExternC()) {
  5501. // For shadowing external vars, make sure that we point to the global
  5502. // declaration, not a locally scoped extern declaration.
  5503. for (auto I : shadowedVar->redecls())
  5504. if (I->isFileVarDecl()) {
  5505. ShadowedDecl = I;
  5506. break;
  5507. }
  5508. }
  5509. DeclContext *OldDC = ShadowedDecl->getDeclContext();
  5510. // Only warn about certain kinds of shadowing for class members.
  5511. if (NewDC && NewDC->isRecord()) {
  5512. // In particular, don't warn about shadowing non-class members.
  5513. if (!OldDC->isRecord())
  5514. return;
  5515. // TODO: should we warn about static data members shadowing
  5516. // static data members from base classes?
  5517. // TODO: don't diagnose for inaccessible shadowed members.
  5518. // This is hard to do perfectly because we might friend the
  5519. // shadowing context, but that's just a false negative.
  5520. }
  5521. // Determine what kind of declaration we're shadowing.
  5522. unsigned Kind;
  5523. if (isa<RecordDecl>(OldDC)) {
  5524. if (isa<FieldDecl>(ShadowedDecl))
  5525. Kind = 3; // field
  5526. else
  5527. Kind = 2; // static data member
  5528. } else if (OldDC->isFileContext())
  5529. Kind = 1; // global
  5530. else
  5531. Kind = 0; // local
  5532. DeclarationName Name = R.getLookupName();
  5533. // Emit warning and note.
  5534. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  5535. return;
  5536. Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
  5537. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  5538. }
  5539. /// \brief Check -Wshadow without the advantage of a previous lookup.
  5540. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  5541. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  5542. return;
  5543. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  5544. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  5545. LookupName(R, S);
  5546. CheckShadow(S, D, R);
  5547. }
  5548. /// Check for conflict between this global or extern "C" declaration and
  5549. /// previous global or extern "C" declarations. This is only used in C++.
  5550. template<typename T>
  5551. static bool checkGlobalOrExternCConflict(
  5552. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  5553. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  5554. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  5555. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  5556. // The common case: this global doesn't conflict with any extern "C"
  5557. // declaration.
  5558. return false;
  5559. }
  5560. if (Prev) {
  5561. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  5562. // Both the old and new declarations have C language linkage. This is a
  5563. // redeclaration.
  5564. Previous.clear();
  5565. Previous.addDecl(Prev);
  5566. return true;
  5567. }
  5568. // This is a global, non-extern "C" declaration, and there is a previous
  5569. // non-global extern "C" declaration. Diagnose if this is a variable
  5570. // declaration.
  5571. if (!isa<VarDecl>(ND))
  5572. return false;
  5573. } else {
  5574. // The declaration is extern "C". Check for any declaration in the
  5575. // translation unit which might conflict.
  5576. if (IsGlobal) {
  5577. // We have already performed the lookup into the translation unit.
  5578. IsGlobal = false;
  5579. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  5580. I != E; ++I) {
  5581. if (isa<VarDecl>(*I)) {
  5582. Prev = *I;
  5583. break;
  5584. }
  5585. }
  5586. } else {
  5587. DeclContext::lookup_result R =
  5588. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  5589. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  5590. I != E; ++I) {
  5591. if (isa<VarDecl>(*I)) {
  5592. Prev = *I;
  5593. break;
  5594. }
  5595. // FIXME: If we have any other entity with this name in global scope,
  5596. // the declaration is ill-formed, but that is a defect: it breaks the
  5597. // 'stat' hack, for instance. Only variables can have mangled name
  5598. // clashes with extern "C" declarations, so only they deserve a
  5599. // diagnostic.
  5600. }
  5601. }
  5602. if (!Prev)
  5603. return false;
  5604. }
  5605. // Use the first declaration's location to ensure we point at something which
  5606. // is lexically inside an extern "C" linkage-spec.
  5607. assert(Prev && "should have found a previous declaration to diagnose");
  5608. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  5609. Prev = FD->getFirstDecl();
  5610. else
  5611. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  5612. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  5613. << IsGlobal << ND;
  5614. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  5615. << IsGlobal;
  5616. return false;
  5617. }
  5618. /// Apply special rules for handling extern "C" declarations. Returns \c true
  5619. /// if we have found that this is a redeclaration of some prior entity.
  5620. ///
  5621. /// Per C++ [dcl.link]p6:
  5622. /// Two declarations [for a function or variable] with C language linkage
  5623. /// with the same name that appear in different scopes refer to the same
  5624. /// [entity]. An entity with C language linkage shall not be declared with
  5625. /// the same name as an entity in global scope.
  5626. template<typename T>
  5627. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  5628. LookupResult &Previous) {
  5629. if (!S.getLangOpts().CPlusPlus) {
  5630. // In C, when declaring a global variable, look for a corresponding 'extern'
  5631. // variable declared in function scope. We don't need this in C++, because
  5632. // we find local extern decls in the surrounding file-scope DeclContext.
  5633. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5634. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  5635. Previous.clear();
  5636. Previous.addDecl(Prev);
  5637. return true;
  5638. }
  5639. }
  5640. return false;
  5641. }
  5642. // A declaration in the translation unit can conflict with an extern "C"
  5643. // declaration.
  5644. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  5645. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  5646. // An extern "C" declaration can conflict with a declaration in the
  5647. // translation unit or can be a redeclaration of an extern "C" declaration
  5648. // in another scope.
  5649. if (isIncompleteDeclExternC(S,ND))
  5650. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  5651. // Neither global nor extern "C": nothing to do.
  5652. return false;
  5653. }
  5654. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  5655. // If the decl is already known invalid, don't check it.
  5656. if (NewVD->isInvalidDecl())
  5657. return;
  5658. TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
  5659. QualType T = TInfo->getType();
  5660. // Defer checking an 'auto' type until its initializer is attached.
  5661. if (T->isUndeducedType())
  5662. return;
  5663. if (NewVD->hasAttrs())
  5664. CheckAlignasUnderalignment(NewVD);
  5665. if (T->isObjCObjectType()) {
  5666. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  5667. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  5668. T = Context.getObjCObjectPointerType(T);
  5669. NewVD->setType(T);
  5670. }
  5671. // Emit an error if an address space was applied to decl with local storage.
  5672. // This includes arrays of objects with address space qualifiers, but not
  5673. // automatic variables that point to other address spaces.
  5674. // ISO/IEC TR 18037 S5.1.2
  5675. if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
  5676. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
  5677. NewVD->setInvalidDecl();
  5678. return;
  5679. }
  5680. // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
  5681. // __constant address space.
  5682. if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
  5683. && T.getAddressSpace() != LangAS::opencl_constant
  5684. && !T->isSamplerT()){
  5685. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
  5686. NewVD->setInvalidDecl();
  5687. return;
  5688. }
  5689. // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
  5690. // scope.
  5691. if ((getLangOpts().OpenCLVersion >= 120)
  5692. && NewVD->isStaticLocal()) {
  5693. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  5694. NewVD->setInvalidDecl();
  5695. return;
  5696. }
  5697. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  5698. && !NewVD->hasAttr<BlocksAttr>()) {
  5699. if (getLangOpts().getGC() != LangOptions::NonGC)
  5700. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  5701. else {
  5702. assert(!getLangOpts().ObjCAutoRefCount);
  5703. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  5704. }
  5705. }
  5706. bool isVM = T->isVariablyModifiedType();
  5707. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  5708. NewVD->hasAttr<BlocksAttr>())
  5709. getCurFunction()->setHasBranchProtectedScope();
  5710. if ((isVM && NewVD->hasLinkage()) ||
  5711. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  5712. bool SizeIsNegative;
  5713. llvm::APSInt Oversized;
  5714. TypeSourceInfo *FixedTInfo =
  5715. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5716. SizeIsNegative, Oversized);
  5717. if (!FixedTInfo && T->isVariableArrayType()) {
  5718. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  5719. // FIXME: This won't give the correct result for
  5720. // int a[10][n];
  5721. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  5722. if (NewVD->isFileVarDecl())
  5723. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  5724. << SizeRange;
  5725. else if (NewVD->isStaticLocal())
  5726. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  5727. << SizeRange;
  5728. else
  5729. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  5730. << SizeRange;
  5731. NewVD->setInvalidDecl();
  5732. return;
  5733. }
  5734. if (!FixedTInfo) {
  5735. if (NewVD->isFileVarDecl())
  5736. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  5737. else
  5738. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  5739. NewVD->setInvalidDecl();
  5740. return;
  5741. }
  5742. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  5743. NewVD->setType(FixedTInfo->getType());
  5744. NewVD->setTypeSourceInfo(FixedTInfo);
  5745. }
  5746. if (T->isVoidType()) {
  5747. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  5748. // of objects and functions.
  5749. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  5750. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  5751. << T;
  5752. NewVD->setInvalidDecl();
  5753. return;
  5754. }
  5755. }
  5756. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  5757. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  5758. NewVD->setInvalidDecl();
  5759. return;
  5760. }
  5761. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  5762. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  5763. NewVD->setInvalidDecl();
  5764. return;
  5765. }
  5766. if (NewVD->isConstexpr() && !T->isDependentType() &&
  5767. RequireLiteralType(NewVD->getLocation(), T,
  5768. diag::err_constexpr_var_non_literal)) {
  5769. NewVD->setInvalidDecl();
  5770. return;
  5771. }
  5772. }
  5773. /// \brief Perform semantic checking on a newly-created variable
  5774. /// declaration.
  5775. ///
  5776. /// This routine performs all of the type-checking required for a
  5777. /// variable declaration once it has been built. It is used both to
  5778. /// check variables after they have been parsed and their declarators
  5779. /// have been translated into a declaration, and to check variables
  5780. /// that have been instantiated from a template.
  5781. ///
  5782. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  5783. ///
  5784. /// Returns true if the variable declaration is a redeclaration.
  5785. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous, ShadowMergeState MergeState) { // HLSL Change - add merge state
  5786. CheckVariableDeclarationType(NewVD);
  5787. // If the decl is already known invalid, don't check it.
  5788. if (NewVD->isInvalidDecl())
  5789. return false;
  5790. // If we did not find anything by this name, look for a non-visible
  5791. // extern "C" declaration with the same name.
  5792. if (Previous.empty() &&
  5793. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  5794. Previous.setShadowed();
  5795. // Filter out any non-conflicting previous declarations.
  5796. filterNonConflictingPreviousDecls(*this, NewVD, Previous);
  5797. if (!Previous.empty()) {
  5798. MergeVarDecl(NewVD, Previous, MergeState); // HLSL Change - add merge state
  5799. return true;
  5800. }
  5801. return false;
  5802. }
  5803. /// \brief Data used with FindOverriddenMethod
  5804. struct FindOverriddenMethodData {
  5805. Sema *S;
  5806. CXXMethodDecl *Method;
  5807. };
  5808. /// \brief Member lookup function that determines whether a given C++
  5809. /// method overrides a method in a base class, to be used with
  5810. /// CXXRecordDecl::lookupInBases().
  5811. static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
  5812. CXXBasePath &Path,
  5813. void *UserData) {
  5814. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  5815. FindOverriddenMethodData *Data
  5816. = reinterpret_cast<FindOverriddenMethodData*>(UserData);
  5817. DeclarationName Name = Data->Method->getDeclName();
  5818. // FIXME: Do we care about other names here too?
  5819. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  5820. // We really want to find the base class destructor here.
  5821. QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
  5822. CanQualType CT = Data->S->Context.getCanonicalType(T);
  5823. Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
  5824. }
  5825. for (Path.Decls = BaseRecord->lookup(Name);
  5826. !Path.Decls.empty();
  5827. Path.Decls = Path.Decls.slice(1)) {
  5828. NamedDecl *D = Path.Decls.front();
  5829. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  5830. if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
  5831. return true;
  5832. }
  5833. }
  5834. return false;
  5835. }
  5836. namespace {
  5837. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  5838. }
  5839. /// \brief Report an error regarding overriding, along with any relevant
  5840. /// overriden methods.
  5841. ///
  5842. /// \param DiagID the primary error to report.
  5843. /// \param MD the overriding method.
  5844. /// \param OEK which overrides to include as notes.
  5845. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  5846. OverrideErrorKind OEK = OEK_All) {
  5847. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  5848. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  5849. E = MD->end_overridden_methods();
  5850. I != E; ++I) {
  5851. // This check (& the OEK parameter) could be replaced by a predicate, but
  5852. // without lambdas that would be overkill. This is still nicer than writing
  5853. // out the diag loop 3 times.
  5854. if ((OEK == OEK_All) ||
  5855. (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
  5856. (OEK == OEK_Deleted && (*I)->isDeleted()))
  5857. S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
  5858. }
  5859. }
  5860. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  5861. /// and if so, check that it's a valid override and remember it.
  5862. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  5863. // Look for methods in base classes that this method might override.
  5864. CXXBasePaths Paths;
  5865. FindOverriddenMethodData Data;
  5866. Data.Method = MD;
  5867. Data.S = this;
  5868. bool hasDeletedOverridenMethods = false;
  5869. bool hasNonDeletedOverridenMethods = false;
  5870. bool AddedAny = false;
  5871. if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
  5872. for (auto *I : Paths.found_decls()) {
  5873. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  5874. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  5875. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  5876. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  5877. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  5878. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  5879. hasDeletedOverridenMethods |= OldMD->isDeleted();
  5880. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  5881. AddedAny = true;
  5882. }
  5883. }
  5884. }
  5885. }
  5886. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  5887. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  5888. }
  5889. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  5890. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  5891. }
  5892. return AddedAny;
  5893. }
  5894. namespace {
  5895. // Struct for holding all of the extra arguments needed by
  5896. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  5897. struct ActOnFDArgs {
  5898. Scope *S;
  5899. Declarator &D;
  5900. MultiTemplateParamsArg TemplateParamLists;
  5901. bool AddToScope;
  5902. };
  5903. }
  5904. namespace {
  5905. // Callback to only accept typo corrections that have a non-zero edit distance.
  5906. // Also only accept corrections that have the same parent decl.
  5907. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  5908. public:
  5909. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  5910. CXXRecordDecl *Parent)
  5911. : Context(Context), OriginalFD(TypoFD),
  5912. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  5913. bool ValidateCandidate(const TypoCorrection &candidate) override {
  5914. if (candidate.getEditDistance() == 0)
  5915. return false;
  5916. SmallVector<unsigned, 1> MismatchedParams;
  5917. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  5918. CDeclEnd = candidate.end();
  5919. CDecl != CDeclEnd; ++CDecl) {
  5920. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  5921. if (FD && !FD->hasBody() &&
  5922. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  5923. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  5924. CXXRecordDecl *Parent = MD->getParent();
  5925. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  5926. return true;
  5927. } else if (!ExpectedParent) {
  5928. return true;
  5929. }
  5930. }
  5931. }
  5932. return false;
  5933. }
  5934. private:
  5935. ASTContext &Context;
  5936. FunctionDecl *OriginalFD;
  5937. CXXRecordDecl *ExpectedParent;
  5938. };
  5939. }
  5940. /// \brief Generate diagnostics for an invalid function redeclaration.
  5941. ///
  5942. /// This routine handles generating the diagnostic messages for an invalid
  5943. /// function redeclaration, including finding possible similar declarations
  5944. /// or performing typo correction if there are no previous declarations with
  5945. /// the same name.
  5946. ///
  5947. /// Returns a NamedDecl iff typo correction was performed and substituting in
  5948. /// the new declaration name does not cause new errors.
  5949. static NamedDecl *DiagnoseInvalidRedeclaration(
  5950. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  5951. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  5952. DeclarationName Name = NewFD->getDeclName();
  5953. DeclContext *NewDC = NewFD->getDeclContext();
  5954. SmallVector<unsigned, 1> MismatchedParams;
  5955. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  5956. TypoCorrection Correction;
  5957. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  5958. unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
  5959. : diag::err_member_decl_does_not_match;
  5960. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  5961. IsLocalFriend ? Sema::LookupLocalFriendName
  5962. : Sema::LookupOrdinaryName,
  5963. Sema::ForRedeclaration);
  5964. NewFD->setInvalidDecl();
  5965. if (IsLocalFriend)
  5966. SemaRef.LookupName(Prev, S);
  5967. else
  5968. SemaRef.LookupQualifiedName(Prev, NewDC);
  5969. assert(!Prev.isAmbiguous() &&
  5970. "Cannot have an ambiguity in previous-declaration lookup");
  5971. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  5972. if (!Prev.empty()) {
  5973. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  5974. Func != FuncEnd; ++Func) {
  5975. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  5976. if (FD &&
  5977. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  5978. // Add 1 to the index so that 0 can mean the mismatch didn't
  5979. // involve a parameter
  5980. unsigned ParamNum =
  5981. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  5982. NearMatches.push_back(std::make_pair(FD, ParamNum));
  5983. }
  5984. }
  5985. // If the qualified name lookup yielded nothing, try typo correction
  5986. } else if ((Correction = SemaRef.CorrectTypo(
  5987. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  5988. &ExtraArgs.D.getCXXScopeSpec(),
  5989. llvm::make_unique<DifferentNameValidatorCCC>(
  5990. SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
  5991. Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
  5992. // Set up everything for the call to ActOnFunctionDeclarator
  5993. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  5994. ExtraArgs.D.getIdentifierLoc());
  5995. Previous.clear();
  5996. Previous.setLookupName(Correction.getCorrection());
  5997. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  5998. CDeclEnd = Correction.end();
  5999. CDecl != CDeclEnd; ++CDecl) {
  6000. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6001. if (FD && !FD->hasBody() &&
  6002. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6003. Previous.addDecl(FD);
  6004. }
  6005. }
  6006. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  6007. NamedDecl *Result;
  6008. // Retry building the function declaration with the new previous
  6009. // declarations, and with errors suppressed.
  6010. {
  6011. // Trap errors.
  6012. Sema::SFINAETrap Trap(SemaRef);
  6013. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  6014. // pieces need to verify the typo-corrected C++ declaration and hopefully
  6015. // eliminate the need for the parameter pack ExtraArgs.
  6016. Result = SemaRef.ActOnFunctionDeclarator(
  6017. ExtraArgs.S, ExtraArgs.D,
  6018. Correction.getCorrectionDecl()->getDeclContext(),
  6019. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  6020. ExtraArgs.AddToScope);
  6021. if (Trap.hasErrorOccurred())
  6022. Result = nullptr;
  6023. }
  6024. if (Result) {
  6025. // Determine which correction we picked.
  6026. Decl *Canonical = Result->getCanonicalDecl();
  6027. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6028. I != E; ++I)
  6029. if ((*I)->getCanonicalDecl() == Canonical)
  6030. Correction.setCorrectionDecl(*I);
  6031. SemaRef.diagnoseTypo(
  6032. Correction,
  6033. SemaRef.PDiag(IsLocalFriend
  6034. ? diag::err_no_matching_local_friend_suggest
  6035. : diag::err_member_decl_does_not_match_suggest)
  6036. << Name << NewDC << IsDefinition);
  6037. return Result;
  6038. }
  6039. // Pretend the typo correction never occurred
  6040. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  6041. ExtraArgs.D.getIdentifierLoc());
  6042. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  6043. Previous.clear();
  6044. Previous.setLookupName(Name);
  6045. }
  6046. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  6047. << Name << NewDC << IsDefinition << NewFD->getLocation();
  6048. bool NewFDisConst = false;
  6049. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  6050. NewFDisConst = NewMD->isConst();
  6051. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  6052. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  6053. NearMatch != NearMatchEnd; ++NearMatch) {
  6054. FunctionDecl *FD = NearMatch->first;
  6055. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6056. bool FDisConst = MD && MD->isConst();
  6057. bool IsMember = MD || !IsLocalFriend;
  6058. // FIXME: These notes are poorly worded for the local friend case.
  6059. if (unsigned Idx = NearMatch->second) {
  6060. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  6061. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  6062. if (Loc.isInvalid()) Loc = FD->getLocation();
  6063. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  6064. : diag::note_local_decl_close_param_match)
  6065. << Idx << FDParam->getType()
  6066. << NewFD->getParamDecl(Idx - 1)->getType();
  6067. } else if (FDisConst != NewFDisConst) {
  6068. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  6069. << NewFDisConst << FD->getSourceRange().getEnd();
  6070. } else
  6071. SemaRef.Diag(FD->getLocation(),
  6072. IsMember ? diag::note_member_def_close_match
  6073. : diag::note_local_decl_close_match);
  6074. }
  6075. return nullptr;
  6076. }
  6077. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  6078. switch (D.getDeclSpec().getStorageClassSpec()) {
  6079. default: llvm_unreachable("Unknown storage class!");
  6080. case DeclSpec::SCS_auto:
  6081. case DeclSpec::SCS_register:
  6082. case DeclSpec::SCS_mutable:
  6083. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6084. diag::err_typecheck_sclass_func);
  6085. D.setInvalidType();
  6086. break;
  6087. case DeclSpec::SCS_unspecified: break;
  6088. case DeclSpec::SCS_extern:
  6089. if (D.getDeclSpec().isExternInLinkageSpec())
  6090. return SC_None;
  6091. return SC_Extern;
  6092. case DeclSpec::SCS_static: {
  6093. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  6094. // C99 6.7.1p5:
  6095. // The declaration of an identifier for a function that has
  6096. // block scope shall have no explicit storage-class specifier
  6097. // other than extern
  6098. // See also (C++ [dcl.stc]p4).
  6099. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6100. diag::err_static_block_func);
  6101. break;
  6102. } else
  6103. return SC_Static;
  6104. }
  6105. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  6106. }
  6107. // No explicit storage class has already been returned
  6108. return SC_None;
  6109. }
  6110. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  6111. DeclContext *DC, QualType &R,
  6112. TypeSourceInfo *TInfo,
  6113. StorageClass SC,
  6114. bool &IsVirtualOkay) {
  6115. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  6116. DeclarationName Name = NameInfo.getName();
  6117. FunctionDecl *NewFD = nullptr;
  6118. bool isInline = D.getDeclSpec().isInlineSpecified();
  6119. if (!SemaRef.getLangOpts().CPlusPlus) {
  6120. // Determine whether the function was written with a
  6121. // prototype. This true when:
  6122. // - there is a prototype in the declarator, or
  6123. // - the type R of the function is some kind of typedef or other reference
  6124. // to a type name (which eventually refers to a function type).
  6125. bool HasPrototype =
  6126. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  6127. (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
  6128. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  6129. D.getLocStart(), NameInfo, R,
  6130. TInfo, SC, isInline,
  6131. HasPrototype, false);
  6132. if (D.isInvalidType())
  6133. NewFD->setInvalidDecl();
  6134. return NewFD;
  6135. }
  6136. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  6137. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  6138. // Check that the return type is not an abstract class type.
  6139. // For record types, this is done by the AbstractClassUsageDiagnoser once
  6140. // the class has been completely parsed.
  6141. if (!DC->isRecord() &&
  6142. SemaRef.RequireNonAbstractType(
  6143. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  6144. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  6145. D.setInvalidType();
  6146. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  6147. // This is a C++ constructor declaration.
  6148. assert(DC->isRecord() &&
  6149. "Constructors can only be declared in a member context");
  6150. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  6151. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  6152. D.getLocStart(), NameInfo,
  6153. R, TInfo, isExplicit, isInline,
  6154. /*isImplicitlyDeclared=*/false,
  6155. isConstexpr);
  6156. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6157. // This is a C++ destructor declaration.
  6158. if (DC->isRecord()) {
  6159. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  6160. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  6161. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  6162. SemaRef.Context, Record,
  6163. D.getLocStart(),
  6164. NameInfo, R, TInfo, isInline,
  6165. /*isImplicitlyDeclared=*/false);
  6166. // If the class is complete, then we now create the implicit exception
  6167. // specification. If the class is incomplete or dependent, we can't do
  6168. // it yet.
  6169. if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
  6170. Record->getDefinition() && !Record->isBeingDefined() &&
  6171. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  6172. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  6173. }
  6174. IsVirtualOkay = true;
  6175. return NewDD;
  6176. } else {
  6177. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  6178. D.setInvalidType();
  6179. // Create a FunctionDecl to satisfy the function definition parsing
  6180. // code path.
  6181. return FunctionDecl::Create(SemaRef.Context, DC,
  6182. D.getLocStart(),
  6183. D.getIdentifierLoc(), Name, R, TInfo,
  6184. SC, isInline,
  6185. /*hasPrototype=*/true, isConstexpr);
  6186. }
  6187. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  6188. if (!DC->isRecord()) {
  6189. SemaRef.Diag(D.getIdentifierLoc(),
  6190. diag::err_conv_function_not_member);
  6191. return nullptr;
  6192. }
  6193. SemaRef.CheckConversionDeclarator(D, R, SC);
  6194. IsVirtualOkay = true;
  6195. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  6196. D.getLocStart(), NameInfo,
  6197. R, TInfo, isInline, isExplicit,
  6198. isConstexpr, SourceLocation());
  6199. } else if (DC->isRecord()) {
  6200. // If the name of the function is the same as the name of the record,
  6201. // then this must be an invalid constructor that has a return type.
  6202. // (The parser checks for a return type and makes the declarator a
  6203. // constructor if it has no return type).
  6204. if (Name.getAsIdentifierInfo() &&
  6205. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  6206. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  6207. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  6208. << SourceRange(D.getIdentifierLoc());
  6209. return nullptr;
  6210. }
  6211. // This is a C++ method declaration.
  6212. CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
  6213. cast<CXXRecordDecl>(DC),
  6214. D.getLocStart(), NameInfo, R,
  6215. TInfo, SC, isInline,
  6216. isConstexpr, SourceLocation());
  6217. IsVirtualOkay = !Ret->isStatic();
  6218. return Ret;
  6219. } else {
  6220. bool isFriend =
  6221. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  6222. if (!isFriend && SemaRef.CurContext->isRecord())
  6223. return nullptr;
  6224. // Determine whether the function was written with a
  6225. // prototype. This true when:
  6226. // - we're in C++ (where every function has a prototype),
  6227. return FunctionDecl::Create(SemaRef.Context, DC,
  6228. D.getLocStart(),
  6229. NameInfo, R, TInfo, SC, isInline,
  6230. true/*HasPrototype*/, isConstexpr);
  6231. }
  6232. }
  6233. enum OpenCLParamType {
  6234. ValidKernelParam,
  6235. PtrPtrKernelParam,
  6236. PtrKernelParam,
  6237. PrivatePtrKernelParam,
  6238. InvalidKernelParam,
  6239. RecordKernelParam
  6240. };
  6241. static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
  6242. if (PT->isPointerType()) {
  6243. QualType PointeeType = PT->getPointeeType();
  6244. if (PointeeType->isPointerType())
  6245. return PtrPtrKernelParam;
  6246. return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
  6247. : PtrKernelParam;
  6248. }
  6249. // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
  6250. // be used as builtin types.
  6251. if (PT->isImageType())
  6252. return PtrKernelParam;
  6253. if (PT->isBooleanType())
  6254. return InvalidKernelParam;
  6255. if (PT->isEventT())
  6256. return InvalidKernelParam;
  6257. if (PT->isHalfType())
  6258. return InvalidKernelParam;
  6259. if (PT->isRecordType())
  6260. return RecordKernelParam;
  6261. return ValidKernelParam;
  6262. }
  6263. static void checkIsValidOpenCLKernelParameter(
  6264. Sema &S,
  6265. Declarator &D,
  6266. ParmVarDecl *Param,
  6267. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  6268. QualType PT = Param->getType();
  6269. // Cache the valid types we encounter to avoid rechecking structs that are
  6270. // used again
  6271. if (ValidTypes.count(PT.getTypePtr()))
  6272. return;
  6273. switch (getOpenCLKernelParameterType(PT)) {
  6274. case PtrPtrKernelParam:
  6275. // OpenCL v1.2 s6.9.a:
  6276. // A kernel function argument cannot be declared as a
  6277. // pointer to a pointer type.
  6278. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  6279. D.setInvalidType();
  6280. return;
  6281. case PrivatePtrKernelParam:
  6282. // OpenCL v1.2 s6.9.a:
  6283. // A kernel function argument cannot be declared as a
  6284. // pointer to the private address space.
  6285. S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
  6286. D.setInvalidType();
  6287. return;
  6288. // OpenCL v1.2 s6.9.k:
  6289. // Arguments to kernel functions in a program cannot be declared with the
  6290. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  6291. // uintptr_t or a struct and/or union that contain fields declared to be
  6292. // one of these built-in scalar types.
  6293. case InvalidKernelParam:
  6294. // OpenCL v1.2 s6.8 n:
  6295. // A kernel function argument cannot be declared
  6296. // of event_t type.
  6297. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  6298. D.setInvalidType();
  6299. return;
  6300. case PtrKernelParam:
  6301. case ValidKernelParam:
  6302. ValidTypes.insert(PT.getTypePtr());
  6303. return;
  6304. case RecordKernelParam:
  6305. break;
  6306. }
  6307. // Track nested structs we will inspect
  6308. SmallVector<const Decl *, 4> VisitStack;
  6309. // Track where we are in the nested structs. Items will migrate from
  6310. // VisitStack to HistoryStack as we do the DFS for bad field.
  6311. SmallVector<const FieldDecl *, 4> HistoryStack;
  6312. HistoryStack.push_back(nullptr);
  6313. const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
  6314. VisitStack.push_back(PD);
  6315. assert(VisitStack.back() && "First decl null?");
  6316. do {
  6317. const Decl *Next = VisitStack.pop_back_val();
  6318. if (!Next) {
  6319. assert(!HistoryStack.empty());
  6320. // Found a marker, we have gone up a level
  6321. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  6322. ValidTypes.insert(Hist->getType().getTypePtr());
  6323. continue;
  6324. }
  6325. // Adds everything except the original parameter declaration (which is not a
  6326. // field itself) to the history stack.
  6327. const RecordDecl *RD;
  6328. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  6329. HistoryStack.push_back(Field);
  6330. RD = Field->getType()->castAs<RecordType>()->getDecl();
  6331. } else {
  6332. RD = cast<RecordDecl>(Next);
  6333. }
  6334. // Add a null marker so we know when we've gone back up a level
  6335. VisitStack.push_back(nullptr);
  6336. for (const auto *FD : RD->fields()) {
  6337. QualType QT = FD->getType();
  6338. if (ValidTypes.count(QT.getTypePtr()))
  6339. continue;
  6340. OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
  6341. if (ParamType == ValidKernelParam)
  6342. continue;
  6343. if (ParamType == RecordKernelParam) {
  6344. VisitStack.push_back(FD);
  6345. continue;
  6346. }
  6347. // OpenCL v1.2 s6.9.p:
  6348. // Arguments to kernel functions that are declared to be a struct or union
  6349. // do not allow OpenCL objects to be passed as elements of the struct or
  6350. // union.
  6351. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  6352. ParamType == PrivatePtrKernelParam) {
  6353. S.Diag(Param->getLocation(),
  6354. diag::err_record_with_pointers_kernel_param)
  6355. << PT->isUnionType()
  6356. << PT;
  6357. } else {
  6358. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  6359. }
  6360. S.Diag(PD->getLocation(), diag::note_within_field_of_type)
  6361. << PD->getDeclName();
  6362. // We have an error, now let's go back up through history and show where
  6363. // the offending field came from
  6364. for (ArrayRef<const FieldDecl *>::const_iterator
  6365. I = HistoryStack.begin() + 1,
  6366. E = HistoryStack.end();
  6367. I != E; ++I) {
  6368. const FieldDecl *OuterField = *I;
  6369. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  6370. << OuterField->getType();
  6371. }
  6372. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  6373. << QT->isPointerType()
  6374. << QT;
  6375. D.setInvalidType();
  6376. return;
  6377. }
  6378. } while (!VisitStack.empty());
  6379. }
  6380. NamedDecl*
  6381. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  6382. TypeSourceInfo *TInfo, LookupResult &Previous,
  6383. MultiTemplateParamsArg TemplateParamLists,
  6384. bool &AddToScope) {
  6385. QualType R = TInfo->getType();
  6386. assert(R.getTypePtr()->isFunctionType());
  6387. // TODO: consider using NameInfo for diagnostic.
  6388. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  6389. DeclarationName Name = NameInfo.getName();
  6390. StorageClass SC = getFunctionStorageClass(*this, D);
  6391. // HLSL Change - reject 'extern' functions
  6392. if (getLangOpts().HLSL && SC == SC_Extern) {
  6393. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'extern'" << "function";
  6394. }
  6395. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  6396. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6397. diag::err_invalid_thread)
  6398. << DeclSpec::getSpecifierName(TSCS);
  6399. if (D.isFirstDeclarationOfMember())
  6400. adjustMemberFunctionCC(R, D.isStaticMember());
  6401. bool isFriend = false;
  6402. FunctionTemplateDecl *FunctionTemplate = nullptr;
  6403. bool isExplicitSpecialization = false;
  6404. bool isFunctionTemplateSpecialization = false;
  6405. bool isDependentClassScopeExplicitSpecialization = false;
  6406. bool HasExplicitTemplateArgs = false;
  6407. TemplateArgumentListInfo TemplateArgs;
  6408. bool isVirtualOkay = false;
  6409. DeclContext *OriginalDC = DC;
  6410. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  6411. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  6412. isVirtualOkay);
  6413. if (!NewFD) return nullptr;
  6414. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  6415. NewFD->setTopLevelDeclInObjCContainer();
  6416. // Set the lexical context. If this is a function-scope declaration, or has a
  6417. // C++ scope specifier, or is the object of a friend declaration, the lexical
  6418. // context will be different from the semantic context.
  6419. NewFD->setLexicalDeclContext(CurContext);
  6420. if (IsLocalExternDecl)
  6421. NewFD->setLocalExternDecl();
  6422. if (getLangOpts().CPlusPlus) {
  6423. bool isInline = D.getDeclSpec().isInlineSpecified();
  6424. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  6425. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  6426. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  6427. isFriend = D.getDeclSpec().isFriendSpecified();
  6428. if (isFriend && !isInline && D.isFunctionDefinition()) {
  6429. // C++ [class.friend]p5
  6430. // A function can be defined in a friend declaration of a
  6431. // class . . . . Such a function is implicitly inline.
  6432. NewFD->setImplicitlyInline();
  6433. }
  6434. // If this is a method defined in an __interface, and is not a constructor
  6435. // or an overloaded operator, then set the pure flag (isVirtual will already
  6436. // return true).
  6437. if (const CXXRecordDecl *Parent =
  6438. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  6439. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  6440. NewFD->setPure(true);
  6441. // C++ [class.union]p2
  6442. // A union can have member functions, but not virtual functions.
  6443. if (isVirtual && Parent->isUnion())
  6444. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  6445. }
  6446. SetNestedNameSpecifier(NewFD, D);
  6447. isExplicitSpecialization = false;
  6448. isFunctionTemplateSpecialization = false;
  6449. if (D.isInvalidType())
  6450. NewFD->setInvalidDecl();
  6451. // Match up the template parameter lists with the scope specifier, then
  6452. // determine whether we have a template or a template specialization.
  6453. bool Invalid = false;
  6454. if (TemplateParameterList *TemplateParams =
  6455. MatchTemplateParametersToScopeSpecifier(
  6456. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  6457. D.getCXXScopeSpec(),
  6458. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  6459. ? D.getName().TemplateId
  6460. : nullptr,
  6461. TemplateParamLists, isFriend, isExplicitSpecialization,
  6462. Invalid)) {
  6463. if (TemplateParams->size() > 0) {
  6464. // This is a function template
  6465. // Check that we can declare a template here.
  6466. if (CheckTemplateDeclScope(S, TemplateParams))
  6467. NewFD->setInvalidDecl();
  6468. // A destructor cannot be a template.
  6469. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6470. Diag(NewFD->getLocation(), diag::err_destructor_template);
  6471. NewFD->setInvalidDecl();
  6472. }
  6473. // If we're adding a template to a dependent context, we may need to
  6474. // rebuilding some of the types used within the template parameter list,
  6475. // now that we know what the current instantiation is.
  6476. if (DC->isDependentContext()) {
  6477. ContextRAII SavedContext(*this, DC);
  6478. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  6479. Invalid = true;
  6480. }
  6481. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  6482. NewFD->getLocation(),
  6483. Name, TemplateParams,
  6484. NewFD);
  6485. FunctionTemplate->setLexicalDeclContext(CurContext);
  6486. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  6487. // For source fidelity, store the other template param lists.
  6488. if (TemplateParamLists.size() > 1) {
  6489. NewFD->setTemplateParameterListsInfo(Context,
  6490. TemplateParamLists.size() - 1,
  6491. TemplateParamLists.data());
  6492. }
  6493. } else {
  6494. // This is a function template specialization.
  6495. isFunctionTemplateSpecialization = true;
  6496. // For source fidelity, store all the template param lists.
  6497. if (TemplateParamLists.size() > 0)
  6498. NewFD->setTemplateParameterListsInfo(Context,
  6499. TemplateParamLists.size(),
  6500. TemplateParamLists.data());
  6501. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  6502. if (isFriend) {
  6503. // We want to remove the "template<>", found here.
  6504. SourceRange RemoveRange = TemplateParams->getSourceRange();
  6505. // If we remove the template<> and the name is not a
  6506. // template-id, we're actually silently creating a problem:
  6507. // the friend declaration will refer to an untemplated decl,
  6508. // and clearly the user wants a template specialization. So
  6509. // we need to insert '<>' after the name.
  6510. SourceLocation InsertLoc;
  6511. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  6512. InsertLoc = D.getName().getSourceRange().getEnd();
  6513. InsertLoc = getLocForEndOfToken(InsertLoc);
  6514. }
  6515. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  6516. << Name << RemoveRange
  6517. << FixItHint::CreateRemoval(RemoveRange)
  6518. << FixItHint::CreateInsertion(InsertLoc, "<>");
  6519. }
  6520. }
  6521. }
  6522. else {
  6523. // All template param lists were matched against the scope specifier:
  6524. // this is NOT (an explicit specialization of) a template.
  6525. if (TemplateParamLists.size() > 0)
  6526. // For source fidelity, store all the template param lists.
  6527. NewFD->setTemplateParameterListsInfo(Context,
  6528. TemplateParamLists.size(),
  6529. TemplateParamLists.data());
  6530. }
  6531. if (Invalid) {
  6532. NewFD->setInvalidDecl();
  6533. if (FunctionTemplate)
  6534. FunctionTemplate->setInvalidDecl();
  6535. }
  6536. // C++ [dcl.fct.spec]p5:
  6537. // The virtual specifier shall only be used in declarations of
  6538. // nonstatic class member functions that appear within a
  6539. // member-specification of a class declaration; see 10.3.
  6540. //
  6541. if (isVirtual && !NewFD->isInvalidDecl()) {
  6542. if (!isVirtualOkay) {
  6543. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  6544. diag::err_virtual_non_function);
  6545. } else if (!CurContext->isRecord()) {
  6546. // 'virtual' was specified outside of the class.
  6547. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  6548. diag::err_virtual_out_of_class)
  6549. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  6550. } else if (NewFD->getDescribedFunctionTemplate()) {
  6551. // C++ [temp.mem]p3:
  6552. // A member function template shall not be virtual.
  6553. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  6554. diag::err_virtual_member_function_template)
  6555. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  6556. } else {
  6557. // Okay: Add virtual to the method.
  6558. NewFD->setVirtualAsWritten(true);
  6559. }
  6560. if (getLangOpts().CPlusPlus14 &&
  6561. NewFD->getReturnType()->isUndeducedType())
  6562. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  6563. }
  6564. if (getLangOpts().CPlusPlus14 &&
  6565. (NewFD->isDependentContext() ||
  6566. (isFriend && CurContext->isDependentContext())) &&
  6567. NewFD->getReturnType()->isUndeducedType()) {
  6568. // If the function template is referenced directly (for instance, as a
  6569. // member of the current instantiation), pretend it has a dependent type.
  6570. // This is not really justified by the standard, but is the only sane
  6571. // thing to do.
  6572. // FIXME: For a friend function, we have not marked the function as being
  6573. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  6574. const FunctionProtoType *FPT =
  6575. NewFD->getType()->castAs<FunctionProtoType>();
  6576. QualType Result =
  6577. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  6578. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  6579. FPT->getExtProtoInfo(), FPT->getParamMods())); // HLSL Change - add param mods
  6580. }
  6581. // C++ [dcl.fct.spec]p3:
  6582. // The inline specifier shall not appear on a block scope function
  6583. // declaration.
  6584. if (isInline && !NewFD->isInvalidDecl()) {
  6585. if (CurContext->isFunctionOrMethod()) {
  6586. // 'inline' is not allowed on block scope function declaration.
  6587. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6588. diag::err_inline_declaration_block_scope) << Name
  6589. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  6590. }
  6591. }
  6592. // C++ [dcl.fct.spec]p6:
  6593. // The explicit specifier shall be used only in the declaration of a
  6594. // constructor or conversion function within its class definition;
  6595. // see 12.3.1 and 12.3.2.
  6596. if (isExplicit && !NewFD->isInvalidDecl()) {
  6597. if (!CurContext->isRecord()) {
  6598. // 'explicit' was specified outside of the class.
  6599. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  6600. diag::err_explicit_out_of_class)
  6601. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  6602. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  6603. !isa<CXXConversionDecl>(NewFD)) {
  6604. // 'explicit' was specified on a function that wasn't a constructor
  6605. // or conversion function.
  6606. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  6607. diag::err_explicit_non_ctor_or_conv_function)
  6608. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  6609. }
  6610. }
  6611. if (isConstexpr) {
  6612. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  6613. // are implicitly inline.
  6614. NewFD->setImplicitlyInline();
  6615. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  6616. // be either constructors or to return a literal type. Therefore,
  6617. // destructors cannot be declared constexpr.
  6618. if (isa<CXXDestructorDecl>(NewFD))
  6619. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  6620. }
  6621. // If __module_private__ was specified, mark the function accordingly.
  6622. if (D.getDeclSpec().isModulePrivateSpecified()) {
  6623. if (isFunctionTemplateSpecialization) {
  6624. SourceLocation ModulePrivateLoc
  6625. = D.getDeclSpec().getModulePrivateSpecLoc();
  6626. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  6627. << 0
  6628. << FixItHint::CreateRemoval(ModulePrivateLoc);
  6629. } else {
  6630. NewFD->setModulePrivate();
  6631. if (FunctionTemplate)
  6632. FunctionTemplate->setModulePrivate();
  6633. }
  6634. }
  6635. if (isFriend) {
  6636. if (FunctionTemplate) {
  6637. FunctionTemplate->setObjectOfFriendDecl();
  6638. FunctionTemplate->setAccess(AS_public);
  6639. }
  6640. NewFD->setObjectOfFriendDecl();
  6641. NewFD->setAccess(AS_public);
  6642. }
  6643. // If a function is defined as defaulted or deleted, mark it as such now.
  6644. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  6645. // definition kind to FDK_Definition.
  6646. switch (D.getFunctionDefinitionKind()) {
  6647. case FDK_Declaration:
  6648. case FDK_Definition:
  6649. break;
  6650. case FDK_Defaulted:
  6651. NewFD->setDefaulted();
  6652. break;
  6653. case FDK_Deleted:
  6654. NewFD->setDeletedAsWritten();
  6655. break;
  6656. }
  6657. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  6658. D.isFunctionDefinition()) {
  6659. // C++ [class.mfct]p2:
  6660. // A member function may be defined (8.4) in its class definition, in
  6661. // which case it is an inline member function (7.1.2)
  6662. NewFD->setImplicitlyInline();
  6663. }
  6664. // HLSL Change: We had to set SC_Static for static data member to
  6665. // distinguish it from global constant variable.
  6666. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  6667. !CurContext->isRecord() && !getLangOpts().HLSL) {
  6668. // C++ [class.static]p1:
  6669. // A data or function member of a class may be declared static
  6670. // in a class definition, in which case it is a static member of
  6671. // the class.
  6672. // Complain about the 'static' specifier if it's on an out-of-line
  6673. // member function definition.
  6674. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6675. diag::err_static_out_of_line)
  6676. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  6677. }
  6678. // C++11 [except.spec]p15:
  6679. // A deallocation function with no exception-specification is treated
  6680. // as if it were specified with noexcept(true).
  6681. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  6682. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  6683. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  6684. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  6685. NewFD->setType(Context.getFunctionType(
  6686. FPT->getReturnType(), FPT->getParamTypes(),
  6687. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept),
  6688. FPT->getParamMods())); // HLSL Change - get param mods
  6689. }
  6690. // Filter out previous declarations that don't match the scope.
  6691. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  6692. D.getCXXScopeSpec().isNotEmpty() ||
  6693. isExplicitSpecialization ||
  6694. isFunctionTemplateSpecialization);
  6695. // Handle GNU asm-label extension (encoded as an attribute).
  6696. if (Expr *E = (Expr*) D.getAsmLabel()) {
  6697. // The parser guarantees this is a string.
  6698. StringLiteral *SE = cast<StringLiteral>(E);
  6699. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  6700. SE->getString(), 0));
  6701. } else if (!ExtnameUndeclaredIdentifiers.empty() &&
  6702. isDeclTUScopedExternallyVisible(NewFD)) {
  6703. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6704. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  6705. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6706. NewFD->addAttr(I->second);
  6707. ExtnameUndeclaredIdentifiers.erase(I);
  6708. }
  6709. }
  6710. // Copy the parameter declarations from the declarator D to the function
  6711. // declaration NewFD, if they are available. First scavenge them into Params.
  6712. SmallVector<ParmVarDecl*, 16> Params;
  6713. if (D.isFunctionDeclarator()) {
  6714. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  6715. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  6716. // function that takes no arguments, not a function that takes a
  6717. // single void argument.
  6718. // We let through "const void" here because Sema::GetTypeForDeclarator
  6719. // already checks for that case.
  6720. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  6721. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  6722. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  6723. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  6724. Param->setDeclContext(NewFD);
  6725. Params.push_back(Param);
  6726. if (Param->isInvalidDecl())
  6727. NewFD->setInvalidDecl();
  6728. }
  6729. }
  6730. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  6731. // When we're declaring a function with a typedef, typeof, etc as in the
  6732. // following example, we'll need to synthesize (unnamed)
  6733. // parameters for use in the declaration.
  6734. //
  6735. // @code
  6736. // typedef void fn(int);
  6737. // fn f;
  6738. // @endcode
  6739. // Synthesize a parameter for each argument type.
  6740. for (const auto &AI : FT->param_types()) {
  6741. ParmVarDecl *Param =
  6742. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  6743. Param->setScopeInfo(0, Params.size());
  6744. Params.push_back(Param);
  6745. }
  6746. } else {
  6747. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  6748. "Should not need args for typedef of non-prototype fn");
  6749. }
  6750. // Finally, we know we have the right number of parameters, install them.
  6751. NewFD->setParams(Params);
  6752. // Find all anonymous symbols defined during the declaration of this function
  6753. // and add to NewFD. This lets us track decls such 'enum Y' in:
  6754. //
  6755. // void f(enum Y {AA} x) {}
  6756. //
  6757. // which would otherwise incorrectly end up in the translation unit scope.
  6758. NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
  6759. DeclsInPrototypeScope.clear();
  6760. if (D.getDeclSpec().isNoreturnSpecified())
  6761. NewFD->addAttr(
  6762. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  6763. Context, 0));
  6764. // Functions returning a variably modified type violate C99 6.7.5.2p2
  6765. // because all functions have linkage.
  6766. if (!NewFD->isInvalidDecl() &&
  6767. NewFD->getReturnType()->isVariablyModifiedType()) {
  6768. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  6769. NewFD->setInvalidDecl();
  6770. }
  6771. // Apply an implicit SectionAttr if #pragma code_seg is active.
  6772. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  6773. !NewFD->hasAttr<SectionAttr>()) {
  6774. NewFD->addAttr(
  6775. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  6776. CodeSegStack.CurrentValue->getString(),
  6777. CodeSegStack.CurrentPragmaLocation));
  6778. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  6779. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  6780. ASTContext::PSF_Read,
  6781. NewFD))
  6782. NewFD->dropAttr<SectionAttr>();
  6783. }
  6784. // Handle attributes.
  6785. ProcessDeclAttributes(S, NewFD, D);
  6786. if (getLangOpts().OpenCL) {
  6787. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  6788. // type declaration will generate a compilation error.
  6789. unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
  6790. if (AddressSpace == LangAS::opencl_local ||
  6791. AddressSpace == LangAS::opencl_global ||
  6792. AddressSpace == LangAS::opencl_constant) {
  6793. Diag(NewFD->getLocation(),
  6794. diag::err_opencl_return_value_with_address_space);
  6795. NewFD->setInvalidDecl();
  6796. }
  6797. }
  6798. if (!getLangOpts().CPlusPlus) {
  6799. // Perform semantic checking on the function declaration.
  6800. bool isExplicitSpecialization=false;
  6801. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  6802. CheckMain(NewFD, D.getDeclSpec());
  6803. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  6804. CheckMSVCRTEntryPoint(NewFD);
  6805. if (!NewFD->isInvalidDecl())
  6806. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  6807. isExplicitSpecialization));
  6808. else if (!Previous.empty())
  6809. // Recover gracefully from an invalid redeclaration.
  6810. D.setRedeclaration(true);
  6811. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  6812. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  6813. "previous declaration set still overloaded");
  6814. // Diagnose no-prototype function declarations with calling conventions that
  6815. // don't support variadic calls. Only do this in C and do it after merging
  6816. // possibly prototyped redeclarations.
  6817. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  6818. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  6819. CallingConv CC = FT->getExtInfo().getCC();
  6820. if (!supportsVariadicCall(CC)) {
  6821. // Windows system headers sometimes accidentally use stdcall without
  6822. // (void) parameters, so we relax this to a warning.
  6823. int DiagID =
  6824. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  6825. Diag(NewFD->getLocation(), DiagID)
  6826. << FunctionType::getNameForCallConv(CC);
  6827. }
  6828. }
  6829. } else {
  6830. // C++11 [replacement.functions]p3:
  6831. // The program's definitions shall not be specified as inline.
  6832. //
  6833. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  6834. //
  6835. // Suppress the diagnostic if the function is __attribute__((used)), since
  6836. // that forces an external definition to be emitted.
  6837. if (D.getDeclSpec().isInlineSpecified() &&
  6838. NewFD->isReplaceableGlobalAllocationFunction() &&
  6839. !NewFD->hasAttr<UsedAttr>())
  6840. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6841. diag::ext_operator_new_delete_declared_inline)
  6842. << NewFD->getDeclName();
  6843. // If the declarator is a template-id, translate the parser's template
  6844. // argument list into our AST format.
  6845. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  6846. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  6847. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  6848. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  6849. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  6850. TemplateId->NumArgs);
  6851. translateTemplateArguments(TemplateArgsPtr,
  6852. TemplateArgs);
  6853. HasExplicitTemplateArgs = true;
  6854. if (NewFD->isInvalidDecl()) {
  6855. HasExplicitTemplateArgs = false;
  6856. } else if (FunctionTemplate) {
  6857. // Function template with explicit template arguments.
  6858. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  6859. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  6860. HasExplicitTemplateArgs = false;
  6861. } else {
  6862. assert((isFunctionTemplateSpecialization ||
  6863. D.getDeclSpec().isFriendSpecified()) &&
  6864. "should have a 'template<>' for this decl");
  6865. // "friend void foo<>(int);" is an implicit specialization decl.
  6866. isFunctionTemplateSpecialization = true;
  6867. }
  6868. } else if (isFriend && isFunctionTemplateSpecialization) {
  6869. // This combination is only possible in a recovery case; the user
  6870. // wrote something like:
  6871. // template <> friend void foo(int);
  6872. // which we're recovering from as if the user had written:
  6873. // friend void foo<>(int);
  6874. // Go ahead and fake up a template id.
  6875. HasExplicitTemplateArgs = true;
  6876. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  6877. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  6878. }
  6879. // If it's a friend (and only if it's a friend), it's possible
  6880. // that either the specialized function type or the specialized
  6881. // template is dependent, and therefore matching will fail. In
  6882. // this case, don't check the specialization yet.
  6883. bool InstantiationDependent = false;
  6884. if (isFunctionTemplateSpecialization && isFriend &&
  6885. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  6886. TemplateSpecializationType::anyDependentTemplateArguments(
  6887. TemplateArgs.getArgumentArray(), TemplateArgs.size(),
  6888. InstantiationDependent))) {
  6889. assert(HasExplicitTemplateArgs &&
  6890. "friend function specialization without template args");
  6891. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  6892. Previous))
  6893. NewFD->setInvalidDecl();
  6894. } else if (isFunctionTemplateSpecialization) {
  6895. if (CurContext->isDependentContext() && CurContext->isRecord()
  6896. && !isFriend) {
  6897. isDependentClassScopeExplicitSpecialization = true;
  6898. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  6899. diag::ext_function_specialization_in_class :
  6900. diag::err_function_specialization_in_class)
  6901. << NewFD->getDeclName();
  6902. } else if (CheckFunctionTemplateSpecialization(NewFD,
  6903. (HasExplicitTemplateArgs ? &TemplateArgs
  6904. : nullptr),
  6905. Previous))
  6906. NewFD->setInvalidDecl();
  6907. // C++ [dcl.stc]p1:
  6908. // A storage-class-specifier shall not be specified in an explicit
  6909. // specialization (14.7.3)
  6910. FunctionTemplateSpecializationInfo *Info =
  6911. NewFD->getTemplateSpecializationInfo();
  6912. if (Info && SC != SC_None) {
  6913. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  6914. Diag(NewFD->getLocation(),
  6915. diag::err_explicit_specialization_inconsistent_storage_class)
  6916. << SC
  6917. << FixItHint::CreateRemoval(
  6918. D.getDeclSpec().getStorageClassSpecLoc());
  6919. else
  6920. Diag(NewFD->getLocation(),
  6921. diag::ext_explicit_specialization_storage_class)
  6922. << FixItHint::CreateRemoval(
  6923. D.getDeclSpec().getStorageClassSpecLoc());
  6924. }
  6925. } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
  6926. if (CheckMemberSpecialization(NewFD, Previous))
  6927. NewFD->setInvalidDecl();
  6928. }
  6929. // Perform semantic checking on the function declaration.
  6930. if (!isDependentClassScopeExplicitSpecialization) {
  6931. if (!getLangOpts().HLSL && !NewFD->isInvalidDecl() && NewFD->isMain()) // HLSL Change: no main() checks in HLSL
  6932. CheckMain(NewFD, D.getDeclSpec());
  6933. if (!getLangOpts().HLSL && !NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) // HLSL Change: no entry point checks in HLSL
  6934. CheckMSVCRTEntryPoint(NewFD);
  6935. if (!NewFD->isInvalidDecl())
  6936. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  6937. isExplicitSpecialization));
  6938. else if (!Previous.empty())
  6939. // Recover gracefully from an invalid redeclaration.
  6940. D.setRedeclaration(true);
  6941. }
  6942. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  6943. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  6944. "previous declaration set still overloaded");
  6945. NamedDecl *PrincipalDecl = (FunctionTemplate
  6946. ? cast<NamedDecl>(FunctionTemplate)
  6947. : NewFD);
  6948. if (isFriend && D.isRedeclaration()) {
  6949. AccessSpecifier Access = AS_public;
  6950. if (!NewFD->isInvalidDecl())
  6951. Access = NewFD->getPreviousDecl()->getAccess();
  6952. NewFD->setAccess(Access);
  6953. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  6954. }
  6955. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  6956. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  6957. PrincipalDecl->setNonMemberOperator();
  6958. // If we have a function template, check the template parameter
  6959. // list. This will check and merge default template arguments.
  6960. if (FunctionTemplate) {
  6961. FunctionTemplateDecl *PrevTemplate =
  6962. FunctionTemplate->getPreviousDecl();
  6963. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  6964. PrevTemplate ? PrevTemplate->getTemplateParameters()
  6965. : nullptr,
  6966. D.getDeclSpec().isFriendSpecified()
  6967. ? (D.isFunctionDefinition()
  6968. ? TPC_FriendFunctionTemplateDefinition
  6969. : TPC_FriendFunctionTemplate)
  6970. : (D.getCXXScopeSpec().isSet() &&
  6971. DC && DC->isRecord() &&
  6972. DC->isDependentContext())
  6973. ? TPC_ClassTemplateMember
  6974. : TPC_FunctionTemplate);
  6975. }
  6976. if (NewFD->isInvalidDecl()) {
  6977. // Ignore all the rest of this.
  6978. } else if (!D.isRedeclaration()) {
  6979. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  6980. AddToScope };
  6981. // Fake up an access specifier if it's supposed to be a class member.
  6982. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  6983. NewFD->setAccess(AS_public);
  6984. // Qualified decls generally require a previous declaration.
  6985. if (D.getCXXScopeSpec().isSet()) {
  6986. // ...with the major exception of templated-scope or
  6987. // dependent-scope friend declarations.
  6988. // TODO: we currently also suppress this check in dependent
  6989. // contexts because (1) the parameter depth will be off when
  6990. // matching friend templates and (2) we might actually be
  6991. // selecting a friend based on a dependent factor. But there
  6992. // are situations where these conditions don't apply and we
  6993. // can actually do this check immediately.
  6994. if (isFriend &&
  6995. (TemplateParamLists.size() ||
  6996. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  6997. CurContext->isDependentContext())) {
  6998. // ignore these
  6999. } else {
  7000. // The user tried to provide an out-of-line definition for a
  7001. // function that is a member of a class or namespace, but there
  7002. // was no such member function declared (C++ [class.mfct]p2,
  7003. // C++ [namespace.memdef]p2). For example:
  7004. //
  7005. // class X {
  7006. // void f() const;
  7007. // };
  7008. //
  7009. // void X::f() { } // ill-formed
  7010. //
  7011. // Complain about this problem, and attempt to suggest close
  7012. // matches (e.g., those that differ only in cv-qualifiers and
  7013. // whether the parameter types are references).
  7014. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7015. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  7016. AddToScope = ExtraArgs.AddToScope;
  7017. return Result;
  7018. }
  7019. }
  7020. // Unqualified local friend declarations are required to resolve
  7021. // to something.
  7022. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  7023. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7024. *this, Previous, NewFD, ExtraArgs, true, S)) {
  7025. AddToScope = ExtraArgs.AddToScope;
  7026. return Result;
  7027. }
  7028. }
  7029. } else if (!D.isFunctionDefinition() &&
  7030. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  7031. !isFriend && !isFunctionTemplateSpecialization &&
  7032. !isExplicitSpecialization) {
  7033. // An out-of-line member function declaration must also be a
  7034. // definition (C++ [class.mfct]p2).
  7035. // Note that this is not the case for explicit specializations of
  7036. // function templates or member functions of class templates, per
  7037. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  7038. // extension for compatibility with old SWIG code which likes to
  7039. // generate them.
  7040. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  7041. << D.getCXXScopeSpec().getRange();
  7042. }
  7043. }
  7044. ProcessPragmaWeak(S, NewFD);
  7045. checkAttributesAfterMerging(*this, *NewFD);
  7046. AddKnownFunctionAttributes(NewFD);
  7047. if (NewFD->hasAttr<OverloadableAttr>() &&
  7048. !NewFD->getType()->getAs<FunctionProtoType>()) {
  7049. Diag(NewFD->getLocation(),
  7050. diag::err_attribute_overloadable_no_prototype)
  7051. << NewFD;
  7052. // Turn this into a variadic function with no parameters.
  7053. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  7054. FunctionProtoType::ExtProtoInfo EPI(
  7055. Context.getDefaultCallingConvention(true, false));
  7056. EPI.Variadic = true;
  7057. EPI.ExtInfo = FT->getExtInfo();
  7058. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI, None); // HLSL Change - all defaults are in
  7059. NewFD->setType(R);
  7060. }
  7061. // If there's a #pragma GCC visibility in scope, and this isn't a class
  7062. // member, set the visibility of this function.
  7063. if (!DC->isRecord() && NewFD->isExternallyVisible())
  7064. AddPushedVisibilityAttribute(NewFD);
  7065. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  7066. // marking the function.
  7067. AddCFAuditedAttribute(NewFD);
  7068. // If this is a function definition, check if we have to apply optnone due to
  7069. // a pragma.
  7070. if(D.isFunctionDefinition())
  7071. AddRangeBasedOptnone(NewFD);
  7072. // If this is the first declaration of an extern C variable, update
  7073. // the map of such variables.
  7074. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  7075. isIncompleteDeclExternC(*this, NewFD))
  7076. RegisterLocallyScopedExternCDecl(NewFD, S);
  7077. // Set this FunctionDecl's range up to the right paren.
  7078. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  7079. if (D.isRedeclaration() && !Previous.empty()) {
  7080. checkDLLAttributeRedeclaration(
  7081. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
  7082. isExplicitSpecialization || isFunctionTemplateSpecialization);
  7083. }
  7084. if (getLangOpts().CPlusPlus) {
  7085. if (FunctionTemplate) {
  7086. if (NewFD->isInvalidDecl())
  7087. FunctionTemplate->setInvalidDecl();
  7088. return FunctionTemplate;
  7089. }
  7090. }
  7091. if (NewFD->hasAttr<OpenCLKernelAttr>()) {
  7092. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  7093. if ((getLangOpts().OpenCLVersion >= 120)
  7094. && (SC == SC_Static)) {
  7095. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  7096. D.setInvalidType();
  7097. }
  7098. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  7099. if (!NewFD->getReturnType()->isVoidType()) {
  7100. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  7101. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  7102. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  7103. : FixItHint());
  7104. D.setInvalidType();
  7105. }
  7106. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  7107. for (auto Param : NewFD->params())
  7108. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  7109. }
  7110. MarkUnusedFileScopedDecl(NewFD);
  7111. if (getLangOpts().CUDA)
  7112. if (IdentifierInfo *II = NewFD->getIdentifier())
  7113. if (!NewFD->isInvalidDecl() &&
  7114. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  7115. if (II->isStr("cudaConfigureCall")) {
  7116. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  7117. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  7118. Context.setcudaConfigureCallDecl(NewFD);
  7119. }
  7120. }
  7121. // Here we have an function template explicit specialization at class scope.
  7122. // The actually specialization will be postponed to template instatiation
  7123. // time via the ClassScopeFunctionSpecializationDecl node.
  7124. if (isDependentClassScopeExplicitSpecialization) {
  7125. ClassScopeFunctionSpecializationDecl *NewSpec =
  7126. ClassScopeFunctionSpecializationDecl::Create(
  7127. Context, CurContext, SourceLocation(),
  7128. cast<CXXMethodDecl>(NewFD),
  7129. HasExplicitTemplateArgs, TemplateArgs);
  7130. CurContext->addDecl(NewSpec);
  7131. AddToScope = false;
  7132. }
  7133. return NewFD;
  7134. }
  7135. /// \brief Perform semantic checking of a new function declaration.
  7136. ///
  7137. /// Performs semantic analysis of the new function declaration
  7138. /// NewFD. This routine performs all semantic checking that does not
  7139. /// require the actual declarator involved in the declaration, and is
  7140. /// used both for the declaration of functions as they are parsed
  7141. /// (called via ActOnDeclarator) and for the declaration of functions
  7142. /// that have been instantiated via C++ template instantiation (called
  7143. /// via InstantiateDecl).
  7144. ///
  7145. /// \param IsExplicitSpecialization whether this new function declaration is
  7146. /// an explicit specialization of the previous declaration.
  7147. ///
  7148. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  7149. ///
  7150. /// \returns true if the function declaration is a redeclaration.
  7151. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  7152. LookupResult &Previous,
  7153. bool IsExplicitSpecialization) {
  7154. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  7155. "Variably modified return types are not handled here");
  7156. // Determine whether the type of this function should be merged with
  7157. // a previous visible declaration. This never happens for functions in C++,
  7158. // and always happens in C if the previous declaration was visible.
  7159. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  7160. !Previous.isShadowed();
  7161. // Filter out any non-conflicting previous declarations.
  7162. filterNonConflictingPreviousDecls(*this, NewFD, Previous);
  7163. bool Redeclaration = false;
  7164. NamedDecl *OldDecl = nullptr;
  7165. // Merge or overload the declaration with an existing declaration of
  7166. // the same name, if appropriate.
  7167. if (!Previous.empty()) {
  7168. // Determine whether NewFD is an overload of PrevDecl or
  7169. // a declaration that requires merging. If it's an overload,
  7170. // there's no more work to do here; we'll just add the new
  7171. // function to the scope.
  7172. if (!AllowOverloadingOfFunction(Previous, Context)) {
  7173. NamedDecl *Candidate = Previous.getFoundDecl();
  7174. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  7175. Redeclaration = true;
  7176. OldDecl = Candidate;
  7177. }
  7178. } else {
  7179. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  7180. /*NewIsUsingDecl*/ false)) {
  7181. case Ovl_Match:
  7182. Redeclaration = true;
  7183. break;
  7184. case Ovl_NonFunction:
  7185. Redeclaration = true;
  7186. break;
  7187. case Ovl_Overload:
  7188. Redeclaration = false;
  7189. break;
  7190. }
  7191. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  7192. // If a function name is overloadable in C, then every function
  7193. // with that name must be marked "overloadable".
  7194. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  7195. << Redeclaration << NewFD;
  7196. NamedDecl *OverloadedDecl = nullptr;
  7197. if (Redeclaration)
  7198. OverloadedDecl = OldDecl;
  7199. else if (!Previous.empty())
  7200. OverloadedDecl = Previous.getRepresentativeDecl();
  7201. if (OverloadedDecl)
  7202. Diag(OverloadedDecl->getLocation(),
  7203. diag::note_attribute_overloadable_prev_overload);
  7204. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  7205. }
  7206. }
  7207. }
  7208. // Check for a previous extern "C" declaration with this name.
  7209. if (!Redeclaration &&
  7210. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  7211. filterNonConflictingPreviousDecls(*this, NewFD, Previous);
  7212. if (!Previous.empty()) {
  7213. // This is an extern "C" declaration with the same name as a previous
  7214. // declaration, and thus redeclares that entity...
  7215. Redeclaration = true;
  7216. OldDecl = Previous.getFoundDecl();
  7217. MergeTypeWithPrevious = false;
  7218. // ... except in the presence of __attribute__((overloadable)).
  7219. if (OldDecl->hasAttr<OverloadableAttr>()) {
  7220. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  7221. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  7222. << Redeclaration << NewFD;
  7223. Diag(Previous.getFoundDecl()->getLocation(),
  7224. diag::note_attribute_overloadable_prev_overload);
  7225. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  7226. }
  7227. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  7228. Redeclaration = false;
  7229. OldDecl = nullptr;
  7230. }
  7231. }
  7232. }
  7233. }
  7234. // HLSL Change Starts
  7235. // Rather than fix for inout parameters, comment out - this is N/A for HLSL
  7236. #if 0
  7237. // HLSL Change Ends
  7238. // C++11 [dcl.constexpr]p8:
  7239. // A constexpr specifier for a non-static member function that is not
  7240. // a constructor declares that member function to be const.
  7241. //
  7242. // This needs to be delayed until we know whether this is an out-of-line
  7243. // definition of a static member function.
  7244. //
  7245. // This rule is not present in C++1y, so we produce a backwards
  7246. // compatibility warning whenever it happens in C++11.
  7247. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  7248. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  7249. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  7250. (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
  7251. CXXMethodDecl *OldMD = nullptr;
  7252. if (OldDecl)
  7253. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  7254. if (!OldMD || !OldMD->isStatic()) {
  7255. const FunctionProtoType *FPT =
  7256. MD->getType()->castAs<FunctionProtoType>();
  7257. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  7258. EPI.TypeQuals |= Qualifiers::Const;
  7259. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  7260. FPT->getParamTypes(), EPI));
  7261. // Warn that we did this, if we're not performing template instantiation.
  7262. // In that case, we'll have warned already when the template was defined.
  7263. if (ActiveTemplateInstantiations.empty()) {
  7264. SourceLocation AddConstLoc;
  7265. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  7266. .IgnoreParens().getAs<FunctionTypeLoc>())
  7267. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  7268. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  7269. << FixItHint::CreateInsertion(AddConstLoc, " const");
  7270. }
  7271. }
  7272. }
  7273. #endif // HLSL Change Ends
  7274. if (Redeclaration) {
  7275. // NewFD and OldDecl represent declarations that need to be
  7276. // merged.
  7277. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  7278. NewFD->setInvalidDecl();
  7279. return Redeclaration;
  7280. }
  7281. Previous.clear();
  7282. Previous.addDecl(OldDecl);
  7283. if (FunctionTemplateDecl *OldTemplateDecl
  7284. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  7285. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  7286. FunctionTemplateDecl *NewTemplateDecl
  7287. = NewFD->getDescribedFunctionTemplate();
  7288. assert(NewTemplateDecl && "Template/non-template mismatch");
  7289. if (CXXMethodDecl *Method
  7290. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  7291. Method->setAccess(OldTemplateDecl->getAccess());
  7292. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  7293. }
  7294. // If this is an explicit specialization of a member that is a function
  7295. // template, mark it as a member specialization.
  7296. if (IsExplicitSpecialization &&
  7297. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  7298. NewTemplateDecl->setMemberSpecialization();
  7299. assert(OldTemplateDecl->isMemberSpecialization());
  7300. }
  7301. } else {
  7302. // This needs to happen first so that 'inline' propagates.
  7303. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  7304. if (isa<CXXMethodDecl>(NewFD))
  7305. NewFD->setAccess(OldDecl->getAccess());
  7306. }
  7307. }
  7308. // Semantic checking for this function declaration (in isolation).
  7309. if (getLangOpts().CPlusPlus) {
  7310. // C++-specific checks.
  7311. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  7312. CheckConstructor(Constructor);
  7313. } else if (CXXDestructorDecl *Destructor =
  7314. dyn_cast<CXXDestructorDecl>(NewFD)) {
  7315. CXXRecordDecl *Record = Destructor->getParent();
  7316. QualType ClassType = Context.getTypeDeclType(Record);
  7317. // FIXME: Shouldn't we be able to perform this check even when the class
  7318. // type is dependent? Both gcc and edg can handle that.
  7319. if (!ClassType->isDependentType()) {
  7320. DeclarationName Name
  7321. = Context.DeclarationNames.getCXXDestructorName(
  7322. Context.getCanonicalType(ClassType));
  7323. if (NewFD->getDeclName() != Name) {
  7324. Diag(NewFD->getLocation(), diag::err_destructor_name);
  7325. NewFD->setInvalidDecl();
  7326. return Redeclaration;
  7327. }
  7328. }
  7329. } else if (CXXConversionDecl *Conversion
  7330. = dyn_cast<CXXConversionDecl>(NewFD)) {
  7331. ActOnConversionDeclarator(Conversion);
  7332. }
  7333. // Find any virtual functions that this function overrides.
  7334. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  7335. if (!Method->isFunctionTemplateSpecialization() &&
  7336. !Method->getDescribedFunctionTemplate() &&
  7337. Method->isCanonicalDecl()) {
  7338. if (AddOverriddenMethods(Method->getParent(), Method)) {
  7339. // If the function was marked as "static", we have a problem.
  7340. if (NewFD->getStorageClass() == SC_Static) {
  7341. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  7342. }
  7343. }
  7344. }
  7345. if (Method->isStatic())
  7346. checkThisInStaticMemberFunctionType(Method);
  7347. }
  7348. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  7349. if (NewFD->isOverloadedOperator() &&
  7350. CheckOverloadedOperatorDeclaration(NewFD)) {
  7351. NewFD->setInvalidDecl();
  7352. return Redeclaration;
  7353. }
  7354. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  7355. if (NewFD->getLiteralIdentifier() &&
  7356. CheckLiteralOperatorDeclaration(NewFD)) {
  7357. NewFD->setInvalidDecl();
  7358. return Redeclaration;
  7359. }
  7360. // In C++, check default arguments now that we have merged decls. Unless
  7361. // the lexical context is the class, because in this case this is done
  7362. // during delayed parsing anyway.
  7363. if (!CurContext->isRecord())
  7364. CheckCXXDefaultArguments(NewFD);
  7365. // If this function declares a builtin function, check the type of this
  7366. // declaration against the expected type for the builtin.
  7367. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  7368. ASTContext::GetBuiltinTypeError Error;
  7369. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  7370. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  7371. if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
  7372. // The type of this function differs from the type of the builtin,
  7373. // so forget about the builtin entirely.
  7374. Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
  7375. }
  7376. }
  7377. // If this function is declared as being extern "C", then check to see if
  7378. // the function returns a UDT (class, struct, or union type) that is not C
  7379. // compatible, and if it does, warn the user.
  7380. // But, issue any diagnostic on the first declaration only.
  7381. if (Previous.empty() && NewFD->isExternC()) {
  7382. QualType R = NewFD->getReturnType();
  7383. if (R->isIncompleteType() && !R->isVoidType())
  7384. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  7385. << NewFD << R;
  7386. else if (!R.isPODType(Context) && !R->isVoidType() &&
  7387. !R->isObjCObjectPointerType())
  7388. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  7389. }
  7390. }
  7391. return Redeclaration;
  7392. }
  7393. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  7394. // C++11 [basic.start.main]p3:
  7395. // A program that [...] declares main to be inline, static or
  7396. // constexpr is ill-formed.
  7397. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  7398. // appear in a declaration of main.
  7399. // static main is not an error under C99, but we should warn about it.
  7400. // We accept _Noreturn main as an extension.
  7401. if (FD->getStorageClass() == SC_Static)
  7402. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  7403. ? diag::err_static_main : diag::warn_static_main)
  7404. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  7405. if (FD->isInlineSpecified())
  7406. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  7407. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  7408. if (DS.isNoreturnSpecified()) {
  7409. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  7410. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  7411. Diag(NoreturnLoc, diag::ext_noreturn_main);
  7412. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  7413. << FixItHint::CreateRemoval(NoreturnRange);
  7414. }
  7415. if (FD->isConstexpr()) {
  7416. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  7417. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  7418. FD->setConstexpr(false);
  7419. }
  7420. if (getLangOpts().OpenCL) {
  7421. Diag(FD->getLocation(), diag::err_opencl_no_main)
  7422. << FD->hasAttr<OpenCLKernelAttr>();
  7423. FD->setInvalidDecl();
  7424. return;
  7425. }
  7426. QualType T = FD->getType();
  7427. assert(T->isFunctionType() && "function decl is not of function type");
  7428. const FunctionType* FT = T->castAs<FunctionType>();
  7429. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  7430. // In C with GNU extensions we allow main() to have non-integer return
  7431. // type, but we should warn about the extension, and we disable the
  7432. // implicit-return-zero rule.
  7433. // GCC in C mode accepts qualified 'int'.
  7434. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  7435. FD->setHasImplicitReturnZero(true);
  7436. else {
  7437. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  7438. SourceRange RTRange = FD->getReturnTypeSourceRange();
  7439. if (RTRange.isValid())
  7440. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  7441. << FixItHint::CreateReplacement(RTRange, "int");
  7442. }
  7443. } else {
  7444. // In C and C++, main magically returns 0 if you fall off the end;
  7445. // set the flag which tells us that.
  7446. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  7447. // All the standards say that main() should return 'int'.
  7448. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  7449. FD->setHasImplicitReturnZero(true);
  7450. else {
  7451. // Otherwise, this is just a flat-out error.
  7452. SourceRange RTRange = FD->getReturnTypeSourceRange();
  7453. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  7454. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  7455. : FixItHint());
  7456. FD->setInvalidDecl(true);
  7457. }
  7458. }
  7459. // Treat protoless main() as nullary.
  7460. if (isa<FunctionNoProtoType>(FT)) return;
  7461. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  7462. unsigned nparams = FTP->getNumParams();
  7463. assert(FD->getNumParams() == nparams);
  7464. bool HasExtraParameters = (nparams > 3);
  7465. if (FTP->isVariadic()) {
  7466. Diag(FD->getLocation(), diag::ext_variadic_main);
  7467. // FIXME: if we had information about the location of the ellipsis, we
  7468. // could add a FixIt hint to remove it as a parameter.
  7469. }
  7470. // Darwin passes an undocumented fourth argument of type char**. If
  7471. // other platforms start sprouting these, the logic below will start
  7472. // getting shifty.
  7473. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  7474. HasExtraParameters = false;
  7475. if (HasExtraParameters) {
  7476. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  7477. FD->setInvalidDecl(true);
  7478. nparams = 3;
  7479. }
  7480. // FIXME: a lot of the following diagnostics would be improved
  7481. // if we had some location information about types.
  7482. QualType CharPP =
  7483. Context.getPointerType(Context.getPointerType(Context.CharTy));
  7484. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  7485. for (unsigned i = 0; i < nparams; ++i) {
  7486. QualType AT = FTP->getParamType(i);
  7487. bool mismatch = true;
  7488. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  7489. mismatch = false;
  7490. else if (Expected[i] == CharPP) {
  7491. // As an extension, the following forms are okay:
  7492. // char const **
  7493. // char const * const *
  7494. // char * const *
  7495. QualifierCollector qs;
  7496. const PointerType* PT;
  7497. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  7498. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  7499. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  7500. Context.CharTy)) {
  7501. qs.removeConst();
  7502. mismatch = !qs.empty();
  7503. }
  7504. }
  7505. if (mismatch) {
  7506. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  7507. // TODO: suggest replacing given type with expected type
  7508. FD->setInvalidDecl(true);
  7509. }
  7510. }
  7511. if (nparams == 1 && !FD->isInvalidDecl()) {
  7512. Diag(FD->getLocation(), diag::warn_main_one_arg);
  7513. }
  7514. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  7515. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  7516. FD->setInvalidDecl();
  7517. }
  7518. }
  7519. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  7520. QualType T = FD->getType();
  7521. assert(T->isFunctionType() && "function decl is not of function type");
  7522. const FunctionType *FT = T->castAs<FunctionType>();
  7523. // Set an implicit return of 'zero' if the function can return some integral,
  7524. // enumeration, pointer or nullptr type.
  7525. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  7526. FT->getReturnType()->isAnyPointerType() ||
  7527. FT->getReturnType()->isNullPtrType())
  7528. // DllMain is exempt because a return value of zero means it failed.
  7529. if (FD->getName() != "DllMain")
  7530. FD->setHasImplicitReturnZero(true);
  7531. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  7532. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  7533. FD->setInvalidDecl();
  7534. }
  7535. }
  7536. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  7537. // FIXME: Need strict checking. In C89, we need to check for
  7538. // any assignment, increment, decrement, function-calls, or
  7539. // commas outside of a sizeof. In C99, it's the same list,
  7540. // except that the aforementioned are allowed in unevaluated
  7541. // expressions. Everything else falls under the
  7542. // "may accept other forms of constant expressions" exception.
  7543. // (We never end up here for C++, so the constant expression
  7544. // rules there don't matter.)
  7545. const Expr *Culprit;
  7546. if (Init->isConstantInitializer(Context, false, &Culprit))
  7547. return false;
  7548. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  7549. << Culprit->getSourceRange();
  7550. return true;
  7551. }
  7552. namespace {
  7553. // Visits an initialization expression to see if OrigDecl is evaluated in
  7554. // its own initialization and throws a warning if it does.
  7555. class SelfReferenceChecker
  7556. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  7557. Sema &S;
  7558. Decl *OrigDecl;
  7559. bool isRecordType;
  7560. bool isPODType;
  7561. bool isReferenceType;
  7562. bool isInitList;
  7563. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  7564. public:
  7565. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  7566. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  7567. S(S), OrigDecl(OrigDecl) {
  7568. isPODType = false;
  7569. isRecordType = false;
  7570. isReferenceType = false;
  7571. isInitList = false;
  7572. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  7573. isPODType = VD->getType().isPODType(S.Context);
  7574. isRecordType = VD->getType()->isRecordType();
  7575. isReferenceType = VD->getType()->isReferenceType();
  7576. }
  7577. }
  7578. // For most expressions, just call the visitor. For initializer lists,
  7579. // track the index of the field being initialized since fields are
  7580. // initialized in order allowing use of previously initialized fields.
  7581. void CheckExpr(Expr *E) {
  7582. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  7583. if (!InitList) {
  7584. Visit(E);
  7585. return;
  7586. }
  7587. // Track and increment the index here.
  7588. isInitList = true;
  7589. InitFieldIndex.push_back(0);
  7590. for (auto Child : InitList->children()) {
  7591. CheckExpr(cast<Expr>(Child));
  7592. ++InitFieldIndex.back();
  7593. }
  7594. InitFieldIndex.pop_back();
  7595. }
  7596. // Returns true if MemberExpr is checked and no futher checking is needed.
  7597. // Returns false if additional checking is required.
  7598. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  7599. llvm::SmallVector<FieldDecl*, 4> Fields;
  7600. Expr *Base = E;
  7601. bool ReferenceField = false;
  7602. // Get the field memebers used.
  7603. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7604. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  7605. if (!FD)
  7606. return false;
  7607. Fields.push_back(FD);
  7608. if (FD->getType()->isReferenceType())
  7609. ReferenceField = true;
  7610. Base = ME->getBase()->IgnoreParenImpCasts();
  7611. }
  7612. // Keep checking only if the base Decl is the same.
  7613. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  7614. if (!DRE || DRE->getDecl() != OrigDecl)
  7615. return false;
  7616. // A reference field can be bound to an unininitialized field.
  7617. if (CheckReference && !ReferenceField)
  7618. return true;
  7619. // Convert FieldDecls to their index number.
  7620. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  7621. for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) {
  7622. UsedFieldIndex.push_back((*I)->getFieldIndex());
  7623. }
  7624. // See if a warning is needed by checking the first difference in index
  7625. // numbers. If field being used has index less than the field being
  7626. // initialized, then the use is safe.
  7627. for (auto UsedIter = UsedFieldIndex.begin(),
  7628. UsedEnd = UsedFieldIndex.end(),
  7629. OrigIter = InitFieldIndex.begin(),
  7630. OrigEnd = InitFieldIndex.end();
  7631. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  7632. if (*UsedIter < *OrigIter)
  7633. return true;
  7634. if (*UsedIter > *OrigIter)
  7635. break;
  7636. }
  7637. // TODO: Add a different warning which will print the field names.
  7638. HandleDeclRefExpr(DRE);
  7639. return true;
  7640. }
  7641. // For most expressions, the cast is directly above the DeclRefExpr.
  7642. // For conditional operators, the cast can be outside the conditional
  7643. // operator if both expressions are DeclRefExpr's.
  7644. void HandleValue(Expr *E) {
  7645. E = E->IgnoreParens();
  7646. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  7647. HandleDeclRefExpr(DRE);
  7648. return;
  7649. }
  7650. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  7651. Visit(CO->getCond());
  7652. HandleValue(CO->getTrueExpr());
  7653. HandleValue(CO->getFalseExpr());
  7654. return;
  7655. }
  7656. if (BinaryConditionalOperator *BCO =
  7657. dyn_cast<BinaryConditionalOperator>(E)) {
  7658. Visit(BCO->getCond());
  7659. HandleValue(BCO->getFalseExpr());
  7660. return;
  7661. }
  7662. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  7663. HandleValue(OVE->getSourceExpr());
  7664. return;
  7665. }
  7666. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  7667. if (BO->getOpcode() == BO_Comma) {
  7668. Visit(BO->getLHS());
  7669. HandleValue(BO->getRHS());
  7670. return;
  7671. }
  7672. }
  7673. if (isa<MemberExpr>(E)) {
  7674. if (isInitList) {
  7675. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  7676. false /*CheckReference*/))
  7677. return;
  7678. }
  7679. Expr *Base = E->IgnoreParenImpCasts();
  7680. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7681. // Check for static member variables and don't warn on them.
  7682. if (!isa<FieldDecl>(ME->getMemberDecl()))
  7683. return;
  7684. Base = ME->getBase()->IgnoreParenImpCasts();
  7685. }
  7686. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  7687. HandleDeclRefExpr(DRE);
  7688. return;
  7689. }
  7690. Visit(E);
  7691. }
  7692. // Reference types not handled in HandleValue are handled here since all
  7693. // uses of references are bad, not just r-value uses.
  7694. void VisitDeclRefExpr(DeclRefExpr *E) {
  7695. if (isReferenceType)
  7696. HandleDeclRefExpr(E);
  7697. }
  7698. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  7699. if (E->getCastKind() == CK_LValueToRValue) {
  7700. HandleValue(E->getSubExpr());
  7701. return;
  7702. }
  7703. Inherited::VisitImplicitCastExpr(E);
  7704. }
  7705. void VisitMemberExpr(MemberExpr *E) {
  7706. if (isInitList) {
  7707. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  7708. return;
  7709. }
  7710. // Don't warn on arrays since they can be treated as pointers.
  7711. if (E->getType()->canDecayToPointerType()) return;
  7712. // Warn when a non-static method call is followed by non-static member
  7713. // field accesses, which is followed by a DeclRefExpr.
  7714. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  7715. bool Warn = (MD && !MD->isStatic());
  7716. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  7717. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7718. if (!isa<FieldDecl>(ME->getMemberDecl()))
  7719. Warn = false;
  7720. Base = ME->getBase()->IgnoreParenImpCasts();
  7721. }
  7722. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  7723. if (Warn)
  7724. HandleDeclRefExpr(DRE);
  7725. return;
  7726. }
  7727. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  7728. // Visit that expression.
  7729. Visit(Base);
  7730. }
  7731. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  7732. Expr *Callee = E->getCallee();
  7733. if (isa<UnresolvedLookupExpr>(Callee))
  7734. return Inherited::VisitCXXOperatorCallExpr(E);
  7735. Visit(Callee);
  7736. for (auto Arg: E->arguments())
  7737. HandleValue(Arg->IgnoreParenImpCasts());
  7738. }
  7739. void VisitUnaryOperator(UnaryOperator *E) {
  7740. // For POD record types, addresses of its own members are well-defined.
  7741. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  7742. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  7743. if (!isPODType)
  7744. HandleValue(E->getSubExpr());
  7745. return;
  7746. }
  7747. if (E->isIncrementDecrementOp()) {
  7748. HandleValue(E->getSubExpr());
  7749. return;
  7750. }
  7751. Inherited::VisitUnaryOperator(E);
  7752. }
  7753. void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
  7754. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  7755. if (E->getConstructor()->isCopyConstructor()) {
  7756. Expr *ArgExpr = E->getArg(0);
  7757. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  7758. if (ILE->getNumInits() == 1)
  7759. ArgExpr = ILE->getInit(0);
  7760. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  7761. if (ICE->getCastKind() == CK_NoOp)
  7762. ArgExpr = ICE->getSubExpr();
  7763. HandleValue(ArgExpr);
  7764. return;
  7765. }
  7766. Inherited::VisitCXXConstructExpr(E);
  7767. }
  7768. void VisitCallExpr(CallExpr *E) {
  7769. // Treat std::move as a use.
  7770. if (E->getNumArgs() == 1) {
  7771. if (FunctionDecl *FD = E->getDirectCallee()) {
  7772. if (FD->isInStdNamespace() && FD->getIdentifier() &&
  7773. FD->getIdentifier()->isStr("move")) {
  7774. HandleValue(E->getArg(0));
  7775. return;
  7776. }
  7777. }
  7778. }
  7779. Inherited::VisitCallExpr(E);
  7780. }
  7781. void VisitBinaryOperator(BinaryOperator *E) {
  7782. if (E->isCompoundAssignmentOp()) {
  7783. HandleValue(E->getLHS());
  7784. Visit(E->getRHS());
  7785. return;
  7786. }
  7787. Inherited::VisitBinaryOperator(E);
  7788. }
  7789. // A custom visitor for BinaryConditionalOperator is needed because the
  7790. // regular visitor would check the condition and true expression separately
  7791. // but both point to the same place giving duplicate diagnostics.
  7792. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  7793. Visit(E->getCond());
  7794. Visit(E->getFalseExpr());
  7795. }
  7796. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  7797. Decl* ReferenceDecl = DRE->getDecl();
  7798. if (OrigDecl != ReferenceDecl) return;
  7799. unsigned diag;
  7800. if (isReferenceType) {
  7801. diag = diag::warn_uninit_self_reference_in_reference_init;
  7802. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  7803. diag = diag::warn_static_self_reference_in_init;
  7804. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  7805. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  7806. DRE->getDecl()->getType()->isRecordType()) {
  7807. diag = diag::warn_uninit_self_reference_in_init;
  7808. } else {
  7809. // Local variables will be handled by the CFG analysis.
  7810. return;
  7811. }
  7812. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  7813. S.PDiag(diag)
  7814. << DRE->getNameInfo().getName()
  7815. << OrigDecl->getLocation()
  7816. << DRE->getSourceRange());
  7817. }
  7818. };
  7819. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  7820. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  7821. bool DirectInit) {
  7822. // Parameters arguments are occassionially constructed with itself,
  7823. // for instance, in recursive functions. Skip them.
  7824. if (isa<ParmVarDecl>(OrigDecl))
  7825. return;
  7826. E = E->IgnoreParens();
  7827. // Skip checking T a = a where T is not a record or reference type.
  7828. // Doing so is a way to silence uninitialized warnings.
  7829. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  7830. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  7831. if (ICE->getCastKind() == CK_LValueToRValue)
  7832. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  7833. if (DRE->getDecl() == OrigDecl)
  7834. return;
  7835. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  7836. }
  7837. }
  7838. /// AddInitializerToDecl - Adds the initializer Init to the
  7839. /// declaration dcl. If DirectInit is true, this is C++ direct
  7840. /// initialization rather than copy initialization.
  7841. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
  7842. bool DirectInit, bool TypeMayContainAuto) {
  7843. // If there is no declaration, there was an error parsing it. Just ignore
  7844. // the initializer.
  7845. if (!RealDecl || RealDecl->isInvalidDecl()) {
  7846. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  7847. return;
  7848. }
  7849. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  7850. // Pure-specifiers are handled in ActOnPureSpecifier.
  7851. Diag(Method->getLocation(), diag::err_member_function_initialization)
  7852. << Method->getDeclName() << Init->getSourceRange();
  7853. Method->setInvalidDecl();
  7854. return;
  7855. }
  7856. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  7857. if (!VDecl) {
  7858. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  7859. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  7860. RealDecl->setInvalidDecl();
  7861. return;
  7862. }
  7863. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  7864. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  7865. if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
  7866. // Attempt typo correction early so that the type of the init expression can
  7867. // be deduced based on the chosen correction:if the original init contains a
  7868. // TypoExpr.
  7869. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  7870. if (!Res.isUsable()) {
  7871. RealDecl->setInvalidDecl();
  7872. return;
  7873. }
  7874. if (Res.get() != Init) {
  7875. Init = Res.get();
  7876. if (CXXDirectInit)
  7877. CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  7878. }
  7879. Expr *DeduceInit = Init;
  7880. // Initializer could be a C++ direct-initializer. Deduction only works if it
  7881. // contains exactly one expression.
  7882. if (CXXDirectInit) {
  7883. if (CXXDirectInit->getNumExprs() == 0) {
  7884. // It isn't possible to write this directly, but it is possible to
  7885. // end up in this situation with "auto x(some_pack...);"
  7886. Diag(CXXDirectInit->getLocStart(),
  7887. VDecl->isInitCapture() ? diag::err_init_capture_no_expression
  7888. : diag::err_auto_var_init_no_expression)
  7889. << VDecl->getDeclName() << VDecl->getType()
  7890. << VDecl->getSourceRange();
  7891. RealDecl->setInvalidDecl();
  7892. return;
  7893. } else if (CXXDirectInit->getNumExprs() > 1) {
  7894. Diag(CXXDirectInit->getExpr(1)->getLocStart(),
  7895. VDecl->isInitCapture()
  7896. ? diag::err_init_capture_multiple_expressions
  7897. : diag::err_auto_var_init_multiple_expressions)
  7898. << VDecl->getDeclName() << VDecl->getType()
  7899. << VDecl->getSourceRange();
  7900. RealDecl->setInvalidDecl();
  7901. return;
  7902. } else {
  7903. DeduceInit = CXXDirectInit->getExpr(0);
  7904. if (isa<InitListExpr>(DeduceInit))
  7905. Diag(CXXDirectInit->getLocStart(),
  7906. diag::err_auto_var_init_paren_braces)
  7907. << VDecl->getDeclName() << VDecl->getType()
  7908. << VDecl->getSourceRange();
  7909. }
  7910. }
  7911. // Expressions default to 'id' when we're in a debugger.
  7912. bool DefaultedToAuto = false;
  7913. if (getLangOpts().DebuggerCastResultToId &&
  7914. Init->getType() == Context.UnknownAnyTy) {
  7915. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  7916. if (Result.isInvalid()) {
  7917. VDecl->setInvalidDecl();
  7918. return;
  7919. }
  7920. Init = Result.get();
  7921. DefaultedToAuto = true;
  7922. }
  7923. QualType DeducedType;
  7924. if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
  7925. DAR_Failed)
  7926. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  7927. if (DeducedType.isNull()) {
  7928. RealDecl->setInvalidDecl();
  7929. return;
  7930. }
  7931. VDecl->setType(DeducedType);
  7932. assert(VDecl->isLinkageValid());
  7933. // In ARC, infer lifetime.
  7934. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  7935. VDecl->setInvalidDecl();
  7936. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  7937. // 'id' instead of a specific object type prevents most of our usual checks.
  7938. // We only want to warn outside of template instantiations, though:
  7939. // inside a template, the 'id' could have come from a parameter.
  7940. if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
  7941. DeducedType->isObjCIdType()) {
  7942. SourceLocation Loc =
  7943. VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
  7944. Diag(Loc, diag::warn_auto_var_is_id)
  7945. << VDecl->getDeclName() << DeduceInit->getSourceRange();
  7946. }
  7947. // If this is a redeclaration, check that the type we just deduced matches
  7948. // the previously declared type.
  7949. assert(!getLangOpts().HLSL && "auto types are not supported - merge type below is inconsequential"); // HLSL Change
  7950. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  7951. // We never need to merge the type, because we cannot form an incomplete
  7952. // array of auto, nor deduce such a type.
  7953. ShadowMergeState MergeState = ShadowMergeState_Disallowed; // HLSL Change - add merge state
  7954. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false, MergeState); // HLSL Change - add merge state
  7955. }
  7956. // Check the deduced type is valid for a variable declaration.
  7957. CheckVariableDeclarationType(VDecl);
  7958. if (VDecl->isInvalidDecl())
  7959. return;
  7960. // If all looks well, warn if this is a case that will change meaning when
  7961. // we implement N3922.
  7962. if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) {
  7963. Diag(Init->getLocStart(),
  7964. diag::warn_auto_var_direct_list_init)
  7965. << FixItHint::CreateInsertion(Init->getLocStart(), "=");
  7966. }
  7967. }
  7968. // dllimport cannot be used on variable definitions.
  7969. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  7970. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  7971. VDecl->setInvalidDecl();
  7972. return;
  7973. }
  7974. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  7975. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  7976. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  7977. VDecl->setInvalidDecl();
  7978. return;
  7979. }
  7980. if (!VDecl->getType()->isDependentType()) {
  7981. // A definition must end up with a complete type, which means it must be
  7982. // complete with the restriction that an array type might be completed by
  7983. // the initializer; note that later code assumes this restriction.
  7984. QualType BaseDeclType = VDecl->getType();
  7985. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  7986. BaseDeclType = Array->getElementType();
  7987. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  7988. diag::err_typecheck_decl_incomplete_type)) {
  7989. RealDecl->setInvalidDecl();
  7990. return;
  7991. }
  7992. // The variable can not have an abstract class type.
  7993. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  7994. diag::err_abstract_type_in_decl,
  7995. AbstractVariableType))
  7996. VDecl->setInvalidDecl();
  7997. }
  7998. VarDecl *Def;
  7999. if ((Def = VDecl->getDefinition()) && Def != VDecl) {
  8000. NamedDecl *Hidden = nullptr;
  8001. if (!hasVisibleDefinition(Def, &Hidden) &&
  8002. (VDecl->getFormalLinkage() == InternalLinkage ||
  8003. VDecl->getDescribedVarTemplate() ||
  8004. VDecl->getNumTemplateParameterLists() ||
  8005. VDecl->getDeclContext()->isDependentContext())) {
  8006. // The previous definition is hidden, and multiple definitions are
  8007. // permitted (in separate TUs). Form another definition of it.
  8008. } else {
  8009. Diag(VDecl->getLocation(), diag::err_redefinition)
  8010. << VDecl->getDeclName();
  8011. Diag(Def->getLocation(), diag::note_previous_definition);
  8012. VDecl->setInvalidDecl();
  8013. return;
  8014. }
  8015. }
  8016. if (getLangOpts().CPlusPlus) {
  8017. // C++ [class.static.data]p4
  8018. // If a static data member is of const integral or const
  8019. // enumeration type, its declaration in the class definition can
  8020. // specify a constant-initializer which shall be an integral
  8021. // constant expression (5.19). In that case, the member can appear
  8022. // in integral constant expressions. The member shall still be
  8023. // defined in a namespace scope if it is used in the program and the
  8024. // namespace scope definition shall not contain an initializer.
  8025. //
  8026. // We already performed a redefinition check above, but for static
  8027. // data members we also need to check whether there was an in-class
  8028. // declaration with an initializer.
  8029. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  8030. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  8031. << VDecl->getDeclName();
  8032. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  8033. diag::note_previous_initializer)
  8034. << 0;
  8035. return;
  8036. }
  8037. if (VDecl->hasLocalStorage())
  8038. getCurFunction()->setHasBranchProtectedScope();
  8039. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  8040. VDecl->setInvalidDecl();
  8041. return;
  8042. }
  8043. }
  8044. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  8045. // a kernel function cannot be initialized."
  8046. if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
  8047. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  8048. VDecl->setInvalidDecl();
  8049. return;
  8050. }
  8051. // Get the decls type and save a reference for later, since
  8052. // CheckInitializerTypes may change it.
  8053. QualType DclT = VDecl->getType(), SavT = DclT;
  8054. // Expressions default to 'id' when we're in a debugger
  8055. // and we are assigning it to a variable of Objective-C pointer type.
  8056. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  8057. Init->getType() == Context.UnknownAnyTy) {
  8058. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  8059. if (Result.isInvalid()) {
  8060. VDecl->setInvalidDecl();
  8061. return;
  8062. }
  8063. Init = Result.get();
  8064. }
  8065. // Perform the initialization.
  8066. if (!VDecl->isInvalidDecl()) {
  8067. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  8068. InitializationKind Kind
  8069. = DirectInit ?
  8070. CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
  8071. Init->getLocStart(),
  8072. Init->getLocEnd())
  8073. : InitializationKind::CreateDirectList(
  8074. VDecl->getLocation())
  8075. : InitializationKind::CreateCopy(VDecl->getLocation(),
  8076. Init->getLocStart());
  8077. MultiExprArg Args = Init;
  8078. if (CXXDirectInit)
  8079. Args = MultiExprArg(CXXDirectInit->getExprs(),
  8080. CXXDirectInit->getNumExprs());
  8081. // Try to correct any TypoExprs in the initialization arguments.
  8082. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  8083. ExprResult Res = CorrectDelayedTyposInExpr(
  8084. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  8085. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  8086. return Init.Failed() ? ExprError() : E;
  8087. });
  8088. if (Res.isInvalid()) {
  8089. VDecl->setInvalidDecl();
  8090. } else if (Res.get() != Args[Idx]) {
  8091. Args[Idx] = Res.get();
  8092. }
  8093. }
  8094. if (VDecl->isInvalidDecl())
  8095. return;
  8096. InitializationSequence InitSeq(*this, Entity, Kind, Args);
  8097. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  8098. if (Result.isInvalid()) {
  8099. VDecl->setInvalidDecl();
  8100. return;
  8101. }
  8102. Init = Result.getAs<Expr>();
  8103. assert(Init != nullptr && "otherwise result should be invalid"); // HLSL Change
  8104. }
  8105. // Check for self-references within variable initializers.
  8106. // Variables declared within a function/method body (except for references)
  8107. // are handled by a dataflow analysis.
  8108. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  8109. VDecl->getType()->isReferenceType()) {
  8110. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  8111. }
  8112. // If the type changed, it means we had an incomplete type that was
  8113. // completed by the initializer. For example:
  8114. // int ary[] = { 1, 3, 5 };
  8115. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  8116. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  8117. VDecl->setType(DclT);
  8118. #if 0 // HLSL Change Starts - no ObjC support
  8119. if (!VDecl->isInvalidDecl()) {
  8120. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  8121. if (VDecl->hasAttr<BlocksAttr>())
  8122. checkRetainCycles(VDecl, Init);
  8123. // It is safe to assign a weak reference into a strong variable.
  8124. // Although this code can still have problems:
  8125. // id x = self.weakProp;
  8126. // id y = self.weakProp;
  8127. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  8128. // paths through the function. This should be revisited if
  8129. // -Wrepeated-use-of-weak is made flow-sensitive.
  8130. if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
  8131. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  8132. Init->getLocStart()))
  8133. getCurFunction()->markSafeWeakUse(Init);
  8134. }
  8135. #endif // HLSL Change Ends - no ObjC support
  8136. // The initialization is usually a full-expression.
  8137. //
  8138. // FIXME: If this is a braced initialization of an aggregate, it is not
  8139. // an expression, and each individual field initializer is a separate
  8140. // full-expression. For instance, in:
  8141. //
  8142. // struct Temp { ~Temp(); };
  8143. // struct S { S(Temp); };
  8144. // struct T { S a, b; } t = { Temp(), Temp() }
  8145. //
  8146. // we should destroy the first Temp before constructing the second.
  8147. ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
  8148. false,
  8149. VDecl->isConstexpr());
  8150. if (Result.isInvalid()) {
  8151. VDecl->setInvalidDecl();
  8152. return;
  8153. }
  8154. Init = Result.get();
  8155. // Attach the initializer to the decl.
  8156. VDecl->setInit(Init);
  8157. if (VDecl->isLocalVarDecl()) {
  8158. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  8159. // static storage duration shall be constant expressions or string literals.
  8160. // C++ does not have this restriction.
  8161. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
  8162. const Expr *Culprit;
  8163. if (VDecl->getStorageClass() == SC_Static)
  8164. CheckForConstantInitializer(Init, DclT);
  8165. // C89 is stricter than C99 for non-static aggregate types.
  8166. // C89 6.5.7p3: All the expressions [...] in an initializer list
  8167. // for an object that has aggregate or union type shall be
  8168. // constant expressions.
  8169. else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  8170. isa<InitListExpr>(Init) &&
  8171. !Init->isConstantInitializer(Context, false, &Culprit))
  8172. Diag(Culprit->getExprLoc(),
  8173. diag::ext_aggregate_init_not_constant)
  8174. << Culprit->getSourceRange();
  8175. }
  8176. } else if (VDecl->isStaticDataMember() &&
  8177. VDecl->getLexicalDeclContext()->isRecord()) {
  8178. // This is an in-class initialization for a static data member, e.g.,
  8179. //
  8180. // struct S {
  8181. // static const int value = 17;
  8182. // };
  8183. // C++ [class.mem]p4:
  8184. // A member-declarator can contain a constant-initializer only
  8185. // if it declares a static member (9.4) of const integral or
  8186. // const enumeration type, see 9.4.2.
  8187. //
  8188. // C++11 [class.static.data]p3:
  8189. // If a non-volatile const static data member is of integral or
  8190. // enumeration type, its declaration in the class definition can
  8191. // specify a brace-or-equal-initializer in which every initalizer-clause
  8192. // that is an assignment-expression is a constant expression. A static
  8193. // data member of literal type can be declared in the class definition
  8194. // with the constexpr specifier; if so, its declaration shall specify a
  8195. // brace-or-equal-initializer in which every initializer-clause that is
  8196. // an assignment-expression is a constant expression.
  8197. // Do nothing on dependent types.
  8198. if (DclT->isDependentType()) {
  8199. // Allow any 'static constexpr' members, whether or not they are of literal
  8200. // type. We separately check that every constexpr variable is of literal
  8201. // type.
  8202. } else if (VDecl->isConstexpr()) {
  8203. // Require constness.
  8204. } else if (!DclT.isConstQualified()) {
  8205. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  8206. << Init->getSourceRange();
  8207. VDecl->setInvalidDecl();
  8208. // We allow integer constant expressions in all cases.
  8209. } else if (DclT->isIntegralOrEnumerationType()) {
  8210. // Check whether the expression is a constant expression.
  8211. SourceLocation Loc;
  8212. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  8213. // In C++11, a non-constexpr const static data member with an
  8214. // in-class initializer cannot be volatile.
  8215. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  8216. else if (Init->isValueDependent())
  8217. ; // Nothing to check.
  8218. else if (Init->isIntegerConstantExpr(Context, &Loc))
  8219. ; // Ok, it's an ICE!
  8220. else if (Init->isEvaluatable(Context)) {
  8221. // If we can constant fold the initializer through heroics, accept it,
  8222. // but report this as a use of an extension for -pedantic.
  8223. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  8224. << Init->getSourceRange();
  8225. } else {
  8226. // Otherwise, this is some crazy unknown case. Report the issue at the
  8227. // location provided by the isIntegerConstantExpr failed check.
  8228. Diag(Loc, diag::err_in_class_initializer_non_constant)
  8229. << Init->getSourceRange();
  8230. VDecl->setInvalidDecl();
  8231. }
  8232. // We allow foldable floating-point constants as an extension.
  8233. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  8234. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  8235. // it anyway and provide a fixit to add the 'constexpr'.
  8236. if (getLangOpts().CPlusPlus11) {
  8237. Diag(VDecl->getLocation(),
  8238. diag::ext_in_class_initializer_float_type_cxx11)
  8239. << DclT << Init->getSourceRange();
  8240. Diag(VDecl->getLocStart(),
  8241. diag::note_in_class_initializer_float_type_cxx11)
  8242. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  8243. } else {
  8244. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  8245. << DclT << Init->getSourceRange();
  8246. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  8247. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  8248. << Init->getSourceRange();
  8249. VDecl->setInvalidDecl();
  8250. }
  8251. }
  8252. // Suggest adding 'constexpr' in C++11 for literal types.
  8253. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  8254. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  8255. << DclT << Init->getSourceRange()
  8256. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  8257. VDecl->setConstexpr(true);
  8258. } else {
  8259. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  8260. << DclT << Init->getSourceRange();
  8261. VDecl->setInvalidDecl();
  8262. }
  8263. } else if (VDecl->isFileVarDecl()) {
  8264. if (VDecl->getStorageClass() == SC_Extern &&
  8265. (!getLangOpts().CPlusPlus ||
  8266. !VDecl->isExternC()) &&
  8267. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  8268. Diag(VDecl->getLocation(), diag::warn_extern_init);
  8269. // C99 6.7.8p4. All file scoped initializers need to be constant.
  8270. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  8271. CheckForConstantInitializer(Init, DclT);
  8272. }
  8273. // We will represent direct-initialization similarly to copy-initialization:
  8274. // int x(1); -as-> int x = 1;
  8275. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  8276. //
  8277. // Clients that want to distinguish between the two forms, can check for
  8278. // direct initializer using VarDecl::getInitStyle().
  8279. // A major benefit is that clients that don't particularly care about which
  8280. // exactly form was it (like the CodeGen) can handle both cases without
  8281. // special case code.
  8282. // C++ 8.5p11:
  8283. // The form of initialization (using parentheses or '=') is generally
  8284. // insignificant, but does matter when the entity being initialized has a
  8285. // class type.
  8286. if (CXXDirectInit) {
  8287. assert(DirectInit && "Call-style initializer must be direct init.");
  8288. VDecl->setInitStyle(VarDecl::CallInit);
  8289. } else if (DirectInit) {
  8290. // This must be list-initialization. No other way is direct-initialization.
  8291. VDecl->setInitStyle(VarDecl::ListInit);
  8292. }
  8293. CheckCompleteVariableDeclaration(VDecl);
  8294. }
  8295. /// ActOnInitializerError - Given that there was an error parsing an
  8296. /// initializer for the given declaration, try to return to some form
  8297. /// of sanity.
  8298. void Sema::ActOnInitializerError(Decl *D) {
  8299. // Our main concern here is re-establishing invariants like "a
  8300. // variable's type is either dependent or complete".
  8301. if (!D || D->isInvalidDecl()) return;
  8302. VarDecl *VD = dyn_cast<VarDecl>(D);
  8303. if (!VD) return;
  8304. // Auto types are meaningless if we can't make sense of the initializer.
  8305. if (ParsingInitForAutoVars.count(D)) {
  8306. D->setInvalidDecl();
  8307. return;
  8308. }
  8309. QualType Ty = VD->getType();
  8310. if (Ty->isDependentType()) return;
  8311. // Require a complete type.
  8312. if (RequireCompleteType(VD->getLocation(),
  8313. Context.getBaseElementType(Ty),
  8314. diag::err_typecheck_decl_incomplete_type)) {
  8315. VD->setInvalidDecl();
  8316. return;
  8317. }
  8318. // Require a non-abstract type.
  8319. if (RequireNonAbstractType(VD->getLocation(), Ty,
  8320. diag::err_abstract_type_in_decl,
  8321. AbstractVariableType)) {
  8322. VD->setInvalidDecl();
  8323. return;
  8324. }
  8325. // Don't bother complaining about constructors or destructors,
  8326. // though.
  8327. }
  8328. void Sema::ActOnUninitializedDecl(Decl *RealDecl,
  8329. bool TypeMayContainAuto) {
  8330. // If there is no declaration, there was an error parsing it. Just ignore it.
  8331. if (!RealDecl)
  8332. return;
  8333. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  8334. QualType Type = Var->getType();
  8335. // C++11 [dcl.spec.auto]p3
  8336. if (TypeMayContainAuto && Type->getContainedAutoType()) {
  8337. Diag(Var->getLocation(), diag::err_auto_var_requires_init)
  8338. << Var->getDeclName() << Type;
  8339. Var->setInvalidDecl();
  8340. return;
  8341. }
  8342. // C++11 [class.static.data]p3: A static data member can be declared with
  8343. // the constexpr specifier; if so, its declaration shall specify
  8344. // a brace-or-equal-initializer.
  8345. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  8346. // the definition of a variable [...] or the declaration of a static data
  8347. // member.
  8348. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
  8349. if (Var->isStaticDataMember())
  8350. Diag(Var->getLocation(),
  8351. diag::err_constexpr_static_mem_var_requires_init)
  8352. << Var->getDeclName();
  8353. else
  8354. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  8355. Var->setInvalidDecl();
  8356. return;
  8357. }
  8358. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  8359. // be initialized.
  8360. if (!Var->isInvalidDecl() &&
  8361. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  8362. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  8363. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  8364. Var->setInvalidDecl();
  8365. return;
  8366. }
  8367. switch (Var->isThisDeclarationADefinition()) {
  8368. case VarDecl::Definition:
  8369. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  8370. break;
  8371. // We have an out-of-line definition of a static data member
  8372. // that has an in-class initializer, so we type-check this like
  8373. // a declaration.
  8374. //
  8375. // Fall through
  8376. case VarDecl::DeclarationOnly:
  8377. // It's only a declaration.
  8378. // Block scope. C99 6.7p7: If an identifier for an object is
  8379. // declared with no linkage (C99 6.2.2p6), the type for the
  8380. // object shall be complete.
  8381. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  8382. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  8383. RequireCompleteType(Var->getLocation(), Type,
  8384. diag::err_typecheck_decl_incomplete_type))
  8385. Var->setInvalidDecl();
  8386. // Make sure that the type is not abstract.
  8387. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  8388. RequireNonAbstractType(Var->getLocation(), Type,
  8389. diag::err_abstract_type_in_decl,
  8390. AbstractVariableType))
  8391. Var->setInvalidDecl();
  8392. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  8393. Var->getStorageClass() == SC_PrivateExtern) {
  8394. Diag(Var->getLocation(), diag::warn_private_extern);
  8395. Diag(Var->getLocation(), diag::note_private_extern);
  8396. }
  8397. return;
  8398. case VarDecl::TentativeDefinition:
  8399. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  8400. // object that has file scope without an initializer, and without a
  8401. // storage-class specifier or with the storage-class specifier "static",
  8402. // constitutes a tentative definition. Note: A tentative definition with
  8403. // external linkage is valid (C99 6.2.2p5).
  8404. if (!Var->isInvalidDecl()) {
  8405. if (const IncompleteArrayType *ArrayT
  8406. = Context.getAsIncompleteArrayType(Type)) {
  8407. if (RequireCompleteType(Var->getLocation(),
  8408. ArrayT->getElementType(),
  8409. diag::err_illegal_decl_array_incomplete_type))
  8410. Var->setInvalidDecl();
  8411. } else if (Var->getStorageClass() == SC_Static) {
  8412. // C99 6.9.2p3: If the declaration of an identifier for an object is
  8413. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  8414. // declared type shall not be an incomplete type.
  8415. // NOTE: code such as the following
  8416. // static struct s;
  8417. // struct s { int a; };
  8418. // is accepted by gcc. Hence here we issue a warning instead of
  8419. // an error and we do not invalidate the static declaration.
  8420. // NOTE: to avoid multiple warnings, only check the first declaration.
  8421. if (Var->isFirstDecl())
  8422. RequireCompleteType(Var->getLocation(), Type,
  8423. diag::ext_typecheck_decl_incomplete_type);
  8424. }
  8425. }
  8426. // Record the tentative definition; we're done.
  8427. if (!Var->isInvalidDecl())
  8428. TentativeDefinitions.push_back(Var);
  8429. return;
  8430. }
  8431. // Provide a specific diagnostic for uninitialized variable
  8432. // definitions with incomplete array type.
  8433. if (Type->isIncompleteArrayType()
  8434. // HLSL Change Starts
  8435. // Allow incomplete resource array.
  8436. && !hlsl::IsIncompleteHLSLResourceArrayType(getASTContext(), Type)
  8437. // Allow incomplete ConstantBufferView array.
  8438. && !(IsOnHLSLBufferView())
  8439. // HLSL Change Ends
  8440. ) {
  8441. Diag(Var->getLocation(),
  8442. diag::err_typecheck_incomplete_array_needs_initializer);
  8443. Var->setInvalidDecl();
  8444. return;
  8445. }
  8446. // Provide a specific diagnostic for uninitialized variable
  8447. // definitions with reference type.
  8448. if (Type->isReferenceType()) {
  8449. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  8450. << Var->getDeclName()
  8451. << SourceRange(Var->getLocation(), Var->getLocation());
  8452. Var->setInvalidDecl();
  8453. return;
  8454. }
  8455. // Do not attempt to type-check the default initializer for a
  8456. // variable with dependent type.
  8457. if (Type->isDependentType())
  8458. return;
  8459. if (Var->isInvalidDecl())
  8460. return;
  8461. if (!Var->hasAttr<AliasAttr>()) {
  8462. if (RequireCompleteType(Var->getLocation(),
  8463. Context.getBaseElementType(Type),
  8464. diag::err_typecheck_decl_incomplete_type)) {
  8465. Var->setInvalidDecl();
  8466. return;
  8467. }
  8468. } else {
  8469. return;
  8470. }
  8471. // The variable can not have an abstract class type.
  8472. if (RequireNonAbstractType(Var->getLocation(), Type,
  8473. diag::err_abstract_type_in_decl,
  8474. AbstractVariableType)) {
  8475. Var->setInvalidDecl();
  8476. return;
  8477. }
  8478. // Check for jumps past the implicit initializer. C++0x
  8479. // clarifies that this applies to a "variable with automatic
  8480. // storage duration", not a "local variable".
  8481. // C++11 [stmt.dcl]p3
  8482. // A program that jumps from a point where a variable with automatic
  8483. // storage duration is not in scope to a point where it is in scope is
  8484. // ill-formed unless the variable has scalar type, class type with a
  8485. // trivial default constructor and a trivial destructor, a cv-qualified
  8486. // version of one of these types, or an array of one of the preceding
  8487. // types and is declared without an initializer.
  8488. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  8489. if (const RecordType *Record
  8490. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  8491. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  8492. // Mark the function for further checking even if the looser rules of
  8493. // C++11 do not require such checks, so that we can diagnose
  8494. // incompatibilities with C++98.
  8495. if (!CXXRecord->isPOD())
  8496. getCurFunction()->setHasBranchProtectedScope();
  8497. }
  8498. }
  8499. // C++03 [dcl.init]p9:
  8500. // If no initializer is specified for an object, and the
  8501. // object is of (possibly cv-qualified) non-POD class type (or
  8502. // array thereof), the object shall be default-initialized; if
  8503. // the object is of const-qualified type, the underlying class
  8504. // type shall have a user-declared default
  8505. // constructor. Otherwise, if no initializer is specified for
  8506. // a non- static object, the object and its subobjects, if
  8507. // any, have an indeterminate initial value); if the object
  8508. // or any of its subobjects are of const-qualified type, the
  8509. // program is ill-formed.
  8510. // C++0x [dcl.init]p11:
  8511. // If no initializer is specified for an object, the object is
  8512. // default-initialized; [...].
  8513. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  8514. InitializationKind Kind
  8515. = InitializationKind::CreateDefault(Var->getLocation());
  8516. InitializationSequence InitSeq(*this, Entity, Kind, None);
  8517. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  8518. if (Init.isInvalid())
  8519. Var->setInvalidDecl();
  8520. else if (Init.get()) {
  8521. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  8522. // This is important for template substitution.
  8523. Var->setInitStyle(VarDecl::CallInit);
  8524. }
  8525. CheckCompleteVariableDeclaration(Var);
  8526. }
  8527. }
  8528. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  8529. VarDecl *VD = dyn_cast<VarDecl>(D);
  8530. if (!VD) {
  8531. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  8532. D->setInvalidDecl();
  8533. return;
  8534. }
  8535. VD->setCXXForRangeDecl(true);
  8536. // for-range-declaration cannot be given a storage class specifier.
  8537. int Error = -1;
  8538. switch (VD->getStorageClass()) {
  8539. case SC_None:
  8540. break;
  8541. case SC_Extern:
  8542. Error = 0;
  8543. break;
  8544. case SC_Static:
  8545. Error = 1;
  8546. break;
  8547. case SC_PrivateExtern:
  8548. Error = 2;
  8549. break;
  8550. case SC_Auto:
  8551. Error = 3;
  8552. break;
  8553. case SC_Register:
  8554. Error = 4;
  8555. break;
  8556. case SC_OpenCLWorkGroupLocal:
  8557. llvm_unreachable("Unexpected storage class");
  8558. }
  8559. if (Error != -1) {
  8560. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  8561. << VD->getDeclName() << Error;
  8562. D->setInvalidDecl();
  8563. }
  8564. }
  8565. StmtResult
  8566. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  8567. IdentifierInfo *Ident,
  8568. ParsedAttributes &Attrs,
  8569. SourceLocation AttrEnd) {
  8570. // C++1y [stmt.iter]p1:
  8571. // A range-based for statement of the form
  8572. // for ( for-range-identifier : for-range-initializer ) statement
  8573. // is equivalent to
  8574. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  8575. DeclSpec DS(Attrs.getPool().getFactory());
  8576. const char *PrevSpec;
  8577. unsigned DiagID;
  8578. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  8579. getPrintingPolicy());
  8580. Declarator D(DS, Declarator::ForContext);
  8581. D.SetIdentifier(Ident, IdentLoc);
  8582. D.takeAttributes(Attrs, AttrEnd);
  8583. ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
  8584. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
  8585. EmptyAttrs, IdentLoc);
  8586. Decl *Var = ActOnDeclarator(S, D);
  8587. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  8588. FinalizeDeclaration(Var);
  8589. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  8590. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  8591. }
  8592. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  8593. if (var->isInvalidDecl()) return;
  8594. // In ARC, don't allow jumps past the implicit initialization of a
  8595. // local retaining variable.
  8596. if (getLangOpts().ObjCAutoRefCount &&
  8597. var->hasLocalStorage()) {
  8598. switch (var->getType().getObjCLifetime()) {
  8599. case Qualifiers::OCL_None:
  8600. case Qualifiers::OCL_ExplicitNone:
  8601. case Qualifiers::OCL_Autoreleasing:
  8602. break;
  8603. case Qualifiers::OCL_Weak:
  8604. case Qualifiers::OCL_Strong:
  8605. getCurFunction()->setHasBranchProtectedScope();
  8606. break;
  8607. }
  8608. }
  8609. // Warn about externally-visible variables being defined without a
  8610. // prior declaration. We only want to do this for global
  8611. // declarations, but we also specifically need to avoid doing it for
  8612. // class members because the linkage of an anonymous class can
  8613. // change if it's later given a typedef name.
  8614. if (var->isThisDeclarationADefinition() &&
  8615. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  8616. var->isExternallyVisible() && var->hasLinkage() &&
  8617. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  8618. var->getLocation())) {
  8619. // Find a previous declaration that's not a definition.
  8620. VarDecl *prev = var->getPreviousDecl();
  8621. while (prev && prev->isThisDeclarationADefinition())
  8622. prev = prev->getPreviousDecl();
  8623. if (!prev)
  8624. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  8625. }
  8626. if (var->getTLSKind() == VarDecl::TLS_Static) {
  8627. const Expr *Culprit;
  8628. if (var->getType().isDestructedType()) {
  8629. // GNU C++98 edits for __thread, [basic.start.term]p3:
  8630. // The type of an object with thread storage duration shall not
  8631. // have a non-trivial destructor.
  8632. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  8633. if (getLangOpts().CPlusPlus11)
  8634. Diag(var->getLocation(), diag::note_use_thread_local);
  8635. } else if (getLangOpts().CPlusPlus && var->hasInit() &&
  8636. !var->getInit()->isConstantInitializer(
  8637. Context, var->getType()->isReferenceType(), &Culprit)) {
  8638. // GNU C++98 edits for __thread, [basic.start.init]p4:
  8639. // An object of thread storage duration shall not require dynamic
  8640. // initialization.
  8641. // FIXME: Need strict checking here.
  8642. Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
  8643. << Culprit->getSourceRange();
  8644. if (getLangOpts().CPlusPlus11)
  8645. Diag(var->getLocation(), diag::note_use_thread_local);
  8646. }
  8647. }
  8648. // Apply section attributes and pragmas to global variables.
  8649. bool GlobalStorage = var->hasGlobalStorage();
  8650. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  8651. ActiveTemplateInstantiations.empty()) {
  8652. PragmaStack<StringLiteral *> *Stack = nullptr;
  8653. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  8654. if (var->getType().isConstQualified()
  8655. // HLSL Change: for HLSL, const initialized isn't the same, unless static
  8656. && (!getLangOpts().HLSL ||
  8657. var->getTLSKind() == VarDecl::TLS_Static)
  8658. )
  8659. Stack = &ConstSegStack;
  8660. else if (!var->getInit()) {
  8661. Stack = &BSSSegStack;
  8662. SectionFlags |= ASTContext::PSF_Write;
  8663. } else {
  8664. Stack = &DataSegStack;
  8665. SectionFlags |= ASTContext::PSF_Write;
  8666. }
  8667. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  8668. var->addAttr(SectionAttr::CreateImplicit(
  8669. Context, SectionAttr::Declspec_allocate,
  8670. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  8671. }
  8672. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  8673. if (UnifySection(SA->getName(), SectionFlags, var))
  8674. var->dropAttr<SectionAttr>();
  8675. // Apply the init_seg attribute if this has an initializer. If the
  8676. // initializer turns out to not be dynamic, we'll end up ignoring this
  8677. // attribute.
  8678. if (CurInitSeg && var->getInit())
  8679. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  8680. CurInitSegLoc));
  8681. }
  8682. // All the following checks are C++ only.
  8683. if (!getLangOpts().CPlusPlus) return;
  8684. QualType type = var->getType();
  8685. if (type->isDependentType()) return;
  8686. // __block variables might require us to capture a copy-initializer.
  8687. if (var->hasAttr<BlocksAttr>()) {
  8688. // It's currently invalid to ever have a __block variable with an
  8689. // array type; should we diagnose that here?
  8690. // Regardless, we don't want to ignore array nesting when
  8691. // constructing this copy.
  8692. if (type->isStructureOrClassType()) {
  8693. EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
  8694. SourceLocation poi = var->getLocation();
  8695. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  8696. ExprResult result
  8697. = PerformMoveOrCopyInitialization(
  8698. InitializedEntity::InitializeBlock(poi, type, false),
  8699. var, var->getType(), varRef, /*AllowNRVO=*/true);
  8700. if (!result.isInvalid()) {
  8701. result = MaybeCreateExprWithCleanups(result);
  8702. Expr *init = result.getAs<Expr>();
  8703. Context.setBlockVarCopyInits(var, init);
  8704. }
  8705. }
  8706. }
  8707. Expr *Init = var->getInit();
  8708. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  8709. QualType baseType = Context.getBaseElementType(type);
  8710. if (!var->getDeclContext()->isDependentContext() &&
  8711. Init && !Init->isValueDependent()) {
  8712. if (IsGlobal && !var->isConstexpr() &&
  8713. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  8714. var->getLocation())) {
  8715. // Warn about globals which don't have a constant initializer. Don't
  8716. // warn about globals with a non-trivial destructor because we already
  8717. // warned about them.
  8718. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  8719. if (!(RD && !RD->hasTrivialDestructor()) &&
  8720. !Init->isConstantInitializer(Context, baseType->isReferenceType()))
  8721. Diag(var->getLocation(), diag::warn_global_constructor)
  8722. << Init->getSourceRange();
  8723. }
  8724. if (var->isConstexpr()) {
  8725. SmallVector<PartialDiagnosticAt, 8> Notes;
  8726. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  8727. SourceLocation DiagLoc = var->getLocation();
  8728. // If the note doesn't add any useful information other than a source
  8729. // location, fold it into the primary diagnostic.
  8730. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  8731. diag::note_invalid_subexpr_in_const_expr) {
  8732. DiagLoc = Notes[0].first;
  8733. Notes.clear();
  8734. }
  8735. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  8736. << var << Init->getSourceRange();
  8737. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  8738. Diag(Notes[I].first, Notes[I].second);
  8739. }
  8740. } else if (var->isUsableInConstantExpressions(Context)) {
  8741. // Check whether the initializer of a const variable of integral or
  8742. // enumeration type is an ICE now, since we can't tell whether it was
  8743. // initialized by a constant expression if we check later.
  8744. var->checkInitIsICE();
  8745. }
  8746. }
  8747. // Require the destructor.
  8748. if (const RecordType *recordType = baseType->getAs<RecordType>())
  8749. FinalizeVarWithDestructor(var, recordType);
  8750. }
  8751. /// \brief Determines if a variable's alignment is dependent.
  8752. static bool hasDependentAlignment(VarDecl *VD) {
  8753. if (VD->getType()->isDependentType())
  8754. return true;
  8755. for (auto *I : VD->specific_attrs<AlignedAttr>())
  8756. if (I->isAlignmentDependent())
  8757. return true;
  8758. return false;
  8759. }
  8760. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  8761. /// any semantic actions necessary after any initializer has been attached.
  8762. void
  8763. Sema::FinalizeDeclaration(Decl *ThisDecl) {
  8764. // Note that we are no longer parsing the initializer for this declaration.
  8765. ParsingInitForAutoVars.erase(ThisDecl);
  8766. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  8767. if (!VD)
  8768. return;
  8769. checkAttributesAfterMerging(*this, *VD);
  8770. // Perform TLS alignment check here after attributes attached to the variable
  8771. // which may affect the alignment have been processed. Only perform the check
  8772. // if the target has a maximum TLS alignment (zero means no constraints).
  8773. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  8774. // Protect the check so that it's not performed on dependent types and
  8775. // dependent alignments (we can't determine the alignment in that case).
  8776. if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
  8777. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  8778. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  8779. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  8780. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  8781. << (unsigned)MaxAlignChars.getQuantity();
  8782. }
  8783. }
  8784. }
  8785. // Static locals inherit dll attributes from their function.
  8786. if (VD->isStaticLocal()) {
  8787. if (FunctionDecl *FD =
  8788. dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  8789. if (Attr *A = getDLLAttr(FD)) {
  8790. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  8791. NewAttr->setInherited(true);
  8792. VD->addAttr(NewAttr);
  8793. }
  8794. }
  8795. }
  8796. // Grab the dllimport or dllexport attribute off of the VarDecl.
  8797. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  8798. // Imported static data members cannot be defined out-of-line.
  8799. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  8800. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  8801. VD->isThisDeclarationADefinition()) {
  8802. // We allow definitions of dllimport class template static data members
  8803. // with a warning.
  8804. CXXRecordDecl *Context =
  8805. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  8806. bool IsClassTemplateMember =
  8807. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  8808. Context->getDescribedClassTemplate();
  8809. Diag(VD->getLocation(),
  8810. IsClassTemplateMember
  8811. ? diag::warn_attribute_dllimport_static_field_definition
  8812. : diag::err_attribute_dllimport_static_field_definition);
  8813. Diag(IA->getLocation(), diag::note_attribute);
  8814. if (!IsClassTemplateMember)
  8815. VD->setInvalidDecl();
  8816. }
  8817. }
  8818. // dllimport/dllexport variables cannot be thread local, their TLS index
  8819. // isn't exported with the variable.
  8820. if (DLLAttr && VD->getTLSKind()) {
  8821. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  8822. << DLLAttr;
  8823. VD->setInvalidDecl();
  8824. }
  8825. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  8826. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  8827. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  8828. VD->dropAttr<UsedAttr>();
  8829. }
  8830. }
  8831. const DeclContext *DC = VD->getDeclContext();
  8832. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8833. // member, set the visibility of this variable.
  8834. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  8835. AddPushedVisibilityAttribute(VD);
  8836. // FIXME: Warn on unused templates.
  8837. if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
  8838. !isa<VarTemplatePartialSpecializationDecl>(VD))
  8839. MarkUnusedFileScopedDecl(VD);
  8840. // Now we have parsed the initializer and can update the table of magic
  8841. // tag values.
  8842. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  8843. !VD->getType()->isIntegralOrEnumerationType())
  8844. return;
  8845. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  8846. const Expr *MagicValueExpr = VD->getInit();
  8847. if (!MagicValueExpr) {
  8848. continue;
  8849. }
  8850. llvm::APSInt MagicValueInt;
  8851. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  8852. Diag(I->getRange().getBegin(),
  8853. diag::err_type_tag_for_datatype_not_ice)
  8854. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  8855. continue;
  8856. }
  8857. if (MagicValueInt.getActiveBits() > 64) {
  8858. Diag(I->getRange().getBegin(),
  8859. diag::err_type_tag_for_datatype_too_large)
  8860. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  8861. continue;
  8862. }
  8863. uint64_t MagicValue = MagicValueInt.getZExtValue();
  8864. RegisterTypeTagForDatatype(I->getArgumentKind(),
  8865. MagicValue,
  8866. I->getMatchingCType(),
  8867. I->getLayoutCompatible(),
  8868. I->getMustBeNull());
  8869. }
  8870. }
  8871. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  8872. ArrayRef<Decl *> Group) {
  8873. SmallVector<Decl*, 8> Decls;
  8874. if (DS.isTypeSpecOwned())
  8875. Decls.push_back(DS.getRepAsDecl());
  8876. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  8877. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  8878. if (Decl *D = Group[i]) {
  8879. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
  8880. if (!FirstDeclaratorInGroup)
  8881. FirstDeclaratorInGroup = DD;
  8882. Decls.push_back(D);
  8883. }
  8884. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  8885. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  8886. handleTagNumbering(Tag, S);
  8887. if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
  8888. Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
  8889. }
  8890. }
  8891. return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
  8892. }
  8893. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  8894. /// group, performing any necessary semantic checking.
  8895. Sema::DeclGroupPtrTy
  8896. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
  8897. bool TypeMayContainAuto) {
  8898. // C++0x [dcl.spec.auto]p7:
  8899. // If the type deduced for the template parameter U is not the same in each
  8900. // deduction, the program is ill-formed.
  8901. // FIXME: When initializer-list support is added, a distinction is needed
  8902. // between the deduced type U and the deduced type which 'auto' stands for.
  8903. // auto a = 0, b = { 1, 2, 3 };
  8904. // is legal because the deduced type U is 'int' in both cases.
  8905. if (TypeMayContainAuto && Group.size() > 1) {
  8906. QualType Deduced;
  8907. CanQualType DeducedCanon;
  8908. VarDecl *DeducedDecl = nullptr;
  8909. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  8910. if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
  8911. AutoType *AT = D->getType()->getContainedAutoType();
  8912. // Don't reissue diagnostics when instantiating a template.
  8913. if (AT && D->isInvalidDecl())
  8914. break;
  8915. QualType U = AT ? AT->getDeducedType() : QualType();
  8916. if (!U.isNull()) {
  8917. CanQualType UCanon = Context.getCanonicalType(U);
  8918. if (Deduced.isNull()) {
  8919. Deduced = U;
  8920. DeducedCanon = UCanon;
  8921. DeducedDecl = D;
  8922. } else if (DeducedCanon != UCanon) {
  8923. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  8924. diag::err_auto_different_deductions)
  8925. << (AT->isDecltypeAuto() ? 1 : 0)
  8926. << Deduced << DeducedDecl->getDeclName()
  8927. << U << D->getDeclName()
  8928. << DeducedDecl->getInit()->getSourceRange()
  8929. << D->getInit()->getSourceRange();
  8930. D->setInvalidDecl();
  8931. break;
  8932. }
  8933. }
  8934. }
  8935. }
  8936. }
  8937. ActOnDocumentableDecls(Group);
  8938. return DeclGroupPtrTy::make(
  8939. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  8940. }
  8941. void Sema::ActOnDocumentableDecl(Decl *D) {
  8942. ActOnDocumentableDecls(D);
  8943. }
  8944. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  8945. // Don't parse the comment if Doxygen diagnostics are ignored.
  8946. if (Group.empty() || !Group[0])
  8947. return;
  8948. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  8949. Group[0]->getLocation()) &&
  8950. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  8951. Group[0]->getLocation()))
  8952. return;
  8953. if (Group.size() >= 2) {
  8954. // This is a decl group. Normally it will contain only declarations
  8955. // produced from declarator list. But in case we have any definitions or
  8956. // additional declaration references:
  8957. // 'typedef struct S {} S;'
  8958. // 'typedef struct S *S;'
  8959. // 'struct S *pS;'
  8960. // FinalizeDeclaratorGroup adds these as separate declarations.
  8961. Decl *MaybeTagDecl = Group[0];
  8962. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  8963. Group = Group.slice(1);
  8964. }
  8965. }
  8966. // See if there are any new comments that are not attached to a decl.
  8967. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  8968. if (!Comments.empty() &&
  8969. !Comments.back()->isAttached()) {
  8970. // There is at least one comment that not attached to a decl.
  8971. // Maybe it should be attached to one of these decls?
  8972. //
  8973. // Note that this way we pick up not only comments that precede the
  8974. // declaration, but also comments that *follow* the declaration -- thanks to
  8975. // the lookahead in the lexer: we've consumed the semicolon and looked
  8976. // ahead through comments.
  8977. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  8978. Context.getCommentForDecl(Group[i], &PP);
  8979. }
  8980. }
  8981. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  8982. /// to introduce parameters into function prototype scope.
  8983. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  8984. const DeclSpec &DS = D.getDeclSpec();
  8985. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  8986. // C++03 [dcl.stc]p2 also permits 'auto'.
  8987. StorageClass SC = SC_None;
  8988. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  8989. SC = SC_Register;
  8990. } else if (getLangOpts().CPlusPlus &&
  8991. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  8992. SC = SC_Auto;
  8993. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  8994. Diag(DS.getStorageClassSpecLoc(),
  8995. diag::err_invalid_storage_class_in_func_decl);
  8996. D.getMutableDeclSpec().ClearStorageClassSpecs();
  8997. }
  8998. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  8999. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  9000. << DeclSpec::getSpecifierName(TSCS);
  9001. if (DS.isConstexprSpecified())
  9002. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  9003. << 0;
  9004. DiagnoseFunctionSpecifiers(DS);
  9005. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  9006. QualType parmDeclType = TInfo->getType();
  9007. if (getLangOpts().CPlusPlus) {
  9008. // Check that there are no default arguments inside the type of this
  9009. // parameter.
  9010. CheckExtraCXXDefaultArguments(D);
  9011. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  9012. if (D.getCXXScopeSpec().isSet()) {
  9013. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  9014. << D.getCXXScopeSpec().getRange();
  9015. D.getCXXScopeSpec().clear();
  9016. }
  9017. }
  9018. // Ensure we have a valid name
  9019. IdentifierInfo *II = nullptr;
  9020. if (D.hasName()) {
  9021. II = D.getIdentifier();
  9022. if (!II) {
  9023. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  9024. << GetNameForDeclarator(D).getName();
  9025. D.setInvalidType(true);
  9026. }
  9027. }
  9028. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  9029. if (II) {
  9030. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  9031. ForRedeclaration);
  9032. LookupName(R, S);
  9033. if (R.isSingleResult()) {
  9034. NamedDecl *PrevDecl = R.getFoundDecl();
  9035. if (PrevDecl->isTemplateParameter()) {
  9036. // Maybe we will complain about the shadowed template parameter.
  9037. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  9038. // Just pretend that we didn't see the previous declaration.
  9039. PrevDecl = nullptr;
  9040. } else if (S->isDeclScope(PrevDecl)) {
  9041. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  9042. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  9043. // Recover by removing the name
  9044. II = nullptr;
  9045. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  9046. D.setInvalidType(true);
  9047. }
  9048. }
  9049. }
  9050. // HLSL Change Starts
  9051. if (getLangOpts().HLSL) {
  9052. const bool IsParm = true;
  9053. if (!DiagnoseHLSLDecl(D, Context.getTranslationUnitDecl(), TInfo, IsParm)) {
  9054. assert(D.isInvalidType() && "otherwise DiagnoseHLSLDecl failed but "
  9055. "didn't invalidate declaration");
  9056. }
  9057. }
  9058. // HLSL Change Ends
  9059. // Temporarily put parameter variables in the translation unit, not
  9060. // the enclosing context. This prevents them from accidentally
  9061. // looking like class members in C++.
  9062. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  9063. D.getLocStart(),
  9064. D.getIdentifierLoc(), II,
  9065. parmDeclType, TInfo,
  9066. SC, hlsl::ParamModFromAttributeList(DS.getAttributes().getList())); // HLSL Change
  9067. if (D.isInvalidType())
  9068. New->setInvalidDecl();
  9069. TransferUnusualAttributes(D, New); // HLSL Change
  9070. assert(S->isFunctionPrototypeScope());
  9071. assert(S->getFunctionPrototypeDepth() >= 1);
  9072. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  9073. S->getNextFunctionPrototypeIndex());
  9074. // Add the parameter declaration into this scope.
  9075. S->AddDecl(New);
  9076. if (II)
  9077. IdResolver.AddDecl(New);
  9078. ProcessDeclAttributes(S, New, D);
  9079. if (D.getDeclSpec().isModulePrivateSpecified())
  9080. Diag(New->getLocation(), diag::err_module_private_local)
  9081. << 1 << New->getDeclName()
  9082. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  9083. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  9084. if (New->hasAttr<BlocksAttr>()) {
  9085. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  9086. }
  9087. return New;
  9088. }
  9089. /// \brief Synthesizes a variable for a parameter arising from a
  9090. /// typedef.
  9091. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  9092. SourceLocation Loc,
  9093. QualType T) {
  9094. /* FIXME: setting StartLoc == Loc.
  9095. Would it be worth to modify callers so as to provide proper source
  9096. location for the unnamed parameters, embedding the parameter's type? */
  9097. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  9098. T, Context.getTrivialTypeSourceInfo(T, Loc),
  9099. SC_None, nullptr);
  9100. Param->setImplicit();
  9101. return Param;
  9102. }
  9103. void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
  9104. ParmVarDecl * const *ParamEnd) {
  9105. // Don't diagnose unused-parameter errors in template instantiations; we
  9106. // will already have done so in the template itself.
  9107. if (!ActiveTemplateInstantiations.empty())
  9108. return;
  9109. for (; Param != ParamEnd; ++Param) {
  9110. if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
  9111. !(*Param)->hasAttr<UnusedAttr>()) {
  9112. Diag((*Param)->getLocation(), diag::warn_unused_parameter)
  9113. << (*Param)->getDeclName();
  9114. }
  9115. }
  9116. }
  9117. void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
  9118. ParmVarDecl * const *ParamEnd,
  9119. QualType ReturnTy,
  9120. NamedDecl *D) {
  9121. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  9122. return;
  9123. // Warn if the return value is pass-by-value and larger than the specified
  9124. // threshold.
  9125. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  9126. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  9127. if (Size > LangOpts.NumLargeByValueCopy)
  9128. Diag(D->getLocation(), diag::warn_return_value_size)
  9129. << D->getDeclName() << Size;
  9130. }
  9131. // Warn if any parameter is pass-by-value and larger than the specified
  9132. // threshold.
  9133. for (; Param != ParamEnd; ++Param) {
  9134. QualType T = (*Param)->getType();
  9135. if (T->isDependentType() || !T.isPODType(Context))
  9136. continue;
  9137. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  9138. if (Size > LangOpts.NumLargeByValueCopy)
  9139. Diag((*Param)->getLocation(), diag::warn_parameter_size)
  9140. << (*Param)->getDeclName() << Size;
  9141. }
  9142. }
  9143. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  9144. SourceLocation NameLoc, IdentifierInfo *Name,
  9145. QualType T, TypeSourceInfo *TSInfo,
  9146. StorageClass SC, hlsl::ParameterModifier ParamMod) { // HLSL Change - add param mod
  9147. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  9148. if (getLangOpts().ObjCAutoRefCount &&
  9149. T.getObjCLifetime() == Qualifiers::OCL_None &&
  9150. T->isObjCLifetimeType()) {
  9151. Qualifiers::ObjCLifetime lifetime;
  9152. // Special cases for arrays:
  9153. // - if it's const, use __unsafe_unretained
  9154. // - otherwise, it's an error
  9155. if (T->isArrayType()) {
  9156. if (!T.isConstQualified()) {
  9157. DelayedDiagnostics.add(
  9158. sema::DelayedDiagnostic::makeForbiddenType(
  9159. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  9160. }
  9161. lifetime = Qualifiers::OCL_ExplicitNone;
  9162. } else {
  9163. lifetime = T->getObjCARCImplicitLifetime();
  9164. }
  9165. T = Context.getLifetimeQualifiedType(T, lifetime);
  9166. }
  9167. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  9168. Context.getAdjustedParameterType(T),
  9169. TSInfo, SC, nullptr, ParamMod);
  9170. // Parameters can not be abstract class types.
  9171. // For record types, this is done by the AbstractClassUsageDiagnoser once
  9172. // the class has been completely parsed.
  9173. if (!CurContext->isRecord() &&
  9174. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  9175. AbstractParamType))
  9176. New->setInvalidDecl();
  9177. // Parameter declarators cannot be interface types. All ObjC objects are
  9178. // passed by reference.
  9179. if (T->isObjCObjectType()) {
  9180. SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
  9181. Diag(NameLoc,
  9182. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  9183. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  9184. T = Context.getObjCObjectPointerType(T);
  9185. New->setType(T);
  9186. }
  9187. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  9188. // duration shall not be qualified by an address-space qualifier."
  9189. // Since all parameters have automatic store duration, they can not have
  9190. // an address space.
  9191. if (T.getAddressSpace() != 0) {
  9192. // OpenCL allows function arguments declared to be an array of a type
  9193. // to be qualified with an address space.
  9194. if (!(getLangOpts().OpenCL && T->isArrayType())) {
  9195. Diag(NameLoc, diag::err_arg_with_address_space);
  9196. New->setInvalidDecl();
  9197. }
  9198. }
  9199. return New;
  9200. }
  9201. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  9202. SourceLocation LocAfterDecls) {
  9203. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  9204. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  9205. // for a K&R function.
  9206. if (!FTI.hasPrototype) {
  9207. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  9208. --i;
  9209. if (FTI.Params[i].Param == nullptr) {
  9210. SmallString<256> Code;
  9211. llvm::raw_svector_ostream(Code)
  9212. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  9213. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  9214. << FTI.Params[i].Ident
  9215. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  9216. // Implicitly declare the argument as type 'int' for lack of a better
  9217. // type.
  9218. AttributeFactory attrs;
  9219. DeclSpec DS(attrs);
  9220. const char* PrevSpec; // unused
  9221. unsigned DiagID; // unused
  9222. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  9223. DiagID, Context.getPrintingPolicy());
  9224. // Use the identifier location for the type source range.
  9225. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  9226. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  9227. Declarator ParamD(DS, Declarator::KNRTypeListContext);
  9228. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  9229. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  9230. }
  9231. }
  9232. }
  9233. }
  9234. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
  9235. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  9236. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  9237. Scope *ParentScope = FnBodyScope->getParent();
  9238. D.setFunctionDefinitionKind(FDK_Definition);
  9239. Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
  9240. return ActOnStartOfFunctionDef(FnBodyScope, DP);
  9241. }
  9242. void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
  9243. Consumer.HandleInlineMethodDefinition(D);
  9244. }
  9245. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  9246. const FunctionDecl*& PossibleZeroParamPrototype) {
  9247. // Don't warn about invalid declarations.
  9248. if (FD->isInvalidDecl())
  9249. return false;
  9250. // Or declarations that aren't global.
  9251. if (!FD->isGlobal())
  9252. return false;
  9253. // Don't warn about C++ member functions.
  9254. if (isa<CXXMethodDecl>(FD))
  9255. return false;
  9256. // Don't warn about 'main'.
  9257. if (FD->isMain())
  9258. return false;
  9259. // Don't warn about inline functions.
  9260. if (FD->isInlined())
  9261. return false;
  9262. // Don't warn about function templates.
  9263. if (FD->getDescribedFunctionTemplate())
  9264. return false;
  9265. // Don't warn about function template specializations.
  9266. if (FD->isFunctionTemplateSpecialization())
  9267. return false;
  9268. // Don't warn for OpenCL kernels.
  9269. if (FD->hasAttr<OpenCLKernelAttr>())
  9270. return false;
  9271. // Don't warn on explicitly deleted functions.
  9272. if (FD->isDeleted())
  9273. return false;
  9274. bool MissingPrototype = true;
  9275. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  9276. Prev; Prev = Prev->getPreviousDecl()) {
  9277. // Ignore any declarations that occur in function or method
  9278. // scope, because they aren't visible from the header.
  9279. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  9280. continue;
  9281. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  9282. if (FD->getNumParams() == 0)
  9283. PossibleZeroParamPrototype = Prev;
  9284. break;
  9285. }
  9286. return MissingPrototype;
  9287. }
  9288. void
  9289. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  9290. const FunctionDecl *EffectiveDefinition) {
  9291. // Don't complain if we're in GNU89 mode and the previous definition
  9292. // was an extern inline function.
  9293. const FunctionDecl *Definition = EffectiveDefinition;
  9294. if (!Definition)
  9295. if (!FD->isDefined(Definition))
  9296. return;
  9297. if (canRedefineFunction(Definition, getLangOpts()))
  9298. return;
  9299. // If we don't have a visible definition of the function, and it's inline or
  9300. // a template, it's OK to form another definition of it.
  9301. //
  9302. // FIXME: Should we skip the body of the function and use the old definition
  9303. // in this case? That may be necessary for functions that return local types
  9304. // through a deduced return type, or instantiate templates with local types.
  9305. if (!hasVisibleDefinition(Definition) &&
  9306. (Definition->getFormalLinkage() == InternalLinkage ||
  9307. Definition->isInlined() ||
  9308. Definition->getDescribedFunctionTemplate() ||
  9309. Definition->getNumTemplateParameterLists()))
  9310. return;
  9311. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  9312. Definition->getStorageClass() == SC_Extern)
  9313. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  9314. << FD->getDeclName() << getLangOpts().CPlusPlus;
  9315. else
  9316. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  9317. Diag(Definition->getLocation(), diag::note_previous_definition);
  9318. FD->setInvalidDecl();
  9319. }
  9320. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  9321. Sema &S) {
  9322. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  9323. LambdaScopeInfo *LSI = S.PushLambdaScope();
  9324. LSI->CallOperator = CallOperator;
  9325. LSI->Lambda = LambdaClass;
  9326. LSI->ReturnType = CallOperator->getReturnType();
  9327. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  9328. if (LCD == LCD_None)
  9329. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  9330. else if (LCD == LCD_ByCopy)
  9331. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  9332. else if (LCD == LCD_ByRef)
  9333. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  9334. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  9335. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  9336. LSI->Mutable = !CallOperator->isConst();
  9337. // Add the captures to the LSI so they can be noted as already
  9338. // captured within tryCaptureVar.
  9339. auto I = LambdaClass->field_begin();
  9340. for (const auto &C : LambdaClass->captures()) {
  9341. if (C.capturesVariable()) {
  9342. VarDecl *VD = C.getCapturedVar();
  9343. if (VD->isInitCapture())
  9344. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  9345. QualType CaptureType = VD->getType();
  9346. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  9347. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  9348. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  9349. /*EllipsisLoc*/C.isPackExpansion()
  9350. ? C.getEllipsisLoc() : SourceLocation(),
  9351. CaptureType, /*Expr*/ nullptr);
  9352. } else if (C.capturesThis()) {
  9353. LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
  9354. S.getCurrentThisType(), /*Expr*/ nullptr);
  9355. } else {
  9356. LSI->addVLATypeCapture(C.getLocation(), I->getType());
  9357. }
  9358. ++I;
  9359. }
  9360. }
  9361. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
  9362. // Clear the last template instantiation error context.
  9363. LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
  9364. if (!D)
  9365. return D;
  9366. FunctionDecl *FD = nullptr;
  9367. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  9368. FD = FunTmpl->getTemplatedDecl();
  9369. else
  9370. FD = cast<FunctionDecl>(D);
  9371. // If we are instantiating a generic lambda call operator, push
  9372. // a LambdaScopeInfo onto the function stack. But use the information
  9373. // that's already been calculated (ActOnLambdaExpr) to prime the current
  9374. // LambdaScopeInfo.
  9375. // When the template operator is being specialized, the LambdaScopeInfo,
  9376. // has to be properly restored so that tryCaptureVariable doesn't try
  9377. // and capture any new variables. In addition when calculating potential
  9378. // captures during transformation of nested lambdas, it is necessary to
  9379. // have the LSI properly restored.
  9380. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  9381. assert(ActiveTemplateInstantiations.size() &&
  9382. "There should be an active template instantiation on the stack "
  9383. "when instantiating a generic lambda!");
  9384. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  9385. }
  9386. else
  9387. // Enter a new function scope
  9388. PushFunctionScope();
  9389. // See if this is a redefinition.
  9390. if (!FD->isLateTemplateParsed())
  9391. CheckForFunctionRedefinition(FD);
  9392. // Builtin functions cannot be defined.
  9393. if (unsigned BuiltinID = FD->getBuiltinID()) {
  9394. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  9395. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  9396. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  9397. FD->setInvalidDecl();
  9398. }
  9399. }
  9400. // The return type of a function definition must be complete
  9401. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  9402. QualType ResultType = FD->getReturnType();
  9403. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  9404. !FD->isInvalidDecl() &&
  9405. RequireCompleteType(FD->getLocation(), ResultType,
  9406. diag::err_func_def_incomplete_result))
  9407. FD->setInvalidDecl();
  9408. if (FnBodyScope)
  9409. PushDeclContext(FnBodyScope, FD);
  9410. // Check the validity of our function parameters
  9411. CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
  9412. /*CheckParameterNames=*/true);
  9413. // Introduce our parameters into the function scope
  9414. for (auto Param : FD->params()) {
  9415. Param->setOwningFunction(FD);
  9416. // If this has an identifier, add it to the scope stack.
  9417. if (Param->getIdentifier() && FnBodyScope) {
  9418. CheckShadow(FnBodyScope, Param);
  9419. PushOnScopeChains(Param, FnBodyScope);
  9420. }
  9421. }
  9422. // If we had any tags defined in the function prototype,
  9423. // introduce them into the function scope.
  9424. if (FnBodyScope) {
  9425. for (ArrayRef<NamedDecl *>::iterator
  9426. I = FD->getDeclsInPrototypeScope().begin(),
  9427. E = FD->getDeclsInPrototypeScope().end();
  9428. I != E; ++I) {
  9429. NamedDecl *D = *I;
  9430. // Some of these decls (like enums) may have been pinned to the
  9431. // translation unit for lack of a real context earlier. If so, remove
  9432. // from the translation unit and reattach to the current context.
  9433. if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
  9434. // Is the decl actually in the context?
  9435. for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
  9436. if (DI == D) {
  9437. Context.getTranslationUnitDecl()->removeDecl(D);
  9438. break;
  9439. }
  9440. }
  9441. // Either way, reassign the lexical decl context to our FunctionDecl.
  9442. D->setLexicalDeclContext(CurContext);
  9443. }
  9444. // If the decl has a non-null name, make accessible in the current scope.
  9445. if (!D->getName().empty())
  9446. PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
  9447. // Similarly, dive into enums and fish their constants out, making them
  9448. // accessible in this scope.
  9449. if (auto *ED = dyn_cast<EnumDecl>(D)) {
  9450. for (auto *EI : ED->enumerators())
  9451. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  9452. }
  9453. }
  9454. }
  9455. // Ensure that the function's exception specification is instantiated.
  9456. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  9457. ResolveExceptionSpec(D->getLocation(), FPT);
  9458. // dllimport cannot be applied to non-inline function definitions.
  9459. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  9460. !FD->isTemplateInstantiation()) {
  9461. assert(!FD->hasAttr<DLLExportAttr>());
  9462. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  9463. FD->setInvalidDecl();
  9464. return D;
  9465. }
  9466. // We want to attach documentation to original Decl (which might be
  9467. // a function template).
  9468. ActOnDocumentableDecl(D);
  9469. if (getCurLexicalContext()->isObjCContainer() &&
  9470. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  9471. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  9472. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  9473. return D;
  9474. }
  9475. /// \brief Given the set of return statements within a function body,
  9476. /// compute the variables that are subject to the named return value
  9477. /// optimization.
  9478. ///
  9479. /// Each of the variables that is subject to the named return value
  9480. /// optimization will be marked as NRVO variables in the AST, and any
  9481. /// return statement that has a marked NRVO variable as its NRVO candidate can
  9482. /// use the named return value optimization.
  9483. ///
  9484. /// This function applies a very simplistic algorithm for NRVO: if every return
  9485. /// statement in the scope of a variable has the same NRVO candidate, that
  9486. /// candidate is an NRVO variable.
  9487. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  9488. ReturnStmt **Returns = Scope->Returns.data();
  9489. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  9490. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  9491. if (!NRVOCandidate->isNRVOVariable())
  9492. Returns[I]->setNRVOCandidate(nullptr);
  9493. }
  9494. }
  9495. }
  9496. bool Sema::canDelayFunctionBody(const Declarator &D) {
  9497. // We can't delay parsing the body of a constexpr function template (yet).
  9498. if (D.getDeclSpec().isConstexprSpecified())
  9499. return false;
  9500. // We can't delay parsing the body of a function template with a deduced
  9501. // return type (yet).
  9502. if (D.getDeclSpec().containsPlaceholderType()) {
  9503. // If the placeholder introduces a non-deduced trailing return type,
  9504. // we can still delay parsing it.
  9505. if (D.getNumTypeObjects()) {
  9506. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  9507. if (Outer.Kind == DeclaratorChunk::Function &&
  9508. Outer.Fun.hasTrailingReturnType()) {
  9509. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  9510. return Ty.isNull() || !Ty->isUndeducedType();
  9511. }
  9512. }
  9513. return false;
  9514. }
  9515. return true;
  9516. }
  9517. bool Sema::canSkipFunctionBody(Decl *D) {
  9518. // We cannot skip the body of a function (or function template) which is
  9519. // constexpr, since we may need to evaluate its body in order to parse the
  9520. // rest of the file.
  9521. // We cannot skip the body of a function with an undeduced return type,
  9522. // because any callers of that function need to know the type.
  9523. if (const FunctionDecl *FD = D->getAsFunction())
  9524. if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
  9525. return false;
  9526. return Consumer.shouldSkipFunctionBody(D);
  9527. }
  9528. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  9529. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
  9530. FD->setHasSkippedBody();
  9531. else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
  9532. MD->setHasSkippedBody();
  9533. return ActOnFinishFunctionBody(Decl, nullptr);
  9534. }
  9535. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  9536. return ActOnFinishFunctionBody(D, BodyArg, false);
  9537. }
  9538. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  9539. bool IsInstantiation) {
  9540. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  9541. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  9542. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  9543. if (FD) {
  9544. FD->setBody(Body);
  9545. if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
  9546. !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
  9547. // If the function has a deduced result type but contains no 'return'
  9548. // statements, the result type as written must be exactly 'auto', and
  9549. // the deduced result type is 'void'.
  9550. if (!FD->getReturnType()->getAs<AutoType>()) {
  9551. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  9552. << FD->getReturnType();
  9553. FD->setInvalidDecl();
  9554. } else {
  9555. // Substitute 'void' for the 'auto' in the type.
  9556. TypeLoc ResultType = getReturnTypeLoc(FD);
  9557. Context.adjustDeducedFunctionResultType(
  9558. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  9559. }
  9560. }
  9561. #if 0 // HLSL Change Start - no lambda support
  9562. else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  9563. auto *LSI = getCurLambda();
  9564. if (LSI->HasImplicitReturnType) {
  9565. deduceClosureReturnType(*LSI);
  9566. // C++11 [expr.prim.lambda]p4:
  9567. // [...] if there are no return statements in the compound-statement
  9568. // [the deduced type is] the type void
  9569. QualType RetType =
  9570. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  9571. // Update the return type to the deduced type.
  9572. const FunctionProtoType *Proto =
  9573. FD->getType()->getAs<FunctionProtoType>();
  9574. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  9575. Proto->getExtProtoInfo()));
  9576. }
  9577. }
  9578. #endif // HLSL Change Start - no lambda support
  9579. // The only way to be included in UndefinedButUsed is if there is an
  9580. // ODR use before the definition. Avoid the expensive map lookup if this
  9581. // is the first declaration.
  9582. if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
  9583. if (!FD->isExternallyVisible())
  9584. UndefinedButUsed.erase(FD);
  9585. else if (FD->isInlined() &&
  9586. !LangOpts.GNUInline &&
  9587. (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
  9588. UndefinedButUsed.erase(FD);
  9589. }
  9590. // If the function implicitly returns zero (like 'main') or is naked,
  9591. // don't complain about missing return statements.
  9592. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  9593. WP.disableCheckFallThrough();
  9594. // MSVC permits the use of pure specifier (=0) on function definition,
  9595. // defined at class scope, warn about this non-standard construct.
  9596. if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
  9597. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  9598. if (!FD->isInvalidDecl()) {
  9599. // Don't diagnose unused parameters of defaulted or deleted functions.
  9600. if (!FD->isDeleted() && !FD->isDefaulted())
  9601. DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
  9602. DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
  9603. FD->getReturnType(), FD);
  9604. // If this is a structor, we need a vtable.
  9605. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  9606. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  9607. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  9608. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  9609. // Try to apply the named return value optimization. We have to check
  9610. // if we can do this here because lambdas keep return statements around
  9611. // to deduce an implicit return type.
  9612. if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
  9613. !FD->isDependentContext())
  9614. computeNRVO(Body, getCurFunction());
  9615. }
  9616. // GNU warning -Wmissing-prototypes:
  9617. // Warn if a global function is defined without a previous
  9618. // prototype declaration. This warning is issued even if the
  9619. // definition itself provides a prototype. The aim is to detect
  9620. // global functions that fail to be declared in header files.
  9621. const FunctionDecl *PossibleZeroParamPrototype = nullptr;
  9622. if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
  9623. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  9624. if (PossibleZeroParamPrototype) {
  9625. // We found a declaration that is not a prototype,
  9626. // but that could be a zero-parameter prototype
  9627. if (TypeSourceInfo *TI =
  9628. PossibleZeroParamPrototype->getTypeSourceInfo()) {
  9629. TypeLoc TL = TI->getTypeLoc();
  9630. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  9631. Diag(PossibleZeroParamPrototype->getLocation(),
  9632. diag::note_declaration_not_a_prototype)
  9633. << PossibleZeroParamPrototype
  9634. << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
  9635. }
  9636. }
  9637. }
  9638. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  9639. const CXXMethodDecl *KeyFunction;
  9640. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  9641. MD->isVirtual() &&
  9642. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  9643. MD == KeyFunction->getCanonicalDecl()) {
  9644. // Update the key-function state if necessary for this ABI.
  9645. if (FD->isInlined() &&
  9646. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  9647. Context.setNonKeyFunction(MD);
  9648. // If the newly-chosen key function is already defined, then we
  9649. // need to mark the vtable as used retroactively.
  9650. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  9651. const FunctionDecl *Definition;
  9652. if (KeyFunction && KeyFunction->isDefined(Definition))
  9653. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  9654. } else {
  9655. // We just defined they key function; mark the vtable as used.
  9656. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  9657. }
  9658. }
  9659. }
  9660. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  9661. "Function parsing confused");
  9662. #if 0 // HLSL Change Starts
  9663. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  9664. assert(MD == getCurMethodDecl() && "Method parsing confused");
  9665. MD->setBody(Body);
  9666. if (!MD->isInvalidDecl()) {
  9667. DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
  9668. DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
  9669. MD->getReturnType(), MD);
  9670. if (Body)
  9671. computeNRVO(Body, getCurFunction());
  9672. }
  9673. if (getCurFunction()->ObjCShouldCallSuper) {
  9674. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
  9675. << MD->getSelector().getAsString();
  9676. getCurFunction()->ObjCShouldCallSuper = false;
  9677. }
  9678. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  9679. const ObjCMethodDecl *InitMethod = nullptr;
  9680. bool isDesignated =
  9681. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  9682. assert(isDesignated && InitMethod);
  9683. (void)isDesignated;
  9684. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  9685. auto IFace = MD->getClassInterface();
  9686. if (!IFace)
  9687. return false;
  9688. auto SuperD = IFace->getSuperClass();
  9689. if (!SuperD)
  9690. return false;
  9691. return SuperD->getIdentifier() ==
  9692. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  9693. };
  9694. // Don't issue this warning for unavailable inits or direct subclasses
  9695. // of NSObject.
  9696. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  9697. Diag(MD->getLocation(),
  9698. diag::warn_objc_designated_init_missing_super_call);
  9699. Diag(InitMethod->getLocation(),
  9700. diag::note_objc_designated_init_marked_here);
  9701. }
  9702. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  9703. }
  9704. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  9705. // Don't issue this warning for unavaialable inits.
  9706. if (!MD->isUnavailable())
  9707. Diag(MD->getLocation(),
  9708. diag::warn_objc_secondary_init_missing_init_call);
  9709. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  9710. }
  9711. #endif // HLSL Change Ends
  9712. } else {
  9713. return nullptr;
  9714. }
  9715. assert(!getCurFunction()->ObjCShouldCallSuper &&
  9716. "This should only be set for ObjC methods, which should have been "
  9717. "handled in the block above.");
  9718. // Verify and clean out per-function state.
  9719. if (Body && (!FD || !FD->isDefaulted())) {
  9720. // C++ constructors that have function-try-blocks can't have return
  9721. // statements in the handlers of that block. (C++ [except.handle]p14)
  9722. // Verify this.
  9723. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  9724. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  9725. // Verify that gotos and switch cases don't jump into scopes illegally.
  9726. if (getCurFunction()->NeedsScopeChecking() &&
  9727. !PP.isCodeCompletionEnabled())
  9728. DiagnoseInvalidJumps(Body);
  9729. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  9730. if (!Destructor->getParent()->isDependentType())
  9731. CheckDestructor(Destructor);
  9732. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  9733. Destructor->getParent());
  9734. }
  9735. // If any errors have occurred, clear out any temporaries that may have
  9736. // been leftover. This ensures that these temporaries won't be picked up for
  9737. // deletion in some later function.
  9738. if (getDiagnostics().hasErrorOccurred() ||
  9739. getDiagnostics().getSuppressAllDiagnostics()) {
  9740. DiscardCleanupsInEvaluationContext();
  9741. }
  9742. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  9743. !isa<FunctionTemplateDecl>(dcl)) {
  9744. // Since the body is valid, issue any analysis-based warnings that are
  9745. // enabled.
  9746. ActivePolicy = &WP;
  9747. }
  9748. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  9749. (!CheckConstexprFunctionDecl(FD) ||
  9750. !CheckConstexprFunctionBody(FD, Body)))
  9751. FD->setInvalidDecl();
  9752. if (FD && FD->hasAttr<NakedAttr>()) {
  9753. for (const Stmt *S : Body->children()) {
  9754. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  9755. Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
  9756. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  9757. FD->setInvalidDecl();
  9758. break;
  9759. }
  9760. }
  9761. }
  9762. assert(ExprCleanupObjects.size() ==
  9763. ExprEvalContexts.back().NumCleanupObjects &&
  9764. "Leftover temporaries in function");
  9765. assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
  9766. assert(MaybeODRUseExprs.empty() &&
  9767. "Leftover expressions for odr-use checking");
  9768. }
  9769. if (!IsInstantiation)
  9770. PopDeclContext();
  9771. PopFunctionScopeInfo(ActivePolicy, dcl);
  9772. // If any errors have occurred, clear out any temporaries that may have
  9773. // been leftover. This ensures that these temporaries won't be picked up for
  9774. // deletion in some later function.
  9775. if (getDiagnostics().hasErrorOccurred()) {
  9776. DiscardCleanupsInEvaluationContext();
  9777. }
  9778. return dcl;
  9779. }
  9780. /// When we finish delayed parsing of an attribute, we must attach it to the
  9781. /// relevant Decl.
  9782. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  9783. ParsedAttributes &Attrs) {
  9784. // Always attach attributes to the underlying decl.
  9785. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  9786. D = TD->getTemplatedDecl();
  9787. ProcessDeclAttributeList(S, D, Attrs.getList());
  9788. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  9789. if (Method->isStatic())
  9790. checkThisInStaticMemberFunctionAttributes(Method);
  9791. }
  9792. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  9793. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  9794. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  9795. IdentifierInfo &II, Scope *S) {
  9796. // Before we produce a declaration for an implicitly defined
  9797. // function, see whether there was a locally-scoped declaration of
  9798. // this name as a function or variable. If so, use that
  9799. // (non-visible) declaration, and complain about it.
  9800. if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
  9801. Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
  9802. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  9803. return ExternCPrev;
  9804. }
  9805. // Extension in C99. Legal in C90, but warn about it.
  9806. unsigned diag_id;
  9807. if (II.getName().startswith("__builtin_"))
  9808. diag_id = diag::warn_builtin_unknown;
  9809. else if (getLangOpts().C99)
  9810. diag_id = diag::ext_implicit_function_decl;
  9811. else
  9812. diag_id = diag::warn_implicit_function_decl;
  9813. Diag(Loc, diag_id) << &II;
  9814. // Because typo correction is expensive, only do it if the implicit
  9815. // function declaration is going to be treated as an error.
  9816. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  9817. TypoCorrection Corrected;
  9818. if (S &&
  9819. (Corrected = CorrectTypo(
  9820. DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
  9821. llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
  9822. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  9823. /*ErrorRecovery*/false);
  9824. }
  9825. // Set a Declarator for the implicit definition: int foo();
  9826. const char *Dummy;
  9827. AttributeFactory attrFactory;
  9828. DeclSpec DS(attrFactory);
  9829. unsigned DiagID;
  9830. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  9831. Context.getPrintingPolicy());
  9832. (void)Error; // Silence warning.
  9833. assert(!Error && "Error setting up implicit decl!");
  9834. SourceLocation NoLoc;
  9835. Declarator D(DS, Declarator::BlockContext);
  9836. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  9837. /*IsAmbiguous=*/false,
  9838. /*LParenLoc=*/NoLoc,
  9839. /*Params=*/nullptr,
  9840. /*NumParams=*/0,
  9841. /*EllipsisLoc=*/NoLoc,
  9842. /*RParenLoc=*/NoLoc,
  9843. /*TypeQuals=*/0,
  9844. /*RefQualifierIsLvalueRef=*/true,
  9845. /*RefQualifierLoc=*/NoLoc,
  9846. /*ConstQualifierLoc=*/NoLoc,
  9847. /*VolatileQualifierLoc=*/NoLoc,
  9848. /*RestrictQualifierLoc=*/NoLoc,
  9849. /*MutableLoc=*/NoLoc,
  9850. EST_None,
  9851. /*ESpecLoc=*/NoLoc,
  9852. /*Exceptions=*/nullptr,
  9853. /*ExceptionRanges=*/nullptr,
  9854. /*NumExceptions=*/0,
  9855. /*NoexceptExpr=*/nullptr,
  9856. /*ExceptionSpecTokens=*/nullptr,
  9857. Loc, Loc, D),
  9858. DS.getAttributes(),
  9859. SourceLocation());
  9860. D.SetIdentifier(&II, Loc);
  9861. // Insert this function into translation-unit scope.
  9862. DeclContext *PrevDC = CurContext;
  9863. CurContext = Context.getTranslationUnitDecl();
  9864. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
  9865. FD->setImplicit();
  9866. CurContext = PrevDC;
  9867. AddKnownFunctionAttributes(FD);
  9868. return FD;
  9869. }
  9870. /// \brief Adds any function attributes that we know a priori based on
  9871. /// the declaration of this function.
  9872. ///
  9873. /// These attributes can apply both to implicitly-declared builtins
  9874. /// (like __builtin___printf_chk) or to library-declared functions
  9875. /// like NSLog or printf.
  9876. ///
  9877. /// We need to check for duplicate attributes both here and where user-written
  9878. /// attributes are applied to declarations.
  9879. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  9880. if (FD->isInvalidDecl())
  9881. return;
  9882. // If this is a built-in function, map its builtin attributes to
  9883. // actual attributes.
  9884. if (unsigned BuiltinID = FD->getBuiltinID()) {
  9885. // Handle printf-formatting attributes.
  9886. unsigned FormatIdx;
  9887. bool HasVAListArg;
  9888. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  9889. if (!FD->hasAttr<FormatAttr>()) {
  9890. const char *fmt = "printf";
  9891. unsigned int NumParams = FD->getNumParams();
  9892. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  9893. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  9894. fmt = "NSString";
  9895. FD->addAttr(FormatAttr::CreateImplicit(Context,
  9896. &Context.Idents.get(fmt),
  9897. FormatIdx+1,
  9898. HasVAListArg ? 0 : FormatIdx+2,
  9899. FD->getLocation()));
  9900. }
  9901. }
  9902. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  9903. HasVAListArg)) {
  9904. if (!FD->hasAttr<FormatAttr>())
  9905. FD->addAttr(FormatAttr::CreateImplicit(Context,
  9906. &Context.Idents.get("scanf"),
  9907. FormatIdx+1,
  9908. HasVAListArg ? 0 : FormatIdx+2,
  9909. FD->getLocation()));
  9910. }
  9911. // Mark const if we don't care about errno and that is the only
  9912. // thing preventing the function from being const. This allows
  9913. // IRgen to use LLVM intrinsics for such functions.
  9914. if (!getLangOpts().MathErrno &&
  9915. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
  9916. if (!FD->hasAttr<ConstAttr>())
  9917. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  9918. }
  9919. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  9920. !FD->hasAttr<ReturnsTwiceAttr>())
  9921. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  9922. FD->getLocation()));
  9923. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  9924. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  9925. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  9926. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  9927. }
  9928. IdentifierInfo *Name = FD->getIdentifier();
  9929. if (!Name)
  9930. return;
  9931. if ((!getLangOpts().CPlusPlus &&
  9932. FD->getDeclContext()->isTranslationUnit()) ||
  9933. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  9934. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  9935. LinkageSpecDecl::lang_c)) {
  9936. // Okay: this could be a libc/libm/Objective-C function we know
  9937. // about.
  9938. } else
  9939. return;
  9940. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  9941. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  9942. // target-specific builtins, perhaps?
  9943. if (!FD->hasAttr<FormatAttr>())
  9944. FD->addAttr(FormatAttr::CreateImplicit(Context,
  9945. &Context.Idents.get("printf"), 2,
  9946. Name->isStr("vasprintf") ? 0 : 3,
  9947. FD->getLocation()));
  9948. }
  9949. if (Name->isStr("__CFStringMakeConstantString")) {
  9950. // We already have a __builtin___CFStringMakeConstantString,
  9951. // but builds that use -fno-constant-cfstrings don't go through that.
  9952. if (!FD->hasAttr<FormatArgAttr>())
  9953. FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
  9954. FD->getLocation()));
  9955. }
  9956. }
  9957. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  9958. TypeSourceInfo *TInfo) {
  9959. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  9960. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  9961. if (!TInfo) {
  9962. assert(D.isInvalidType() && "no declarator info for valid type");
  9963. TInfo = Context.getTrivialTypeSourceInfo(T);
  9964. }
  9965. // Scope manipulation handled by caller.
  9966. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  9967. D.getLocStart(),
  9968. D.getIdentifierLoc(),
  9969. D.getIdentifier(),
  9970. TInfo);
  9971. // Bail out immediately if we have an invalid declaration.
  9972. if (D.isInvalidType()) {
  9973. NewTD->setInvalidDecl();
  9974. return NewTD;
  9975. }
  9976. if (D.getDeclSpec().isModulePrivateSpecified()) {
  9977. if (CurContext->isFunctionOrMethod())
  9978. Diag(NewTD->getLocation(), diag::err_module_private_local)
  9979. << 2 << NewTD->getDeclName()
  9980. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  9981. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  9982. else
  9983. NewTD->setModulePrivate();
  9984. }
  9985. // C++ [dcl.typedef]p8:
  9986. // If the typedef declaration defines an unnamed class (or
  9987. // enum), the first typedef-name declared by the declaration
  9988. // to be that class type (or enum type) is used to denote the
  9989. // class type (or enum type) for linkage purposes only.
  9990. // We need to check whether the type was declared in the declaration.
  9991. switch (D.getDeclSpec().getTypeSpecType()) {
  9992. case TST_enum:
  9993. case TST_struct:
  9994. case TST_interface:
  9995. case TST_union:
  9996. case TST_class: {
  9997. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  9998. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  9999. break;
  10000. }
  10001. default:
  10002. break;
  10003. }
  10004. return NewTD;
  10005. }
  10006. /// \brief Check that this is a valid underlying type for an enum declaration.
  10007. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  10008. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  10009. QualType T = TI->getType();
  10010. if (T->isDependentType())
  10011. return false;
  10012. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  10013. if (BT->isInteger())
  10014. return false;
  10015. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  10016. return true;
  10017. }
  10018. /// Check whether this is a valid redeclaration of a previous enumeration.
  10019. /// \return true if the redeclaration was invalid.
  10020. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  10021. QualType EnumUnderlyingTy,
  10022. const EnumDecl *Prev) {
  10023. bool IsFixed = !EnumUnderlyingTy.isNull();
  10024. if (IsScoped != Prev->isScoped()) {
  10025. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  10026. << Prev->isScoped();
  10027. Diag(Prev->getLocation(), diag::note_previous_declaration);
  10028. return true;
  10029. }
  10030. if (IsFixed && Prev->isFixed()) {
  10031. if (!EnumUnderlyingTy->isDependentType() &&
  10032. !Prev->getIntegerType()->isDependentType() &&
  10033. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  10034. Prev->getIntegerType())) {
  10035. // TODO: Highlight the underlying type of the redeclaration.
  10036. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  10037. << EnumUnderlyingTy << Prev->getIntegerType();
  10038. Diag(Prev->getLocation(), diag::note_previous_declaration)
  10039. << Prev->getIntegerTypeRange();
  10040. return true;
  10041. }
  10042. } else if (IsFixed != Prev->isFixed()) {
  10043. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  10044. << Prev->isFixed();
  10045. Diag(Prev->getLocation(), diag::note_previous_declaration);
  10046. return true;
  10047. }
  10048. return false;
  10049. }
  10050. /// \brief Get diagnostic %select index for tag kind for
  10051. /// redeclaration diagnostic message.
  10052. /// WARNING: Indexes apply to particular diagnostics only!
  10053. ///
  10054. /// \returns diagnostic %select index.
  10055. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  10056. switch (Tag) {
  10057. case TTK_Struct: return 0;
  10058. case TTK_Interface: return 1;
  10059. case TTK_Class: return 2;
  10060. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  10061. }
  10062. }
  10063. /// \brief Determine if tag kind is a class-key compatible with
  10064. /// class for redeclaration (class, struct, or __interface).
  10065. ///
  10066. /// \returns true iff the tag kind is compatible.
  10067. static bool isClassCompatTagKind(TagTypeKind Tag)
  10068. {
  10069. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  10070. }
  10071. /// \brief Determine whether a tag with a given kind is acceptable
  10072. /// as a redeclaration of the given tag declaration.
  10073. ///
  10074. /// \returns true if the new tag kind is acceptable, false otherwise.
  10075. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  10076. TagTypeKind NewTag, bool isDefinition,
  10077. SourceLocation NewTagLoc,
  10078. const IdentifierInfo *Name) {
  10079. // C++ [dcl.type.elab]p3:
  10080. // The class-key or enum keyword present in the
  10081. // elaborated-type-specifier shall agree in kind with the
  10082. // declaration to which the name in the elaborated-type-specifier
  10083. // refers. This rule also applies to the form of
  10084. // elaborated-type-specifier that declares a class-name or
  10085. // friend class since it can be construed as referring to the
  10086. // definition of the class. Thus, in any
  10087. // elaborated-type-specifier, the enum keyword shall be used to
  10088. // refer to an enumeration (7.2), the union class-key shall be
  10089. // used to refer to a union (clause 9), and either the class or
  10090. // struct class-key shall be used to refer to a class (clause 9)
  10091. // declared using the class or struct class-key.
  10092. TagTypeKind OldTag = Previous->getTagKind();
  10093. if (!isDefinition || !isClassCompatTagKind(NewTag))
  10094. if (OldTag == NewTag)
  10095. return true;
  10096. if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
  10097. // Warn about the struct/class tag mismatch.
  10098. bool isTemplate = false;
  10099. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  10100. isTemplate = Record->getDescribedClassTemplate();
  10101. if (!ActiveTemplateInstantiations.empty()) {
  10102. // In a template instantiation, do not offer fix-its for tag mismatches
  10103. // since they usually mess up the template instead of fixing the problem.
  10104. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  10105. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  10106. << getRedeclDiagFromTagKind(OldTag);
  10107. return true;
  10108. }
  10109. if (isDefinition) {
  10110. // On definitions, check previous tags and issue a fix-it for each
  10111. // one that doesn't match the current tag.
  10112. if (Previous->getDefinition()) {
  10113. // Don't suggest fix-its for redefinitions.
  10114. return true;
  10115. }
  10116. bool previousMismatch = false;
  10117. for (auto I : Previous->redecls()) {
  10118. if (I->getTagKind() != NewTag) {
  10119. if (!previousMismatch) {
  10120. previousMismatch = true;
  10121. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  10122. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  10123. << getRedeclDiagFromTagKind(I->getTagKind());
  10124. }
  10125. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  10126. << getRedeclDiagFromTagKind(NewTag)
  10127. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  10128. TypeWithKeyword::getTagTypeKindName(NewTag));
  10129. }
  10130. }
  10131. return true;
  10132. }
  10133. // Check for a previous definition. If current tag and definition
  10134. // are same type, do nothing. If no definition, but disagree with
  10135. // with previous tag type, give a warning, but no fix-it.
  10136. const TagDecl *Redecl = Previous->getDefinition() ?
  10137. Previous->getDefinition() : Previous;
  10138. if (Redecl->getTagKind() == NewTag) {
  10139. return true;
  10140. }
  10141. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  10142. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  10143. << getRedeclDiagFromTagKind(OldTag);
  10144. Diag(Redecl->getLocation(), diag::note_previous_use);
  10145. // If there is a previous definition, suggest a fix-it.
  10146. if (Previous->getDefinition()) {
  10147. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  10148. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  10149. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  10150. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  10151. }
  10152. return true;
  10153. }
  10154. return false;
  10155. }
  10156. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  10157. /// from an outer enclosing namespace or file scope inside a friend declaration.
  10158. /// This should provide the commented out code in the following snippet:
  10159. /// namespace N {
  10160. /// struct X;
  10161. /// namespace M {
  10162. /// struct Y { friend struct /*N::*/ X; };
  10163. /// }
  10164. /// }
  10165. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  10166. SourceLocation NameLoc) {
  10167. // While the decl is in a namespace, do repeated lookup of that name and see
  10168. // if we get the same namespace back. If we do not, continue until
  10169. // translation unit scope, at which point we have a fully qualified NNS.
  10170. SmallVector<IdentifierInfo *, 4> Namespaces;
  10171. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  10172. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  10173. // This tag should be declared in a namespace, which can only be enclosed by
  10174. // other namespaces. Bail if there's an anonymous namespace in the chain.
  10175. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  10176. if (!Namespace || Namespace->isAnonymousNamespace())
  10177. return FixItHint();
  10178. IdentifierInfo *II = Namespace->getIdentifier();
  10179. Namespaces.push_back(II);
  10180. NamedDecl *Lookup = SemaRef.LookupSingleName(
  10181. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  10182. if (Lookup == Namespace)
  10183. break;
  10184. }
  10185. // Once we have all the namespaces, reverse them to go outermost first, and
  10186. // build an NNS.
  10187. SmallString<64> Insertion;
  10188. llvm::raw_svector_ostream OS(Insertion);
  10189. if (DC->isTranslationUnit())
  10190. OS << "::";
  10191. std::reverse(Namespaces.begin(), Namespaces.end());
  10192. for (auto *II : Namespaces)
  10193. OS << II->getName() << "::";
  10194. OS.flush();
  10195. return FixItHint::CreateInsertion(NameLoc, Insertion);
  10196. }
  10197. /// \brief Determine whether a tag originally declared in context \p OldDC can
  10198. /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
  10199. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  10200. /// using-declaration).
  10201. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  10202. DeclContext *NewDC) {
  10203. OldDC = OldDC->getRedeclContext();
  10204. NewDC = NewDC->getRedeclContext();
  10205. if (OldDC->Equals(NewDC))
  10206. return true;
  10207. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  10208. // encloses the other).
  10209. if (S.getLangOpts().MSVCCompat &&
  10210. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  10211. return true;
  10212. return false;
  10213. }
  10214. /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
  10215. /// former case, Name will be non-null. In the later case, Name will be null.
  10216. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  10217. /// reference/declaration/definition of a tag.
  10218. ///
  10219. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  10220. /// trailing-type-specifier) other than one in an alias-declaration.
  10221. ///
  10222. /// \param SkipBody If non-null, will be set to indicate if the caller should
  10223. /// skip the definition of this tag and treat it as if it were a declaration.
  10224. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  10225. SourceLocation KWLoc, CXXScopeSpec &SS,
  10226. IdentifierInfo *Name, SourceLocation NameLoc,
  10227. AttributeList *Attr, AccessSpecifier AS,
  10228. SourceLocation ModulePrivateLoc,
  10229. MultiTemplateParamsArg TemplateParameterLists,
  10230. bool &OwnedDecl, bool &IsDependent,
  10231. SourceLocation ScopedEnumKWLoc,
  10232. bool ScopedEnumUsesClassTag,
  10233. TypeResult UnderlyingType,
  10234. bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
  10235. // If this is not a definition, it must have a name.
  10236. IdentifierInfo *OrigName = Name;
  10237. assert((Name != nullptr || TUK == TUK_Definition) &&
  10238. "Nameless record must be a definition!");
  10239. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  10240. OwnedDecl = false;
  10241. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  10242. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  10243. // FIXME: Check explicit specializations more carefully.
  10244. bool isExplicitSpecialization = false;
  10245. bool Invalid = false;
  10246. // We only need to do this matching if we have template parameters
  10247. // or a scope specifier, which also conveniently avoids this work
  10248. // for non-C++ cases.
  10249. if (TemplateParameterLists.size() > 0 ||
  10250. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  10251. if (TemplateParameterList *TemplateParams =
  10252. MatchTemplateParametersToScopeSpecifier(
  10253. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  10254. TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
  10255. if (Kind == TTK_Enum) {
  10256. Diag(KWLoc, diag::err_enum_template);
  10257. return nullptr;
  10258. }
  10259. if (TemplateParams->size() > 0) {
  10260. // This is a declaration or definition of a class template (which may
  10261. // be a member of another template).
  10262. if (Invalid)
  10263. return nullptr;
  10264. OwnedDecl = false;
  10265. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  10266. SS, Name, NameLoc, Attr,
  10267. TemplateParams, AS,
  10268. ModulePrivateLoc,
  10269. /*FriendLoc*/SourceLocation(),
  10270. TemplateParameterLists.size()-1,
  10271. TemplateParameterLists.data(),
  10272. SkipBody);
  10273. return Result.get();
  10274. } else {
  10275. // The "template<>" header is extraneous.
  10276. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  10277. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  10278. isExplicitSpecialization = true;
  10279. }
  10280. }
  10281. }
  10282. // Figure out the underlying type if this a enum declaration. We need to do
  10283. // this early, because it's needed to detect if this is an incompatible
  10284. // redeclaration.
  10285. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  10286. if (Kind == TTK_Enum) {
  10287. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
  10288. // No underlying type explicitly specified, or we failed to parse the
  10289. // type, default to int.
  10290. EnumUnderlying = Context.IntTy.getTypePtr();
  10291. else if (UnderlyingType.get()) {
  10292. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  10293. // integral type; any cv-qualification is ignored.
  10294. TypeSourceInfo *TI = nullptr;
  10295. GetTypeFromParser(UnderlyingType.get(), &TI);
  10296. EnumUnderlying = TI;
  10297. if (CheckEnumUnderlyingType(TI))
  10298. // Recover by falling back to int.
  10299. EnumUnderlying = Context.IntTy.getTypePtr();
  10300. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  10301. UPPC_FixedUnderlyingType))
  10302. EnumUnderlying = Context.IntTy.getTypePtr();
  10303. } else if (getLangOpts().MSVCCompat)
  10304. // Microsoft enums are always of int type.
  10305. EnumUnderlying = Context.IntTy.getTypePtr();
  10306. }
  10307. // HLSL Change Starts
  10308. if (getLangOpts().HLSLVersion == 2015 && TUK == TUK_Declaration) {
  10309. Diag(NameLoc, diag::err_hlsl_unsupported_construct)
  10310. << "struct declaration without definition";
  10311. }
  10312. // HLSL Change Ends
  10313. DeclContext *SearchDC = CurContext;
  10314. DeclContext *DC = CurContext;
  10315. bool isStdBadAlloc = false;
  10316. RedeclarationKind Redecl = ForRedeclaration;
  10317. if (TUK == TUK_Friend || TUK == TUK_Reference)
  10318. Redecl = NotForRedeclaration;
  10319. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  10320. if (Name && SS.isNotEmpty()) {
  10321. // We have a nested-name tag ('struct foo::bar').
  10322. // Check for invalid 'foo::'.
  10323. if (SS.isInvalid()) {
  10324. Name = nullptr;
  10325. goto CreateNewDecl;
  10326. }
  10327. // If this is a friend or a reference to a class in a dependent
  10328. // context, don't try to make a decl for it.
  10329. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  10330. DC = computeDeclContext(SS, false);
  10331. if (!DC) {
  10332. IsDependent = true;
  10333. return nullptr;
  10334. }
  10335. } else {
  10336. DC = computeDeclContext(SS, true);
  10337. if (!DC) {
  10338. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  10339. << SS.getRange();
  10340. return nullptr;
  10341. }
  10342. }
  10343. if (RequireCompleteDeclContext(SS, DC))
  10344. return nullptr;
  10345. SearchDC = DC;
  10346. // Look-up name inside 'foo::'.
  10347. LookupQualifiedName(Previous, DC);
  10348. if (Previous.isAmbiguous())
  10349. return nullptr;
  10350. if (Previous.empty()) {
  10351. // Name lookup did not find anything. However, if the
  10352. // nested-name-specifier refers to the current instantiation,
  10353. // and that current instantiation has any dependent base
  10354. // classes, we might find something at instantiation time: treat
  10355. // this as a dependent elaborated-type-specifier.
  10356. // But this only makes any sense for reference-like lookups.
  10357. if (Previous.wasNotFoundInCurrentInstantiation() &&
  10358. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  10359. IsDependent = true;
  10360. return nullptr;
  10361. }
  10362. // A tag 'foo::bar' must already exist.
  10363. Diag(NameLoc, diag::err_not_tag_in_scope)
  10364. << Kind << Name << DC << SS.getRange();
  10365. Name = nullptr;
  10366. Invalid = true;
  10367. goto CreateNewDecl;
  10368. }
  10369. } else if (Name) {
  10370. // C++14 [class.mem]p14:
  10371. // If T is the name of a class, then each of the following shall have a
  10372. // name different from T:
  10373. // -- every member of class T that is itself a type
  10374. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  10375. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  10376. return nullptr;
  10377. // If this is a named struct, check to see if there was a previous forward
  10378. // declaration or definition.
  10379. // FIXME: We're looking into outer scopes here, even when we
  10380. // shouldn't be. Doing so can result in ambiguities that we
  10381. // shouldn't be diagnosing.
  10382. LookupName(Previous, S);
  10383. // When declaring or defining a tag, ignore ambiguities introduced
  10384. // by types using'ed into this scope.
  10385. if (Previous.isAmbiguous() &&
  10386. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  10387. LookupResult::Filter F = Previous.makeFilter();
  10388. while (F.hasNext()) {
  10389. NamedDecl *ND = F.next();
  10390. if (ND->getDeclContext()->getRedeclContext() != SearchDC)
  10391. F.erase();
  10392. }
  10393. F.done();
  10394. }
  10395. // C++11 [namespace.memdef]p3:
  10396. // If the name in a friend declaration is neither qualified nor
  10397. // a template-id and the declaration is a function or an
  10398. // elaborated-type-specifier, the lookup to determine whether
  10399. // the entity has been previously declared shall not consider
  10400. // any scopes outside the innermost enclosing namespace.
  10401. //
  10402. // MSVC doesn't implement the above rule for types, so a friend tag
  10403. // declaration may be a redeclaration of a type declared in an enclosing
  10404. // scope. They do implement this rule for friend functions.
  10405. //
  10406. // Does it matter that this should be by scope instead of by
  10407. // semantic context?
  10408. if (!Previous.empty() && TUK == TUK_Friend) {
  10409. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  10410. LookupResult::Filter F = Previous.makeFilter();
  10411. bool FriendSawTagOutsideEnclosingNamespace = false;
  10412. while (F.hasNext()) {
  10413. NamedDecl *ND = F.next();
  10414. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  10415. if (DC->isFileContext() &&
  10416. !EnclosingNS->Encloses(ND->getDeclContext())) {
  10417. if (getLangOpts().MSVCCompat)
  10418. FriendSawTagOutsideEnclosingNamespace = true;
  10419. else
  10420. F.erase();
  10421. }
  10422. }
  10423. F.done();
  10424. // Diagnose this MSVC extension in the easy case where lookup would have
  10425. // unambiguously found something outside the enclosing namespace.
  10426. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  10427. NamedDecl *ND = Previous.getFoundDecl();
  10428. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  10429. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  10430. }
  10431. }
  10432. // Note: there used to be some attempt at recovery here.
  10433. if (Previous.isAmbiguous())
  10434. return nullptr;
  10435. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  10436. // FIXME: This makes sure that we ignore the contexts associated
  10437. // with C structs, unions, and enums when looking for a matching
  10438. // tag declaration or definition. See the similar lookup tweak
  10439. // in Sema::LookupName; is there a better way to deal with this?
  10440. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  10441. SearchDC = SearchDC->getParent();
  10442. }
  10443. }
  10444. if (Previous.isSingleResult() &&
  10445. Previous.getFoundDecl()->isTemplateParameter()) {
  10446. // Maybe we will complain about the shadowed template parameter.
  10447. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  10448. // Just pretend that we didn't see the previous declaration.
  10449. Previous.clear();
  10450. }
  10451. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  10452. DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
  10453. // This is a declaration of or a reference to "std::bad_alloc".
  10454. isStdBadAlloc = true;
  10455. if (Previous.empty() && StdBadAlloc) {
  10456. // std::bad_alloc has been implicitly declared (but made invisible to
  10457. // name lookup). Fill in this implicit declaration as the previous
  10458. // declaration, so that the declarations get chained appropriately.
  10459. Previous.addDecl(getStdBadAlloc());
  10460. }
  10461. }
  10462. // If we didn't find a previous declaration, and this is a reference
  10463. // (or friend reference), move to the correct scope. In C++, we
  10464. // also need to do a redeclaration lookup there, just in case
  10465. // there's a shadow friend decl.
  10466. if (Name && Previous.empty() &&
  10467. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  10468. if (Invalid) goto CreateNewDecl;
  10469. assert(SS.isEmpty());
  10470. if (TUK == TUK_Reference) {
  10471. // C++ [basic.scope.pdecl]p5:
  10472. // -- for an elaborated-type-specifier of the form
  10473. //
  10474. // class-key identifier
  10475. //
  10476. // if the elaborated-type-specifier is used in the
  10477. // decl-specifier-seq or parameter-declaration-clause of a
  10478. // function defined in namespace scope, the identifier is
  10479. // declared as a class-name in the namespace that contains
  10480. // the declaration; otherwise, except as a friend
  10481. // declaration, the identifier is declared in the smallest
  10482. // non-class, non-function-prototype scope that contains the
  10483. // declaration.
  10484. //
  10485. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  10486. // C structs and unions.
  10487. //
  10488. // It is an error in C++ to declare (rather than define) an enum
  10489. // type, including via an elaborated type specifier. We'll
  10490. // diagnose that later; for now, declare the enum in the same
  10491. // scope as we would have picked for any other tag type.
  10492. //
  10493. // GNU C also supports this behavior as part of its incomplete
  10494. // enum types extension, while GNU C++ does not.
  10495. //
  10496. // Find the context where we'll be declaring the tag.
  10497. // FIXME: We would like to maintain the current DeclContext as the
  10498. // lexical context,
  10499. while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
  10500. SearchDC = SearchDC->getParent();
  10501. // Find the scope where we'll be declaring the tag.
  10502. while (S->isClassScope() ||
  10503. (getLangOpts().CPlusPlus &&
  10504. S->isFunctionPrototypeScope()) ||
  10505. ((S->getFlags() & Scope::DeclScope) == 0) ||
  10506. (S->getEntity() && S->getEntity()->isTransparentContext()))
  10507. S = S->getParent();
  10508. } else {
  10509. assert(TUK == TUK_Friend);
  10510. // C++ [namespace.memdef]p3:
  10511. // If a friend declaration in a non-local class first declares a
  10512. // class or function, the friend class or function is a member of
  10513. // the innermost enclosing namespace.
  10514. SearchDC = SearchDC->getEnclosingNamespaceContext();
  10515. }
  10516. // In C++, we need to do a redeclaration lookup to properly
  10517. // diagnose some problems.
  10518. if (getLangOpts().CPlusPlus) {
  10519. Previous.setRedeclarationKind(ForRedeclaration);
  10520. LookupQualifiedName(Previous, SearchDC);
  10521. }
  10522. }
  10523. // If we have a known previous declaration to use, then use it.
  10524. if (Previous.empty() && SkipBody && SkipBody->Previous)
  10525. Previous.addDecl(SkipBody->Previous);
  10526. if (!Previous.empty()) {
  10527. NamedDecl *PrevDecl = Previous.getFoundDecl();
  10528. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  10529. // It's okay to have a tag decl in the same scope as a typedef
  10530. // which hides a tag decl in the same scope. Finding this
  10531. // insanity with a redeclaration lookup can only actually happen
  10532. // in C++.
  10533. //
  10534. // This is also okay for elaborated-type-specifiers, which is
  10535. // technically forbidden by the current standard but which is
  10536. // okay according to the likely resolution of an open issue;
  10537. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  10538. if (getLangOpts().CPlusPlus) {
  10539. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  10540. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  10541. TagDecl *Tag = TT->getDecl();
  10542. if (Tag->getDeclName() == Name &&
  10543. Tag->getDeclContext()->getRedeclContext()
  10544. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  10545. PrevDecl = Tag;
  10546. Previous.clear();
  10547. Previous.addDecl(Tag);
  10548. Previous.resolveKind();
  10549. }
  10550. }
  10551. }
  10552. }
  10553. // If this is a redeclaration of a using shadow declaration, it must
  10554. // declare a tag in the same context. In MSVC mode, we allow a
  10555. // redefinition if either context is within the other.
  10556. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  10557. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  10558. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  10559. isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
  10560. !(OldTag && isAcceptableTagRedeclContext(
  10561. *this, OldTag->getDeclContext(), SearchDC))) {
  10562. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  10563. Diag(Shadow->getTargetDecl()->getLocation(),
  10564. diag::note_using_decl_target);
  10565. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  10566. << 0;
  10567. // Recover by ignoring the old declaration.
  10568. Previous.clear();
  10569. goto CreateNewDecl;
  10570. }
  10571. }
  10572. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  10573. // If this is a use of a previous tag, or if the tag is already declared
  10574. // in the same scope (so that the definition/declaration completes or
  10575. // rementions the tag), reuse the decl.
  10576. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  10577. isDeclInScope(DirectPrevDecl, SearchDC, S,
  10578. SS.isNotEmpty() || isExplicitSpecialization)) {
  10579. // Make sure that this wasn't declared as an enum and now used as a
  10580. // struct or something similar.
  10581. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  10582. TUK == TUK_Definition, KWLoc,
  10583. Name)) {
  10584. bool SafeToContinue
  10585. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  10586. Kind != TTK_Enum);
  10587. if (SafeToContinue)
  10588. Diag(KWLoc, diag::err_use_with_wrong_tag)
  10589. << Name
  10590. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  10591. PrevTagDecl->getKindName());
  10592. else
  10593. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  10594. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  10595. if (SafeToContinue)
  10596. Kind = PrevTagDecl->getTagKind();
  10597. else {
  10598. // Recover by making this an anonymous redefinition.
  10599. Name = nullptr;
  10600. Previous.clear();
  10601. Invalid = true;
  10602. }
  10603. }
  10604. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  10605. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  10606. // If this is an elaborated-type-specifier for a scoped enumeration,
  10607. // the 'class' keyword is not necessary and not permitted.
  10608. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  10609. if (ScopedEnum)
  10610. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  10611. << PrevEnum->isScoped()
  10612. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  10613. return PrevTagDecl;
  10614. }
  10615. QualType EnumUnderlyingTy;
  10616. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  10617. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  10618. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  10619. EnumUnderlyingTy = QualType(T, 0);
  10620. // All conflicts with previous declarations are recovered by
  10621. // returning the previous declaration, unless this is a definition,
  10622. // in which case we want the caller to bail out.
  10623. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  10624. ScopedEnum, EnumUnderlyingTy, PrevEnum))
  10625. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  10626. }
  10627. // C++11 [class.mem]p1:
  10628. // A member shall not be declared twice in the member-specification,
  10629. // except that a nested class or member class template can be declared
  10630. // and then later defined.
  10631. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  10632. S->isDeclScope(PrevDecl)) {
  10633. Diag(NameLoc, diag::ext_member_redeclared);
  10634. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  10635. }
  10636. if (!Invalid) {
  10637. // If this is a use, just return the declaration we found, unless
  10638. // we have attributes.
  10639. // FIXME: In the future, return a variant or some other clue
  10640. // for the consumer of this Decl to know it doesn't own it.
  10641. // For our current ASTs this shouldn't be a problem, but will
  10642. // need to be changed with DeclGroups.
  10643. if (!Attr &&
  10644. ((TUK == TUK_Reference &&
  10645. (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
  10646. || TUK == TUK_Friend))
  10647. return PrevTagDecl;
  10648. // Diagnose attempts to redefine a tag.
  10649. if (TUK == TUK_Definition) {
  10650. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  10651. // If we're defining a specialization and the previous definition
  10652. // is from an implicit instantiation, don't emit an error
  10653. // here; we'll catch this in the general case below.
  10654. bool IsExplicitSpecializationAfterInstantiation = false;
  10655. if (isExplicitSpecialization) {
  10656. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  10657. IsExplicitSpecializationAfterInstantiation =
  10658. RD->getTemplateSpecializationKind() !=
  10659. TSK_ExplicitSpecialization;
  10660. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  10661. IsExplicitSpecializationAfterInstantiation =
  10662. ED->getTemplateSpecializationKind() !=
  10663. TSK_ExplicitSpecialization;
  10664. }
  10665. NamedDecl *Hidden = nullptr;
  10666. if (SkipBody && getLangOpts().CPlusPlus &&
  10667. !hasVisibleDefinition(Def, &Hidden)) {
  10668. // There is a definition of this tag, but it is not visible. We
  10669. // explicitly make use of C++'s one definition rule here, and
  10670. // assume that this definition is identical to the hidden one
  10671. // we already have. Make the existing definition visible and
  10672. // use it in place of this one.
  10673. SkipBody->ShouldSkip = true;
  10674. makeMergedDefinitionVisible(Hidden, KWLoc);
  10675. return Def;
  10676. } else if (!IsExplicitSpecializationAfterInstantiation) {
  10677. // A redeclaration in function prototype scope in C isn't
  10678. // visible elsewhere, so merely issue a warning.
  10679. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  10680. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  10681. else
  10682. Diag(NameLoc, diag::err_redefinition) << Name;
  10683. Diag(Def->getLocation(), diag::note_previous_definition);
  10684. // If this is a redefinition, recover by making this
  10685. // struct be anonymous, which will make any later
  10686. // references get the previous definition.
  10687. Name = nullptr;
  10688. Previous.clear();
  10689. Invalid = true;
  10690. }
  10691. } else {
  10692. // If the type is currently being defined, complain
  10693. // about a nested redefinition.
  10694. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  10695. if (TD->isBeingDefined()) {
  10696. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  10697. Diag(PrevTagDecl->getLocation(),
  10698. diag::note_previous_definition);
  10699. Name = nullptr;
  10700. Previous.clear();
  10701. Invalid = true;
  10702. }
  10703. }
  10704. // Okay, this is definition of a previously declared or referenced
  10705. // tag. We're going to create a new Decl for it.
  10706. }
  10707. // Okay, we're going to make a redeclaration. If this is some kind
  10708. // of reference, make sure we build the redeclaration in the same DC
  10709. // as the original, and ignore the current access specifier.
  10710. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  10711. SearchDC = PrevTagDecl->getDeclContext();
  10712. AS = AS_none;
  10713. }
  10714. }
  10715. // If we get here we have (another) forward declaration or we
  10716. // have a definition. Just create a new decl.
  10717. } else {
  10718. // If we get here, this is a definition of a new tag type in a nested
  10719. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  10720. // new decl/type. We set PrevDecl to NULL so that the entities
  10721. // have distinct types.
  10722. Previous.clear();
  10723. }
  10724. // If we get here, we're going to create a new Decl. If PrevDecl
  10725. // is non-NULL, it's a definition of the tag declared by
  10726. // PrevDecl. If it's NULL, we have a new definition.
  10727. // Otherwise, PrevDecl is not a tag, but was found with tag
  10728. // lookup. This is only actually possible in C++, where a few
  10729. // things like templates still live in the tag namespace.
  10730. } else {
  10731. // Use a better diagnostic if an elaborated-type-specifier
  10732. // found the wrong kind of type on the first
  10733. // (non-redeclaration) lookup.
  10734. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  10735. !Previous.isForRedeclaration()) {
  10736. unsigned Kind = 0;
  10737. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  10738. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  10739. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  10740. Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
  10741. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  10742. Invalid = true;
  10743. // Otherwise, only diagnose if the declaration is in scope.
  10744. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  10745. SS.isNotEmpty() || isExplicitSpecialization)) {
  10746. // do nothing
  10747. // Diagnose implicit declarations introduced by elaborated types.
  10748. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  10749. unsigned Kind = 0;
  10750. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  10751. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  10752. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  10753. Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
  10754. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  10755. Invalid = true;
  10756. // Otherwise it's a declaration. Call out a particularly common
  10757. // case here.
  10758. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  10759. unsigned Kind = 0;
  10760. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  10761. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  10762. << Name << Kind << TND->getUnderlyingType();
  10763. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  10764. Invalid = true;
  10765. // Otherwise, diagnose.
  10766. } else {
  10767. // The tag name clashes with something else in the target scope,
  10768. // issue an error and recover by making this tag be anonymous.
  10769. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  10770. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  10771. Name = nullptr;
  10772. Invalid = true;
  10773. }
  10774. // The existing declaration isn't relevant to us; we're in a
  10775. // new scope, so clear out the previous declaration.
  10776. Previous.clear();
  10777. }
  10778. }
  10779. CreateNewDecl:
  10780. TagDecl *PrevDecl = nullptr;
  10781. if (Previous.isSingleResult())
  10782. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  10783. // If there is an identifier, use the location of the identifier as the
  10784. // location of the decl, otherwise use the location of the struct/union
  10785. // keyword.
  10786. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  10787. // Otherwise, create a new declaration. If there is a previous
  10788. // declaration of the same entity, the two will be linked via
  10789. // PrevDecl.
  10790. TagDecl *New;
  10791. bool IsForwardReference = false;
  10792. if (Kind == TTK_Enum) {
  10793. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  10794. // enum X { A, B, C } D; D should chain to X.
  10795. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  10796. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  10797. ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
  10798. // If this is an undefined enum, warn.
  10799. if (TUK != TUK_Definition && !Invalid) {
  10800. TagDecl *Def;
  10801. if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
  10802. cast<EnumDecl>(New)->isFixed()) {
  10803. // C++0x: 7.2p2: opaque-enum-declaration.
  10804. // Conflicts are diagnosed above. Do nothing.
  10805. }
  10806. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  10807. Diag(Loc, diag::ext_forward_ref_enum_def)
  10808. << New;
  10809. Diag(Def->getLocation(), diag::note_previous_definition);
  10810. } else {
  10811. unsigned DiagID = diag::ext_forward_ref_enum;
  10812. if (getLangOpts().MSVCCompat)
  10813. DiagID = diag::ext_ms_forward_ref_enum;
  10814. else if (getLangOpts().CPlusPlus)
  10815. DiagID = diag::err_forward_ref_enum;
  10816. Diag(Loc, DiagID);
  10817. // If this is a forward-declared reference to an enumeration, make a
  10818. // note of it; we won't actually be introducing the declaration into
  10819. // the declaration context.
  10820. if (TUK == TUK_Reference)
  10821. IsForwardReference = true;
  10822. }
  10823. }
  10824. if (EnumUnderlying) {
  10825. EnumDecl *ED = cast<EnumDecl>(New);
  10826. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  10827. ED->setIntegerTypeSourceInfo(TI);
  10828. else
  10829. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  10830. ED->setPromotionType(ED->getIntegerType());
  10831. }
  10832. } else {
  10833. // struct/union/class
  10834. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  10835. // struct X { int A; } D; D should chain to X.
  10836. if (getLangOpts().CPlusPlus) {
  10837. // FIXME: Look for a way to use RecordDecl for simple structs.
  10838. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  10839. cast_or_null<CXXRecordDecl>(PrevDecl));
  10840. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  10841. StdBadAlloc = cast<CXXRecordDecl>(New);
  10842. } else
  10843. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  10844. cast_or_null<RecordDecl>(PrevDecl));
  10845. }
  10846. // C++11 [dcl.type]p3:
  10847. // A type-specifier-seq shall not define a class or enumeration [...].
  10848. if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
  10849. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  10850. << Context.getTagDeclType(New);
  10851. Invalid = true;
  10852. }
  10853. // Maybe add qualifier info.
  10854. if (SS.isNotEmpty()) {
  10855. if (SS.isSet()) {
  10856. // If this is either a declaration or a definition, check the
  10857. // nested-name-specifier against the current context. We don't do this
  10858. // for explicit specializations, because they have similar checking
  10859. // (with more specific diagnostics) in the call to
  10860. // CheckMemberSpecialization, below.
  10861. if (!isExplicitSpecialization &&
  10862. (TUK == TUK_Definition || TUK == TUK_Declaration) &&
  10863. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
  10864. Invalid = true;
  10865. New->setQualifierInfo(SS.getWithLocInContext(Context));
  10866. if (TemplateParameterLists.size() > 0) {
  10867. New->setTemplateParameterListsInfo(Context,
  10868. TemplateParameterLists.size(),
  10869. TemplateParameterLists.data());
  10870. }
  10871. }
  10872. else
  10873. Invalid = true;
  10874. }
  10875. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  10876. // Add alignment attributes if necessary; these attributes are checked when
  10877. // the ASTContext lays out the structure.
  10878. //
  10879. // It is important for implementing the correct semantics that this
  10880. // happen here (in act on tag decl). The #pragma pack stack is
  10881. // maintained as a result of parser callbacks which can occur at
  10882. // many points during the parsing of a struct declaration (because
  10883. // the #pragma tokens are effectively skipped over during the
  10884. // parsing of the struct).
  10885. if (TUK == TUK_Definition) {
  10886. AddAlignmentAttributesForRecord(RD);
  10887. AddMsStructLayoutForRecord(RD);
  10888. }
  10889. }
  10890. if (ModulePrivateLoc.isValid()) {
  10891. if (isExplicitSpecialization)
  10892. Diag(New->getLocation(), diag::err_module_private_specialization)
  10893. << 2
  10894. << FixItHint::CreateRemoval(ModulePrivateLoc);
  10895. // __module_private__ does not apply to local classes. However, we only
  10896. // diagnose this as an error when the declaration specifiers are
  10897. // freestanding. Here, we just ignore the __module_private__.
  10898. else if (!SearchDC->isFunctionOrMethod())
  10899. New->setModulePrivate();
  10900. }
  10901. // If this is a specialization of a member class (of a class template),
  10902. // check the specialization.
  10903. if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
  10904. Invalid = true;
  10905. // If we're declaring or defining a tag in function prototype scope in C,
  10906. // note that this type can only be used within the function and add it to
  10907. // the list of decls to inject into the function definition scope.
  10908. if ((Name || Kind == TTK_Enum) &&
  10909. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  10910. if (getLangOpts().CPlusPlus) {
  10911. // C++ [dcl.fct]p6:
  10912. // Types shall not be defined in return or parameter types.
  10913. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  10914. Diag(Loc, diag::err_type_defined_in_param_type)
  10915. << Name;
  10916. Invalid = true;
  10917. }
  10918. } else {
  10919. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  10920. }
  10921. DeclsInPrototypeScope.push_back(New);
  10922. }
  10923. if (Invalid)
  10924. New->setInvalidDecl();
  10925. if (Attr)
  10926. ProcessDeclAttributeList(S, New, Attr);
  10927. // Set the lexical context. If the tag has a C++ scope specifier, the
  10928. // lexical context will be different from the semantic context.
  10929. New->setLexicalDeclContext(CurContext);
  10930. // Mark this as a friend decl if applicable.
  10931. // In Microsoft mode, a friend declaration also acts as a forward
  10932. // declaration so we always pass true to setObjectOfFriendDecl to make
  10933. // the tag name visible.
  10934. if (TUK == TUK_Friend)
  10935. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  10936. // Set the access specifier.
  10937. if (!Invalid && SearchDC->isRecord())
  10938. SetMemberAccessSpecifier(New, PrevDecl, AS);
  10939. if (TUK == TUK_Definition)
  10940. New->startDefinition();
  10941. // If this has an identifier, add it to the scope stack.
  10942. if (TUK == TUK_Friend) {
  10943. // We might be replacing an existing declaration in the lookup tables;
  10944. // if so, borrow its access specifier.
  10945. if (PrevDecl)
  10946. New->setAccess(PrevDecl->getAccess());
  10947. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  10948. DC->makeDeclVisibleInContext(New);
  10949. if (Name) // can be null along some error paths
  10950. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  10951. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  10952. } else if (Name) {
  10953. S = getNonFieldDeclScope(S);
  10954. PushOnScopeChains(New, S, !IsForwardReference);
  10955. if (IsForwardReference)
  10956. SearchDC->makeDeclVisibleInContext(New);
  10957. } else {
  10958. CurContext->addDecl(New);
  10959. }
  10960. // If this is the C FILE type, notify the AST context.
  10961. if (IdentifierInfo *II = New->getIdentifier())
  10962. if (!New->isInvalidDecl() &&
  10963. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  10964. II->isStr("FILE"))
  10965. Context.setFILEDecl(New);
  10966. if (PrevDecl)
  10967. mergeDeclAttributes(New, PrevDecl);
  10968. // If there's a #pragma GCC visibility in scope, set the visibility of this
  10969. // record.
  10970. AddPushedVisibilityAttribute(New);
  10971. OwnedDecl = true;
  10972. // In C++, don't return an invalid declaration. We can't recover well from
  10973. // the cases where we make the type anonymous.
  10974. return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
  10975. }
  10976. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  10977. AdjustDeclIfTemplate(TagD);
  10978. TagDecl *Tag = cast<TagDecl>(TagD);
  10979. // Enter the tag context.
  10980. PushDeclContext(S, Tag);
  10981. ActOnDocumentableDecl(TagD);
  10982. // If there's a #pragma GCC visibility in scope, set the visibility of this
  10983. // record.
  10984. AddPushedVisibilityAttribute(Tag);
  10985. }
  10986. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  10987. assert(isa<ObjCContainerDecl>(IDecl) &&
  10988. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  10989. DeclContext *OCD = cast<DeclContext>(IDecl);
  10990. assert(getContainingDC(OCD) == CurContext &&
  10991. "The next DeclContext should be lexically contained in the current one.");
  10992. CurContext = OCD;
  10993. return IDecl;
  10994. }
  10995. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  10996. SourceLocation FinalLoc,
  10997. bool IsFinalSpelledSealed,
  10998. SourceLocation LBraceLoc) {
  10999. AdjustDeclIfTemplate(TagD);
  11000. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  11001. FieldCollector->StartClass();
  11002. if (!Record->getIdentifier())
  11003. return;
  11004. if (FinalLoc.isValid())
  11005. Record->addAttr(new (Context)
  11006. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  11007. // C++ [class]p2:
  11008. // [...] The class-name is also inserted into the scope of the
  11009. // class itself; this is known as the injected-class-name. For
  11010. // purposes of access checking, the injected-class-name is treated
  11011. // as if it were a public member name.
  11012. CXXRecordDecl *InjectedClassName
  11013. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  11014. Record->getLocStart(), Record->getLocation(),
  11015. Record->getIdentifier(),
  11016. /*PrevDecl=*/nullptr,
  11017. /*DelayTypeCreation=*/true);
  11018. Context.getTypeDeclType(InjectedClassName, Record);
  11019. InjectedClassName->setImplicit();
  11020. InjectedClassName->setAccess(AS_public);
  11021. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  11022. InjectedClassName->setDescribedClassTemplate(Template);
  11023. PushOnScopeChains(InjectedClassName, S);
  11024. assert(InjectedClassName->isInjectedClassName() &&
  11025. "Broken injected-class-name");
  11026. }
  11027. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  11028. SourceLocation RBraceLoc) {
  11029. AdjustDeclIfTemplate(TagD);
  11030. TagDecl *Tag = cast<TagDecl>(TagD);
  11031. Tag->setRBraceLoc(RBraceLoc);
  11032. // Make sure we "complete" the definition even it is invalid.
  11033. if (Tag->isBeingDefined()) {
  11034. assert(Tag->isInvalidDecl() && "We should already have completed it");
  11035. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  11036. RD->completeDefinition();
  11037. }
  11038. if (isa<CXXRecordDecl>(Tag))
  11039. FieldCollector->FinishClass();
  11040. // Exit this scope of this tag's definition.
  11041. PopDeclContext();
  11042. if (getCurLexicalContext()->isObjCContainer() &&
  11043. Tag->getDeclContext()->isFileContext())
  11044. Tag->setTopLevelDeclInObjCContainer();
  11045. // Notify the consumer that we've defined a tag.
  11046. if (!Tag->isInvalidDecl())
  11047. Consumer.HandleTagDeclDefinition(Tag);
  11048. }
  11049. void Sema::ActOnObjCContainerFinishDefinition() {
  11050. // Exit this scope of this interface definition.
  11051. PopDeclContext();
  11052. }
  11053. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  11054. assert(DC == CurContext && "Mismatch of container contexts");
  11055. OriginalLexicalContext = DC;
  11056. ActOnObjCContainerFinishDefinition();
  11057. }
  11058. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  11059. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  11060. OriginalLexicalContext = nullptr;
  11061. }
  11062. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  11063. AdjustDeclIfTemplate(TagD);
  11064. TagDecl *Tag = cast<TagDecl>(TagD);
  11065. Tag->setInvalidDecl();
  11066. // Make sure we "complete" the definition even it is invalid.
  11067. if (Tag->isBeingDefined()) {
  11068. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  11069. RD->completeDefinition();
  11070. }
  11071. // We're undoing ActOnTagStartDefinition here, not
  11072. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  11073. // the FieldCollector.
  11074. PopDeclContext();
  11075. }
  11076. // Note that FieldName may be null for anonymous bitfields.
  11077. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  11078. IdentifierInfo *FieldName,
  11079. QualType FieldTy, bool IsMsStruct,
  11080. Expr *BitWidth, bool *ZeroWidth) {
  11081. // Default to true; that shouldn't confuse checks for emptiness
  11082. if (ZeroWidth)
  11083. *ZeroWidth = true;
  11084. // C99 6.7.2.1p4 - verify the field type.
  11085. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  11086. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  11087. // Handle incomplete types with specific error.
  11088. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  11089. return ExprError();
  11090. if (FieldName)
  11091. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  11092. << FieldName << FieldTy << BitWidth->getSourceRange();
  11093. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  11094. << FieldTy << BitWidth->getSourceRange();
  11095. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  11096. UPPC_BitFieldWidth))
  11097. return ExprError();
  11098. // If the bit-width is type- or value-dependent, don't try to check
  11099. // it now.
  11100. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  11101. return BitWidth;
  11102. llvm::APSInt Value;
  11103. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  11104. if (ICE.isInvalid())
  11105. return ICE;
  11106. BitWidth = ICE.get();
  11107. if (Value != 0 && ZeroWidth)
  11108. *ZeroWidth = false;
  11109. // Zero-width bitfield is ok for anonymous field.
  11110. if (Value == 0 && FieldName)
  11111. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  11112. if (Value.isSigned() && Value.isNegative()) {
  11113. if (FieldName)
  11114. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  11115. << FieldName << Value.toString(10);
  11116. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  11117. << Value.toString(10);
  11118. }
  11119. if (!FieldTy->isDependentType()) {
  11120. uint64_t TypeSize = Context.getTypeSize(FieldTy);
  11121. if (Value.getZExtValue() > TypeSize) {
  11122. if (!getLangOpts().CPlusPlus || IsMsStruct ||
  11123. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  11124. if (FieldName)
  11125. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
  11126. << FieldName << (unsigned)Value.getZExtValue()
  11127. << (unsigned)TypeSize;
  11128. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
  11129. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  11130. }
  11131. if (FieldName)
  11132. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
  11133. << FieldName << (unsigned)Value.getZExtValue()
  11134. << (unsigned)TypeSize;
  11135. else
  11136. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
  11137. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  11138. }
  11139. }
  11140. return BitWidth;
  11141. }
  11142. /// ActOnField - Each field of a C struct/union is passed into this in order
  11143. /// to create a FieldDecl object for it.
  11144. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  11145. Declarator &D, Expr *BitfieldWidth) {
  11146. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  11147. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  11148. /*InitStyle=*/ICIS_NoInit, AS_public);
  11149. return Res;
  11150. }
  11151. /// HandleField - Analyze a field of a C struct or a C++ data member.
  11152. ///
  11153. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  11154. SourceLocation DeclStart,
  11155. Declarator &D, Expr *BitWidth,
  11156. InClassInitStyle InitStyle,
  11157. AccessSpecifier AS) {
  11158. IdentifierInfo *II = D.getIdentifier();
  11159. SourceLocation Loc = DeclStart;
  11160. if (II) Loc = D.getIdentifierLoc();
  11161. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11162. QualType T = TInfo->getType();
  11163. if (getLangOpts().CPlusPlus) {
  11164. CheckExtraCXXDefaultArguments(D);
  11165. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  11166. UPPC_DataMemberType)) {
  11167. D.setInvalidType();
  11168. T = Context.IntTy;
  11169. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  11170. }
  11171. }
  11172. // HLSL Changes Start
  11173. if (getLangOpts().HLSL) {
  11174. const bool IsParameterFalse = false;
  11175. if (!DiagnoseHLSLDecl(D, CurContext, TInfo, IsParameterFalse)) {
  11176. // Let the diagnostic provide errors, don't actually return nullptr here;
  11177. // compilation will recover, which is helpful because HLSL diagnostics
  11178. // need not interrupt the declaration processing.
  11179. }
  11180. }
  11181. // HLSL Changes End
  11182. // TR 18037 does not allow fields to be declared with address spaces.
  11183. if (T.getQualifiers().hasAddressSpace()) {
  11184. Diag(Loc, diag::err_field_with_address_space);
  11185. D.setInvalidType();
  11186. }
  11187. // OpenCL 1.2 spec, s6.9 r:
  11188. // The event type cannot be used to declare a structure or union field.
  11189. if (LangOpts.OpenCL && T->isEventT()) {
  11190. Diag(Loc, diag::err_event_t_struct_field);
  11191. D.setInvalidType();
  11192. }
  11193. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  11194. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  11195. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  11196. diag::err_invalid_thread)
  11197. << DeclSpec::getSpecifierName(TSCS);
  11198. // Check to see if this name was declared as a member previously
  11199. NamedDecl *PrevDecl = nullptr;
  11200. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  11201. LookupName(Previous, S);
  11202. switch (Previous.getResultKind()) {
  11203. case LookupResult::Found:
  11204. case LookupResult::FoundUnresolvedValue:
  11205. PrevDecl = Previous.getAsSingle<NamedDecl>();
  11206. break;
  11207. case LookupResult::FoundOverloaded:
  11208. PrevDecl = Previous.getRepresentativeDecl();
  11209. break;
  11210. case LookupResult::NotFound:
  11211. case LookupResult::NotFoundInCurrentInstantiation:
  11212. case LookupResult::Ambiguous:
  11213. break;
  11214. }
  11215. Previous.suppressDiagnostics();
  11216. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  11217. // Maybe we will complain about the shadowed template parameter.
  11218. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11219. // Just pretend that we didn't see the previous declaration.
  11220. PrevDecl = nullptr;
  11221. }
  11222. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  11223. PrevDecl = nullptr;
  11224. bool Mutable
  11225. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  11226. SourceLocation TSSL = D.getLocStart();
  11227. FieldDecl *NewFD
  11228. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  11229. TSSL, AS, PrevDecl, &D);
  11230. if (NewFD->isInvalidDecl())
  11231. Record->setInvalidDecl();
  11232. TransferUnusualAttributes(D, NewFD); // HLSL Change
  11233. if (D.getDeclSpec().isModulePrivateSpecified())
  11234. NewFD->setModulePrivate();
  11235. if (NewFD->isInvalidDecl() && PrevDecl) {
  11236. // Don't introduce NewFD into scope; there's already something
  11237. // with the same name in the same scope.
  11238. } else if (II) {
  11239. PushOnScopeChains(NewFD, S);
  11240. } else
  11241. Record->addDecl(NewFD);
  11242. return NewFD;
  11243. }
  11244. /// \brief Build a new FieldDecl and check its well-formedness.
  11245. ///
  11246. /// This routine builds a new FieldDecl given the fields name, type,
  11247. /// record, etc. \p PrevDecl should refer to any previous declaration
  11248. /// with the same name and in the same scope as the field to be
  11249. /// created.
  11250. ///
  11251. /// \returns a new FieldDecl.
  11252. ///
  11253. /// \todo The Declarator argument is a hack. It will be removed once
  11254. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  11255. TypeSourceInfo *TInfo,
  11256. RecordDecl *Record, SourceLocation Loc,
  11257. bool Mutable, Expr *BitWidth,
  11258. InClassInitStyle InitStyle,
  11259. SourceLocation TSSL,
  11260. AccessSpecifier AS, NamedDecl *PrevDecl,
  11261. Declarator *D) {
  11262. IdentifierInfo *II = Name.getAsIdentifierInfo();
  11263. bool InvalidDecl = false;
  11264. if (D) InvalidDecl = D->isInvalidType();
  11265. // If we receive a broken type, recover by assuming 'int' and
  11266. // marking this declaration as invalid.
  11267. if (T.isNull()) {
  11268. InvalidDecl = true;
  11269. T = Context.IntTy;
  11270. }
  11271. QualType EltTy = Context.getBaseElementType(T);
  11272. if (!EltTy->isDependentType()) {
  11273. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  11274. // Fields of incomplete type force their record to be invalid.
  11275. Record->setInvalidDecl();
  11276. InvalidDecl = true;
  11277. } else {
  11278. NamedDecl *Def;
  11279. EltTy->isIncompleteType(&Def);
  11280. if (Def && Def->isInvalidDecl()) {
  11281. Record->setInvalidDecl();
  11282. InvalidDecl = true;
  11283. }
  11284. }
  11285. }
  11286. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  11287. if (BitWidth && getLangOpts().OpenCL) {
  11288. Diag(Loc, diag::err_opencl_bitfields);
  11289. InvalidDecl = true;
  11290. }
  11291. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  11292. // than a variably modified type.
  11293. if (!InvalidDecl && T->isVariablyModifiedType()) {
  11294. bool SizeIsNegative;
  11295. llvm::APSInt Oversized;
  11296. TypeSourceInfo *FixedTInfo =
  11297. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  11298. SizeIsNegative,
  11299. Oversized);
  11300. if (FixedTInfo) {
  11301. Diag(Loc, diag::warn_illegal_constant_array_size);
  11302. TInfo = FixedTInfo;
  11303. T = FixedTInfo->getType();
  11304. } else {
  11305. if (SizeIsNegative)
  11306. Diag(Loc, diag::err_typecheck_negative_array_size);
  11307. else if (Oversized.getBoolValue())
  11308. Diag(Loc, diag::err_array_too_large)
  11309. << Oversized.toString(10);
  11310. else
  11311. Diag(Loc, diag::err_typecheck_field_variable_size);
  11312. InvalidDecl = true;
  11313. }
  11314. }
  11315. // Fields can not have abstract class types
  11316. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  11317. diag::err_abstract_type_in_decl,
  11318. AbstractFieldType))
  11319. InvalidDecl = true;
  11320. bool ZeroWidth = false;
  11321. if (InvalidDecl)
  11322. BitWidth = nullptr;
  11323. // If this is declared as a bit-field, check the bit-field.
  11324. if (BitWidth) {
  11325. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  11326. &ZeroWidth).get();
  11327. if (!BitWidth) {
  11328. InvalidDecl = true;
  11329. BitWidth = nullptr;
  11330. ZeroWidth = false;
  11331. }
  11332. }
  11333. // Check that 'mutable' is consistent with the type of the declaration.
  11334. if (!InvalidDecl && Mutable) {
  11335. unsigned DiagID = 0;
  11336. if (T->isReferenceType())
  11337. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  11338. : diag::err_mutable_reference;
  11339. else if (T.isConstQualified())
  11340. DiagID = diag::err_mutable_const;
  11341. if (DiagID) {
  11342. SourceLocation ErrLoc = Loc;
  11343. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  11344. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  11345. Diag(ErrLoc, DiagID);
  11346. if (DiagID != diag::ext_mutable_reference) {
  11347. Mutable = false;
  11348. InvalidDecl = true;
  11349. }
  11350. }
  11351. }
  11352. // C++11 [class.union]p8 (DR1460):
  11353. // At most one variant member of a union may have a
  11354. // brace-or-equal-initializer.
  11355. if (InitStyle != ICIS_NoInit)
  11356. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  11357. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  11358. BitWidth, Mutable, InitStyle);
  11359. if (InvalidDecl)
  11360. NewFD->setInvalidDecl();
  11361. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  11362. Diag(Loc, diag::err_duplicate_member) << II;
  11363. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  11364. NewFD->setInvalidDecl();
  11365. }
  11366. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  11367. if (Record->isUnion()) {
  11368. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  11369. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  11370. if (RDecl->getDefinition()) {
  11371. // C++ [class.union]p1: An object of a class with a non-trivial
  11372. // constructor, a non-trivial copy constructor, a non-trivial
  11373. // destructor, or a non-trivial copy assignment operator
  11374. // cannot be a member of a union, nor can an array of such
  11375. // objects.
  11376. if (CheckNontrivialField(NewFD))
  11377. NewFD->setInvalidDecl();
  11378. }
  11379. }
  11380. // C++ [class.union]p1: If a union contains a member of reference type,
  11381. // the program is ill-formed, except when compiling with MSVC extensions
  11382. // enabled.
  11383. if (EltTy->isReferenceType()) {
  11384. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  11385. diag::ext_union_member_of_reference_type :
  11386. diag::err_union_member_of_reference_type)
  11387. << NewFD->getDeclName() << EltTy;
  11388. if (!getLangOpts().MicrosoftExt)
  11389. NewFD->setInvalidDecl();
  11390. }
  11391. }
  11392. }
  11393. // FIXME: We need to pass in the attributes given an AST
  11394. // representation, not a parser representation.
  11395. if (D) {
  11396. // FIXME: The current scope is almost... but not entirely... correct here.
  11397. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  11398. if (NewFD->hasAttrs())
  11399. CheckAlignasUnderalignment(NewFD);
  11400. }
  11401. // In auto-retain/release, infer strong retension for fields of
  11402. // retainable type.
  11403. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  11404. NewFD->setInvalidDecl();
  11405. if (T.isObjCGCWeak())
  11406. Diag(Loc, diag::warn_attribute_weak_on_field);
  11407. NewFD->setAccess(AS);
  11408. return NewFD;
  11409. }
  11410. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  11411. assert(FD);
  11412. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  11413. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  11414. return false;
  11415. QualType EltTy = Context.getBaseElementType(FD->getType());
  11416. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  11417. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  11418. if (RDecl->getDefinition()) {
  11419. // We check for copy constructors before constructors
  11420. // because otherwise we'll never get complaints about
  11421. // copy constructors.
  11422. CXXSpecialMember member = CXXInvalid;
  11423. // We're required to check for any non-trivial constructors. Since the
  11424. // implicit default constructor is suppressed if there are any
  11425. // user-declared constructors, we just need to check that there is a
  11426. // trivial default constructor and a trivial copy constructor. (We don't
  11427. // worry about move constructors here, since this is a C++98 check.)
  11428. if (RDecl->hasNonTrivialCopyConstructor())
  11429. member = CXXCopyConstructor;
  11430. else if (!RDecl->hasTrivialDefaultConstructor())
  11431. member = CXXDefaultConstructor;
  11432. else if (RDecl->hasNonTrivialCopyAssignment())
  11433. member = CXXCopyAssignment;
  11434. else if (RDecl->hasNonTrivialDestructor())
  11435. member = CXXDestructor;
  11436. if (member != CXXInvalid) {
  11437. if (!getLangOpts().CPlusPlus11 &&
  11438. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  11439. // Objective-C++ ARC: it is an error to have a non-trivial field of
  11440. // a union. However, system headers in Objective-C programs
  11441. // occasionally have Objective-C lifetime objects within unions,
  11442. // and rather than cause the program to fail, we make those
  11443. // members unavailable.
  11444. SourceLocation Loc = FD->getLocation();
  11445. if (getSourceManager().isInSystemHeader(Loc)) {
  11446. if (!FD->hasAttr<UnavailableAttr>())
  11447. FD->addAttr(UnavailableAttr::CreateImplicit(Context,
  11448. "this system field has retaining ownership",
  11449. Loc));
  11450. return false;
  11451. }
  11452. }
  11453. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  11454. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  11455. diag::err_illegal_union_or_anon_struct_member)
  11456. << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
  11457. DiagnoseNontrivial(RDecl, member);
  11458. return !getLangOpts().CPlusPlus11;
  11459. }
  11460. }
  11461. }
  11462. return false;
  11463. }
  11464. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  11465. /// AST enum value.
  11466. static ObjCIvarDecl::AccessControl
  11467. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  11468. switch (ivarVisibility) {
  11469. default: llvm_unreachable("Unknown visitibility kind");
  11470. case tok::objc_private: return ObjCIvarDecl::Private;
  11471. case tok::objc_public: return ObjCIvarDecl::Public;
  11472. case tok::objc_protected: return ObjCIvarDecl::Protected;
  11473. case tok::objc_package: return ObjCIvarDecl::Package;
  11474. }
  11475. }
  11476. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  11477. /// in order to create an IvarDecl object for it.
  11478. Decl *Sema::ActOnIvar(Scope *S,
  11479. SourceLocation DeclStart,
  11480. Declarator &D, Expr *BitfieldWidth,
  11481. tok::ObjCKeywordKind Visibility) {
  11482. IdentifierInfo *II = D.getIdentifier();
  11483. Expr *BitWidth = (Expr*)BitfieldWidth;
  11484. SourceLocation Loc = DeclStart;
  11485. if (II) Loc = D.getIdentifierLoc();
  11486. // FIXME: Unnamed fields can be handled in various different ways, for
  11487. // example, unnamed unions inject all members into the struct namespace!
  11488. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11489. QualType T = TInfo->getType();
  11490. if (BitWidth) {
  11491. // 6.7.2.1p3, 6.7.2.1p4
  11492. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  11493. if (!BitWidth)
  11494. D.setInvalidType();
  11495. } else {
  11496. // Not a bitfield.
  11497. // validate II.
  11498. }
  11499. if (T->isReferenceType()) {
  11500. Diag(Loc, diag::err_ivar_reference_type);
  11501. D.setInvalidType();
  11502. }
  11503. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  11504. // than a variably modified type.
  11505. else if (T->isVariablyModifiedType()) {
  11506. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  11507. D.setInvalidType();
  11508. }
  11509. // Get the visibility (access control) for this ivar.
  11510. ObjCIvarDecl::AccessControl ac =
  11511. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  11512. : ObjCIvarDecl::None;
  11513. // Must set ivar's DeclContext to its enclosing interface.
  11514. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  11515. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  11516. return nullptr;
  11517. ObjCContainerDecl *EnclosingContext;
  11518. if (ObjCImplementationDecl *IMPDecl =
  11519. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  11520. if (LangOpts.ObjCRuntime.isFragile()) {
  11521. // Case of ivar declared in an implementation. Context is that of its class.
  11522. EnclosingContext = IMPDecl->getClassInterface();
  11523. assert(EnclosingContext && "Implementation has no class interface!");
  11524. }
  11525. else
  11526. EnclosingContext = EnclosingDecl;
  11527. } else {
  11528. if (ObjCCategoryDecl *CDecl =
  11529. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  11530. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  11531. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  11532. return nullptr;
  11533. }
  11534. }
  11535. EnclosingContext = EnclosingDecl;
  11536. }
  11537. // Construct the decl.
  11538. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  11539. DeclStart, Loc, II, T,
  11540. TInfo, ac, (Expr *)BitfieldWidth);
  11541. if (II) {
  11542. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  11543. ForRedeclaration);
  11544. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  11545. && !isa<TagDecl>(PrevDecl)) {
  11546. Diag(Loc, diag::err_duplicate_member) << II;
  11547. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  11548. NewID->setInvalidDecl();
  11549. }
  11550. }
  11551. // Process attributes attached to the ivar.
  11552. ProcessDeclAttributes(S, NewID, D);
  11553. if (D.isInvalidType())
  11554. NewID->setInvalidDecl();
  11555. // In ARC, infer 'retaining' for ivars of retainable type.
  11556. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  11557. NewID->setInvalidDecl();
  11558. if (D.getDeclSpec().isModulePrivateSpecified())
  11559. NewID->setModulePrivate();
  11560. if (II) {
  11561. // FIXME: When interfaces are DeclContexts, we'll need to add
  11562. // these to the interface.
  11563. S->AddDecl(NewID);
  11564. IdResolver.AddDecl(NewID);
  11565. }
  11566. if (LangOpts.ObjCRuntime.isNonFragile() &&
  11567. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  11568. Diag(Loc, diag::warn_ivars_in_interface);
  11569. return NewID;
  11570. }
  11571. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  11572. /// class and class extensions. For every class \@interface and class
  11573. /// extension \@interface, if the last ivar is a bitfield of any type,
  11574. /// then add an implicit `char :0` ivar to the end of that interface.
  11575. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  11576. SmallVectorImpl<Decl *> &AllIvarDecls) {
  11577. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  11578. return;
  11579. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  11580. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  11581. if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
  11582. return;
  11583. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  11584. if (!ID) {
  11585. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  11586. if (!CD->IsClassExtension())
  11587. return;
  11588. }
  11589. // No need to add this to end of @implementation.
  11590. else
  11591. return;
  11592. }
  11593. // All conditions are met. Add a new bitfield to the tail end of ivars.
  11594. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  11595. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  11596. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  11597. DeclLoc, DeclLoc, nullptr,
  11598. Context.CharTy,
  11599. Context.getTrivialTypeSourceInfo(Context.CharTy,
  11600. DeclLoc),
  11601. ObjCIvarDecl::Private, BW,
  11602. true);
  11603. AllIvarDecls.push_back(Ivar);
  11604. }
  11605. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  11606. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  11607. SourceLocation RBrac, AttributeList *Attr) {
  11608. assert(EnclosingDecl && "missing record or interface decl");
  11609. // If this is an Objective-C @implementation or category and we have
  11610. // new fields here we should reset the layout of the interface since
  11611. // it will now change.
  11612. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  11613. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  11614. switch (DC->getKind()) {
  11615. default: break;
  11616. case Decl::ObjCCategory:
  11617. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  11618. break;
  11619. case Decl::ObjCImplementation:
  11620. Context.
  11621. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  11622. break;
  11623. }
  11624. }
  11625. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  11626. // Start counting up the number of named members; make sure to include
  11627. // members of anonymous structs and unions in the total.
  11628. unsigned NumNamedMembers = 0;
  11629. if (Record) {
  11630. for (const auto *I : Record->decls()) {
  11631. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  11632. if (IFD->getDeclName())
  11633. ++NumNamedMembers;
  11634. }
  11635. }
  11636. // Verify that all the fields are okay.
  11637. SmallVector<FieldDecl*, 32> RecFields;
  11638. bool ARCErrReported = false;
  11639. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  11640. i != end; ++i) {
  11641. FieldDecl *FD = cast<FieldDecl>(*i);
  11642. // Get the type for the field.
  11643. const Type *FDTy = FD->getType().getTypePtr();
  11644. if (!FD->isAnonymousStructOrUnion()) {
  11645. // Remember all fields written by the user.
  11646. RecFields.push_back(FD);
  11647. }
  11648. // If the field is already invalid for some reason, don't emit more
  11649. // diagnostics about it.
  11650. if (FD->isInvalidDecl()) {
  11651. EnclosingDecl->setInvalidDecl();
  11652. continue;
  11653. }
  11654. // C99 6.7.2.1p2:
  11655. // A structure or union shall not contain a member with
  11656. // incomplete or function type (hence, a structure shall not
  11657. // contain an instance of itself, but may contain a pointer to
  11658. // an instance of itself), except that the last member of a
  11659. // structure with more than one named member may have incomplete
  11660. // array type; such a structure (and any union containing,
  11661. // possibly recursively, a member that is such a structure)
  11662. // shall not be a member of a structure or an element of an
  11663. // array.
  11664. if (FDTy->isFunctionType()) {
  11665. // Field declared as a function.
  11666. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  11667. << FD->getDeclName();
  11668. FD->setInvalidDecl();
  11669. EnclosingDecl->setInvalidDecl();
  11670. continue;
  11671. } else if (FDTy->isIncompleteArrayType() && Record &&
  11672. ((i + 1 == Fields.end() && !Record->isUnion()) ||
  11673. ((getLangOpts().MicrosoftExt ||
  11674. getLangOpts().CPlusPlus) &&
  11675. (i + 1 == Fields.end() || Record->isUnion())))) {
  11676. // Flexible array member.
  11677. // Microsoft and g++ is more permissive regarding flexible array.
  11678. // It will accept flexible array in union and also
  11679. // as the sole element of a struct/class.
  11680. unsigned DiagID = 0;
  11681. if (Record->isUnion())
  11682. DiagID = getLangOpts().MicrosoftExt
  11683. ? diag::ext_flexible_array_union_ms
  11684. : getLangOpts().CPlusPlus
  11685. ? diag::ext_flexible_array_union_gnu
  11686. : diag::err_flexible_array_union;
  11687. else if (Fields.size() == 1)
  11688. DiagID = getLangOpts().MicrosoftExt
  11689. ? diag::ext_flexible_array_empty_aggregate_ms
  11690. : getLangOpts().CPlusPlus
  11691. ? diag::ext_flexible_array_empty_aggregate_gnu
  11692. : NumNamedMembers < 1
  11693. ? diag::err_flexible_array_empty_aggregate
  11694. : 0;
  11695. if (DiagID)
  11696. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  11697. << Record->getTagKind();
  11698. // While the layout of types that contain virtual bases is not specified
  11699. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  11700. // virtual bases after the derived members. This would make a flexible
  11701. // array member declared at the end of an object not adjacent to the end
  11702. // of the type.
  11703. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
  11704. if (RD->getNumVBases() != 0)
  11705. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  11706. << FD->getDeclName() << Record->getTagKind();
  11707. if (!getLangOpts().C99)
  11708. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  11709. << FD->getDeclName() << Record->getTagKind();
  11710. // If the element type has a non-trivial destructor, we would not
  11711. // implicitly destroy the elements, so disallow it for now.
  11712. //
  11713. // FIXME: GCC allows this. We should probably either implicitly delete
  11714. // the destructor of the containing class, or just allow this.
  11715. QualType BaseElem = Context.getBaseElementType(FD->getType());
  11716. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  11717. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  11718. << FD->getDeclName() << FD->getType();
  11719. FD->setInvalidDecl();
  11720. EnclosingDecl->setInvalidDecl();
  11721. continue;
  11722. }
  11723. // Okay, we have a legal flexible array member at the end of the struct.
  11724. Record->setHasFlexibleArrayMember(true);
  11725. } else if (!FDTy->isDependentType() &&
  11726. RequireCompleteType(FD->getLocation(), FD->getType(),
  11727. diag::err_field_incomplete)) {
  11728. // Incomplete type
  11729. FD->setInvalidDecl();
  11730. EnclosingDecl->setInvalidDecl();
  11731. continue;
  11732. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  11733. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  11734. // A type which contains a flexible array member is considered to be a
  11735. // flexible array member.
  11736. Record->setHasFlexibleArrayMember(true);
  11737. if (!Record->isUnion()) {
  11738. // If this is a struct/class and this is not the last element, reject
  11739. // it. Note that GCC supports variable sized arrays in the middle of
  11740. // structures.
  11741. if (i + 1 != Fields.end())
  11742. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  11743. << FD->getDeclName() << FD->getType();
  11744. else {
  11745. // We support flexible arrays at the end of structs in
  11746. // other structs as an extension.
  11747. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  11748. << FD->getDeclName();
  11749. }
  11750. }
  11751. }
  11752. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  11753. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  11754. diag::err_abstract_type_in_decl,
  11755. AbstractIvarType)) {
  11756. // Ivars can not have abstract class types
  11757. FD->setInvalidDecl();
  11758. }
  11759. if (Record && FDTTy->getDecl()->hasObjectMember())
  11760. Record->setHasObjectMember(true);
  11761. if (Record && FDTTy->getDecl()->hasVolatileMember())
  11762. Record->setHasVolatileMember(true);
  11763. } else if (FDTy->isObjCObjectType()) {
  11764. /// A field cannot be an Objective-c object
  11765. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  11766. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  11767. QualType T = Context.getObjCObjectPointerType(FD->getType());
  11768. FD->setType(T);
  11769. } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
  11770. (!getLangOpts().CPlusPlus || Record->isUnion())) {
  11771. // It's an error in ARC if a field has lifetime.
  11772. // We don't want to report this in a system header, though,
  11773. // so we just make the field unavailable.
  11774. // FIXME: that's really not sufficient; we need to make the type
  11775. // itself invalid to, say, initialize or copy.
  11776. QualType T = FD->getType();
  11777. Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
  11778. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
  11779. SourceLocation loc = FD->getLocation();
  11780. if (getSourceManager().isInSystemHeader(loc)) {
  11781. if (!FD->hasAttr<UnavailableAttr>()) {
  11782. FD->addAttr(UnavailableAttr::CreateImplicit(Context,
  11783. "this system field has retaining ownership",
  11784. loc));
  11785. }
  11786. } else {
  11787. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  11788. << T->isBlockPointerType() << Record->getTagKind();
  11789. }
  11790. ARCErrReported = true;
  11791. }
  11792. } else if (getLangOpts().ObjC1 &&
  11793. getLangOpts().getGC() != LangOptions::NonGC &&
  11794. Record && !Record->hasObjectMember()) {
  11795. if (FD->getType()->isObjCObjectPointerType() ||
  11796. FD->getType().isObjCGCStrong())
  11797. Record->setHasObjectMember(true);
  11798. else if (Context.getAsArrayType(FD->getType())) {
  11799. QualType BaseType = Context.getBaseElementType(FD->getType());
  11800. if (BaseType->isRecordType() &&
  11801. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  11802. Record->setHasObjectMember(true);
  11803. else if (BaseType->isObjCObjectPointerType() ||
  11804. BaseType.isObjCGCStrong())
  11805. Record->setHasObjectMember(true);
  11806. }
  11807. }
  11808. if (Record && FD->getType().isVolatileQualified())
  11809. Record->setHasVolatileMember(true);
  11810. // Keep track of the number of named members.
  11811. if (FD->getIdentifier())
  11812. ++NumNamedMembers;
  11813. }
  11814. // Okay, we successfully defined 'Record'.
  11815. if (Record) {
  11816. bool Completed = false;
  11817. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  11818. if (!CXXRecord->isInvalidDecl()) {
  11819. // Set access bits correctly on the directly-declared conversions.
  11820. for (CXXRecordDecl::conversion_iterator
  11821. I = CXXRecord->conversion_begin(),
  11822. E = CXXRecord->conversion_end(); I != E; ++I)
  11823. I.setAccess((*I)->getAccess());
  11824. if (!CXXRecord->isDependentType()) {
  11825. if (CXXRecord->hasUserDeclaredDestructor()) {
  11826. // Adjust user-defined destructor exception spec.
  11827. if (getLangOpts().CPlusPlus11)
  11828. AdjustDestructorExceptionSpec(CXXRecord,
  11829. CXXRecord->getDestructor());
  11830. }
  11831. // Add any implicitly-declared members to this class.
  11832. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  11833. // If we have virtual base classes, we may end up finding multiple
  11834. // final overriders for a given virtual function. Check for this
  11835. // problem now.
  11836. if (CXXRecord->getNumVBases()) {
  11837. CXXFinalOverriderMap FinalOverriders;
  11838. CXXRecord->getFinalOverriders(FinalOverriders);
  11839. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  11840. MEnd = FinalOverriders.end();
  11841. M != MEnd; ++M) {
  11842. for (OverridingMethods::iterator SO = M->second.begin(),
  11843. SOEnd = M->second.end();
  11844. SO != SOEnd; ++SO) {
  11845. assert(SO->second.size() > 0 &&
  11846. "Virtual function without overridding functions?");
  11847. if (SO->second.size() == 1)
  11848. continue;
  11849. // C++ [class.virtual]p2:
  11850. // In a derived class, if a virtual member function of a base
  11851. // class subobject has more than one final overrider the
  11852. // program is ill-formed.
  11853. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  11854. << (const NamedDecl *)M->first << Record;
  11855. Diag(M->first->getLocation(),
  11856. diag::note_overridden_virtual_function);
  11857. for (OverridingMethods::overriding_iterator
  11858. OM = SO->second.begin(),
  11859. OMEnd = SO->second.end();
  11860. OM != OMEnd; ++OM)
  11861. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  11862. << (const NamedDecl *)M->first << OM->Method->getParent();
  11863. Record->setInvalidDecl();
  11864. }
  11865. }
  11866. CXXRecord->completeDefinition(&FinalOverriders);
  11867. Completed = true;
  11868. }
  11869. }
  11870. }
  11871. }
  11872. if (!Completed)
  11873. Record->completeDefinition();
  11874. if (Record->hasAttrs()) {
  11875. CheckAlignasUnderalignment(Record);
  11876. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  11877. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  11878. IA->getRange(), IA->getBestCase(),
  11879. IA->getSemanticSpelling());
  11880. }
  11881. // Check if the structure/union declaration is a type that can have zero
  11882. // size in C. For C this is a language extension, for C++ it may cause
  11883. // compatibility problems.
  11884. bool CheckForZeroSize;
  11885. if (!getLangOpts().CPlusPlus) {
  11886. CheckForZeroSize = true;
  11887. } else {
  11888. // For C++ filter out types that cannot be referenced in C code.
  11889. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  11890. CheckForZeroSize =
  11891. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  11892. !CXXRecord->isDependentType() &&
  11893. CXXRecord->isCLike();
  11894. }
  11895. if (CheckForZeroSize) {
  11896. bool ZeroSize = true;
  11897. bool IsEmpty = true;
  11898. unsigned NonBitFields = 0;
  11899. for (RecordDecl::field_iterator I = Record->field_begin(),
  11900. E = Record->field_end();
  11901. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  11902. IsEmpty = false;
  11903. if (I->isUnnamedBitfield()) {
  11904. if (I->getBitWidthValue(Context) > 0)
  11905. ZeroSize = false;
  11906. } else {
  11907. ++NonBitFields;
  11908. QualType FieldType = I->getType();
  11909. if (FieldType->isIncompleteType() ||
  11910. !Context.getTypeSizeInChars(FieldType).isZero())
  11911. ZeroSize = false;
  11912. }
  11913. }
  11914. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  11915. // allowed in C++, but warn if its declaration is inside
  11916. // extern "C" block.
  11917. if (ZeroSize) {
  11918. Diag(RecLoc, getLangOpts().CPlusPlus ?
  11919. diag::warn_zero_size_struct_union_in_extern_c :
  11920. diag::warn_zero_size_struct_union_compat)
  11921. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  11922. }
  11923. // Structs without named members are extension in C (C99 6.7.2.1p7),
  11924. // but are accepted by GCC.
  11925. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  11926. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  11927. diag::ext_no_named_members_in_struct_union)
  11928. << Record->isUnion();
  11929. }
  11930. }
  11931. } else {
  11932. ObjCIvarDecl **ClsFields =
  11933. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  11934. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  11935. ID->setEndOfDefinitionLoc(RBrac);
  11936. // Add ivar's to class's DeclContext.
  11937. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  11938. ClsFields[i]->setLexicalDeclContext(ID);
  11939. ID->addDecl(ClsFields[i]);
  11940. }
  11941. // Must enforce the rule that ivars in the base classes may not be
  11942. // duplicates.
  11943. if (ID->getSuperClass())
  11944. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  11945. } else if (ObjCImplementationDecl *IMPDecl =
  11946. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  11947. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  11948. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  11949. // Ivar declared in @implementation never belongs to the implementation.
  11950. // Only it is in implementation's lexical context.
  11951. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  11952. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  11953. IMPDecl->setIvarLBraceLoc(LBrac);
  11954. IMPDecl->setIvarRBraceLoc(RBrac);
  11955. } else if (ObjCCategoryDecl *CDecl =
  11956. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  11957. // case of ivars in class extension; all other cases have been
  11958. // reported as errors elsewhere.
  11959. // FIXME. Class extension does not have a LocEnd field.
  11960. // CDecl->setLocEnd(RBrac);
  11961. // Add ivar's to class extension's DeclContext.
  11962. // Diagnose redeclaration of private ivars.
  11963. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  11964. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  11965. if (IDecl) {
  11966. if (const ObjCIvarDecl *ClsIvar =
  11967. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  11968. Diag(ClsFields[i]->getLocation(),
  11969. diag::err_duplicate_ivar_declaration);
  11970. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  11971. continue;
  11972. }
  11973. for (const auto *Ext : IDecl->known_extensions()) {
  11974. if (const ObjCIvarDecl *ClsExtIvar
  11975. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  11976. Diag(ClsFields[i]->getLocation(),
  11977. diag::err_duplicate_ivar_declaration);
  11978. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  11979. continue;
  11980. }
  11981. }
  11982. }
  11983. ClsFields[i]->setLexicalDeclContext(CDecl);
  11984. CDecl->addDecl(ClsFields[i]);
  11985. }
  11986. CDecl->setIvarLBraceLoc(LBrac);
  11987. CDecl->setIvarRBraceLoc(RBrac);
  11988. }
  11989. }
  11990. if (Attr)
  11991. ProcessDeclAttributeList(S, Record, Attr);
  11992. }
  11993. /// \brief Determine whether the given integral value is representable within
  11994. /// the given type T.
  11995. static bool isRepresentableIntegerValue(ASTContext &Context,
  11996. llvm::APSInt &Value,
  11997. QualType T) {
  11998. assert(T->isIntegralType(Context) && "Integral type required!");
  11999. unsigned BitWidth = Context.getIntWidth(T);
  12000. if (Value.isUnsigned() || Value.isNonNegative()) {
  12001. if (T->isSignedIntegerOrEnumerationType())
  12002. --BitWidth;
  12003. return Value.getActiveBits() <= BitWidth;
  12004. }
  12005. return Value.getMinSignedBits() <= BitWidth;
  12006. }
  12007. // \brief Given an integral type, return the next larger integral type
  12008. // (or a NULL type of no such type exists).
  12009. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  12010. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  12011. // enum checking below.
  12012. assert(T->isIntegralType(Context) && "Integral type required!");
  12013. const unsigned NumTypes = 4;
  12014. QualType SignedIntegralTypes[NumTypes] = {
  12015. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  12016. };
  12017. QualType UnsignedIntegralTypes[NumTypes] = {
  12018. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  12019. Context.UnsignedLongLongTy
  12020. };
  12021. unsigned BitWidth = Context.getTypeSize(T);
  12022. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  12023. : UnsignedIntegralTypes;
  12024. for (unsigned I = 0; I != NumTypes; ++I)
  12025. if (Context.getTypeSize(Types[I]) > BitWidth)
  12026. return Types[I];
  12027. return QualType();
  12028. }
  12029. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  12030. EnumConstantDecl *LastEnumConst,
  12031. SourceLocation IdLoc,
  12032. IdentifierInfo *Id,
  12033. Expr *Val) {
  12034. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  12035. llvm::APSInt EnumVal(IntWidth);
  12036. QualType EltTy;
  12037. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  12038. Val = nullptr;
  12039. if (Val)
  12040. Val = DefaultLvalueConversion(Val).get();
  12041. if (Val) {
  12042. if (Enum->isDependentType() || Val->isTypeDependent())
  12043. EltTy = Context.DependentTy;
  12044. else {
  12045. SourceLocation ExpLoc;
  12046. // HLSL Change - check constant expression for enum
  12047. if ((getLangOpts().HLSLVersion >= 2017 || getLangOpts().CPlusPlus11) &&
  12048. Enum->isFixed() && !getLangOpts().MSVCCompat) {
  12049. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  12050. // constant-expression in the enumerator-definition shall be a converted
  12051. // constant expression of the underlying type.
  12052. EltTy = Enum->getIntegerType();
  12053. ExprResult Converted =
  12054. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  12055. CCEK_Enumerator);
  12056. if (Converted.isInvalid())
  12057. Val = nullptr;
  12058. else
  12059. Val = Converted.get();
  12060. } else if (!Val->isValueDependent() &&
  12061. !(Val = VerifyIntegerConstantExpression(Val,
  12062. &EnumVal).get())) {
  12063. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  12064. } else {
  12065. if (Enum->isFixed()) {
  12066. EltTy = Enum->getIntegerType();
  12067. // In Obj-C and Microsoft mode, require the enumeration value to be
  12068. // representable in the underlying type of the enumeration. In C++11,
  12069. // we perform a non-narrowing conversion as part of converted constant
  12070. // expression checking.
  12071. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  12072. if (getLangOpts().MSVCCompat) {
  12073. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  12074. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  12075. } else
  12076. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  12077. } else
  12078. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  12079. } else if (getLangOpts().CPlusPlus) {
  12080. // C++11 [dcl.enum]p5:
  12081. // If the underlying type is not fixed, the type of each enumerator
  12082. // is the type of its initializing value:
  12083. // - If an initializer is specified for an enumerator, the
  12084. // initializing value has the same type as the expression.
  12085. EltTy = Val->getType();
  12086. } else {
  12087. // C99 6.7.2.2p2:
  12088. // The expression that defines the value of an enumeration constant
  12089. // shall be an integer constant expression that has a value
  12090. // representable as an int.
  12091. // Complain if the value is not representable in an int.
  12092. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  12093. Diag(IdLoc, diag::ext_enum_value_not_int)
  12094. << EnumVal.toString(10) << Val->getSourceRange()
  12095. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  12096. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  12097. // Force the type of the expression to 'int'.
  12098. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  12099. }
  12100. EltTy = Val->getType();
  12101. }
  12102. }
  12103. }
  12104. }
  12105. if (!Val) {
  12106. if (Enum->isDependentType())
  12107. EltTy = Context.DependentTy;
  12108. else if (!LastEnumConst) {
  12109. // C++0x [dcl.enum]p5:
  12110. // If the underlying type is not fixed, the type of each enumerator
  12111. // is the type of its initializing value:
  12112. // - If no initializer is specified for the first enumerator, the
  12113. // initializing value has an unspecified integral type.
  12114. //
  12115. // GCC uses 'int' for its unspecified integral type, as does
  12116. // C99 6.7.2.2p3.
  12117. if (Enum->isFixed()) {
  12118. EltTy = Enum->getIntegerType();
  12119. }
  12120. else {
  12121. EltTy = Context.IntTy;
  12122. }
  12123. } else {
  12124. // Assign the last value + 1.
  12125. EnumVal = LastEnumConst->getInitVal();
  12126. ++EnumVal;
  12127. EltTy = LastEnumConst->getType();
  12128. // Check for overflow on increment.
  12129. if (EnumVal < LastEnumConst->getInitVal()) {
  12130. // C++0x [dcl.enum]p5:
  12131. // If the underlying type is not fixed, the type of each enumerator
  12132. // is the type of its initializing value:
  12133. //
  12134. // - Otherwise the type of the initializing value is the same as
  12135. // the type of the initializing value of the preceding enumerator
  12136. // unless the incremented value is not representable in that type,
  12137. // in which case the type is an unspecified integral type
  12138. // sufficient to contain the incremented value. If no such type
  12139. // exists, the program is ill-formed.
  12140. QualType T = getNextLargerIntegralType(Context, EltTy);
  12141. if (T.isNull() || Enum->isFixed()) {
  12142. // There is no integral type larger enough to represent this
  12143. // value. Complain, then allow the value to wrap around.
  12144. EnumVal = LastEnumConst->getInitVal();
  12145. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  12146. ++EnumVal;
  12147. if (Enum->isFixed())
  12148. // When the underlying type is fixed, this is ill-formed.
  12149. Diag(IdLoc, diag::err_enumerator_wrapped)
  12150. << EnumVal.toString(10)
  12151. << EltTy;
  12152. else
  12153. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  12154. << EnumVal.toString(10);
  12155. } else {
  12156. EltTy = T;
  12157. }
  12158. // Retrieve the last enumerator's value, extent that type to the
  12159. // type that is supposed to be large enough to represent the incremented
  12160. // value, then increment.
  12161. EnumVal = LastEnumConst->getInitVal();
  12162. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  12163. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  12164. ++EnumVal;
  12165. // If we're not in C++, diagnose the overflow of enumerator values,
  12166. // which in C99 means that the enumerator value is not representable in
  12167. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  12168. // permits enumerator values that are representable in some larger
  12169. // integral type.
  12170. if (!getLangOpts().CPlusPlus && !T.isNull())
  12171. Diag(IdLoc, diag::warn_enum_value_overflow);
  12172. } else if (!getLangOpts().CPlusPlus &&
  12173. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  12174. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  12175. Diag(IdLoc, diag::ext_enum_value_not_int)
  12176. << EnumVal.toString(10) << 1;
  12177. }
  12178. }
  12179. }
  12180. if (!EltTy->isDependentType()) {
  12181. // Make the enumerator value match the signedness and size of the
  12182. // enumerator's type.
  12183. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  12184. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  12185. }
  12186. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  12187. Val, EnumVal);
  12188. }
  12189. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  12190. SourceLocation IILoc) {
  12191. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  12192. !getLangOpts().CPlusPlus)
  12193. return SkipBodyInfo();
  12194. // We have an anonymous enum definition. Look up the first enumerator to
  12195. // determine if we should merge the definition with an existing one and
  12196. // skip the body.
  12197. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  12198. ForRedeclaration);
  12199. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  12200. NamedDecl *Hidden;
  12201. if (PrevECD &&
  12202. !hasVisibleDefinition(cast<NamedDecl>(PrevECD->getDeclContext()),
  12203. &Hidden)) {
  12204. SkipBodyInfo Skip;
  12205. Skip.Previous = Hidden;
  12206. return Skip;
  12207. }
  12208. return SkipBodyInfo();
  12209. }
  12210. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  12211. SourceLocation IdLoc, IdentifierInfo *Id,
  12212. AttributeList *Attr,
  12213. SourceLocation EqualLoc, Expr *Val) {
  12214. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  12215. EnumConstantDecl *LastEnumConst =
  12216. cast_or_null<EnumConstantDecl>(lastEnumConst);
  12217. // The scope passed in may not be a decl scope. Zip up the scope tree until
  12218. // we find one that is.
  12219. S = getNonFieldDeclScope(S);
  12220. // Verify that there isn't already something declared with this name in this
  12221. // scope.
  12222. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  12223. ForRedeclaration);
  12224. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  12225. // Maybe we will complain about the shadowed template parameter.
  12226. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  12227. // Just pretend that we didn't see the previous declaration.
  12228. PrevDecl = nullptr;
  12229. }
  12230. if (PrevDecl) {
  12231. // When in C++, we may get a TagDecl with the same name; in this case the
  12232. // enum constant will 'hide' the tag.
  12233. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  12234. "Received TagDecl when not in C++!");
  12235. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  12236. if (isa<EnumConstantDecl>(PrevDecl))
  12237. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  12238. else
  12239. Diag(IdLoc, diag::err_redefinition) << Id;
  12240. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  12241. return nullptr;
  12242. }
  12243. }
  12244. // C++ [class.mem]p15:
  12245. // If T is the name of a class, then each of the following shall have a name
  12246. // different from T:
  12247. // - every enumerator of every member of class T that is an unscoped
  12248. // enumerated type
  12249. if (!TheEnumDecl->isScoped())
  12250. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  12251. DeclarationNameInfo(Id, IdLoc));
  12252. EnumConstantDecl *New =
  12253. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  12254. if (New) {
  12255. // Process attributes.
  12256. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  12257. // Register this decl in the current scope stack.
  12258. New->setAccess(TheEnumDecl->getAccess());
  12259. PushOnScopeChains(New, S);
  12260. }
  12261. ActOnDocumentableDecl(New);
  12262. return New;
  12263. }
  12264. // Returns true when the enum initial expression does not trigger the
  12265. // duplicate enum warning. A few common cases are exempted as follows:
  12266. // Element2 = Element1
  12267. // Element2 = Element1 + 1
  12268. // Element2 = Element1 - 1
  12269. // Where Element2 and Element1 are from the same enum.
  12270. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  12271. Expr *InitExpr = ECD->getInitExpr();
  12272. if (!InitExpr)
  12273. return true;
  12274. InitExpr = InitExpr->IgnoreImpCasts();
  12275. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  12276. if (!BO->isAdditiveOp())
  12277. return true;
  12278. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  12279. if (!IL)
  12280. return true;
  12281. if (IL->getValue() != 1)
  12282. return true;
  12283. InitExpr = BO->getLHS();
  12284. }
  12285. // This checks if the elements are from the same enum.
  12286. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  12287. if (!DRE)
  12288. return true;
  12289. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  12290. if (!EnumConstant)
  12291. return true;
  12292. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  12293. Enum)
  12294. return true;
  12295. return false;
  12296. }
  12297. struct DupKey {
  12298. int64_t val;
  12299. bool isTombstoneOrEmptyKey;
  12300. DupKey(int64_t val, bool isTombstoneOrEmptyKey)
  12301. : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
  12302. };
  12303. static DupKey GetDupKey(const llvm::APSInt& Val) {
  12304. return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
  12305. false);
  12306. }
  12307. struct DenseMapInfoDupKey {
  12308. static DupKey getEmptyKey() { return DupKey(0, true); }
  12309. static DupKey getTombstoneKey() { return DupKey(1, true); }
  12310. static unsigned getHashValue(const DupKey Key) {
  12311. return (unsigned)(Key.val * 37);
  12312. }
  12313. static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
  12314. return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
  12315. LHS.val == RHS.val;
  12316. }
  12317. };
  12318. // Emits a warning when an element is implicitly set a value that
  12319. // a previous element has already been set to.
  12320. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  12321. EnumDecl *Enum,
  12322. QualType EnumType) {
  12323. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  12324. return;
  12325. // Avoid anonymous enums
  12326. if (!Enum->getIdentifier())
  12327. return;
  12328. // Only check for small enums.
  12329. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  12330. return;
  12331. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  12332. typedef SmallVector<ECDVector *, 3> DuplicatesVector;
  12333. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  12334. typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
  12335. ValueToVectorMap;
  12336. DuplicatesVector DupVector;
  12337. ValueToVectorMap EnumMap;
  12338. // Populate the EnumMap with all values represented by enum constants without
  12339. // an initialier.
  12340. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  12341. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  12342. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  12343. // this constant. Skip this enum since it may be ill-formed.
  12344. if (!ECD) {
  12345. return;
  12346. }
  12347. if (ECD->getInitExpr())
  12348. continue;
  12349. DupKey Key = GetDupKey(ECD->getInitVal());
  12350. DeclOrVector &Entry = EnumMap[Key];
  12351. // First time encountering this value.
  12352. if (Entry.isNull())
  12353. Entry = ECD;
  12354. }
  12355. // Create vectors for any values that has duplicates.
  12356. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  12357. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
  12358. if (!ValidDuplicateEnum(ECD, Enum))
  12359. continue;
  12360. DupKey Key = GetDupKey(ECD->getInitVal());
  12361. DeclOrVector& Entry = EnumMap[Key];
  12362. if (Entry.isNull())
  12363. continue;
  12364. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  12365. // Ensure constants are different.
  12366. if (D == ECD)
  12367. continue;
  12368. // Create new vector and push values onto it.
  12369. ECDVector *Vec = new ECDVector();
  12370. Vec->push_back(D);
  12371. Vec->push_back(ECD);
  12372. // Update entry to point to the duplicates vector.
  12373. Entry = Vec;
  12374. // Store the vector somewhere we can consult later for quick emission of
  12375. // diagnostics.
  12376. DupVector.push_back(Vec);
  12377. continue;
  12378. }
  12379. ECDVector *Vec = Entry.get<ECDVector*>();
  12380. // Make sure constants are not added more than once.
  12381. if (*Vec->begin() == ECD)
  12382. continue;
  12383. Vec->push_back(ECD);
  12384. }
  12385. // Emit diagnostics.
  12386. for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
  12387. DupVectorEnd = DupVector.end();
  12388. DupVectorIter != DupVectorEnd; ++DupVectorIter) {
  12389. ECDVector *Vec = *DupVectorIter;
  12390. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  12391. // Emit warning for one enum constant.
  12392. ECDVector::iterator I = Vec->begin();
  12393. S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
  12394. << (*I)->getName() << (*I)->getInitVal().toString(10)
  12395. << (*I)->getSourceRange();
  12396. ++I;
  12397. // Emit one note for each of the remaining enum constants with
  12398. // the same value.
  12399. for (ECDVector::iterator E = Vec->end(); I != E; ++I)
  12400. S.Diag((*I)->getLocation(), diag::note_duplicate_element)
  12401. << (*I)->getName() << (*I)->getInitVal().toString(10)
  12402. << (*I)->getSourceRange();
  12403. delete Vec;
  12404. }
  12405. }
  12406. bool
  12407. Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  12408. bool AllowMask) const {
  12409. FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>();
  12410. assert(FEAttr && "looking for value in non-flag enum");
  12411. llvm::APInt FlagMask = ~FEAttr->getFlagBits();
  12412. unsigned Width = FlagMask.getBitWidth();
  12413. // We will try a zero-extended value for the regular check first.
  12414. llvm::APInt ExtVal = Val.zextOrSelf(Width);
  12415. // A value is in a flag enum if either its bits are a subset of the enum's
  12416. // flag bits (the first condition) or we are allowing masks and the same is
  12417. // true of its complement (the second condition). When masks are allowed, we
  12418. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  12419. //
  12420. // While it's true that any value could be used as a mask, the assumption is
  12421. // that a mask will have all of the insignificant bits set. Anything else is
  12422. // likely a logic error.
  12423. if (!(FlagMask & ExtVal))
  12424. return true;
  12425. if (AllowMask) {
  12426. // Try a one-extended value instead. This can happen if the enum is wider
  12427. // than the constant used, in C with extensions to allow for wider enums.
  12428. // The mask will still have the correct behaviour, so we give the user the
  12429. // benefit of the doubt.
  12430. //
  12431. // FIXME: This heuristic can cause weird results if the enum was extended
  12432. // to a larger type and is signed, because then bit-masks of smaller types
  12433. // that get extended will fall out of range (e.g. ~0x1u). We currently don't
  12434. // detect that case and will get a false positive for it. In most cases,
  12435. // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may
  12436. // be fine just to accept this as a warning.
  12437. ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth());
  12438. if (!(FlagMask & ~ExtVal))
  12439. return true;
  12440. }
  12441. return false;
  12442. }
  12443. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
  12444. SourceLocation RBraceLoc, Decl *EnumDeclX,
  12445. ArrayRef<Decl *> Elements,
  12446. Scope *S, AttributeList *Attr) {
  12447. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  12448. QualType EnumType = Context.getTypeDeclType(Enum);
  12449. if (Attr)
  12450. ProcessDeclAttributeList(S, Enum, Attr);
  12451. if (Enum->isDependentType()) {
  12452. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  12453. EnumConstantDecl *ECD =
  12454. cast_or_null<EnumConstantDecl>(Elements[i]);
  12455. if (!ECD) continue;
  12456. ECD->setType(EnumType);
  12457. }
  12458. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  12459. return;
  12460. }
  12461. // TODO: If the result value doesn't fit in an int, it must be a long or long
  12462. // long value. ISO C does not support this, but GCC does as an extension,
  12463. // emit a warning.
  12464. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  12465. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  12466. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  12467. // Verify that all the values are okay, compute the size of the values, and
  12468. // reverse the list.
  12469. unsigned NumNegativeBits = 0;
  12470. unsigned NumPositiveBits = 0;
  12471. // Keep track of whether all elements have type int.
  12472. bool AllElementsInt = true;
  12473. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  12474. EnumConstantDecl *ECD =
  12475. cast_or_null<EnumConstantDecl>(Elements[i]);
  12476. if (!ECD) continue; // Already issued a diagnostic.
  12477. const llvm::APSInt &InitVal = ECD->getInitVal();
  12478. // Keep track of the size of positive and negative values.
  12479. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  12480. NumPositiveBits = std::max(NumPositiveBits,
  12481. (unsigned)InitVal.getActiveBits());
  12482. else
  12483. NumNegativeBits = std::max(NumNegativeBits,
  12484. (unsigned)InitVal.getMinSignedBits());
  12485. // Keep track of whether every enum element has type int (very commmon).
  12486. if (AllElementsInt)
  12487. AllElementsInt = ECD->getType() == Context.IntTy;
  12488. }
  12489. // Figure out the type that should be used for this enum.
  12490. QualType BestType;
  12491. unsigned BestWidth;
  12492. // C++0x N3000 [conv.prom]p3:
  12493. // An rvalue of an unscoped enumeration type whose underlying
  12494. // type is not fixed can be converted to an rvalue of the first
  12495. // of the following types that can represent all the values of
  12496. // the enumeration: int, unsigned int, long int, unsigned long
  12497. // int, long long int, or unsigned long long int.
  12498. // C99 6.4.4.3p2:
  12499. // An identifier declared as an enumeration constant has type int.
  12500. // The C99 rule is modified by a gcc extension
  12501. QualType BestPromotionType;
  12502. bool Packed = Enum->hasAttr<PackedAttr>();
  12503. // -fshort-enums is the equivalent to specifying the packed attribute on all
  12504. // enum definitions.
  12505. if (LangOpts.ShortEnums)
  12506. Packed = true;
  12507. if (Enum->isFixed()) {
  12508. BestType = Enum->getIntegerType();
  12509. if (BestType->isPromotableIntegerType())
  12510. BestPromotionType = Context.getPromotedIntegerType(BestType);
  12511. else
  12512. BestPromotionType = BestType;
  12513. BestWidth = Context.getIntWidth(BestType);
  12514. }
  12515. else if (NumNegativeBits) {
  12516. // If there is a negative value, figure out the smallest integer type (of
  12517. // int/long/longlong) that fits.
  12518. // If it's packed, check also if it fits a char or a short.
  12519. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  12520. BestType = Context.SignedCharTy;
  12521. BestWidth = CharWidth;
  12522. } else if (Packed && NumNegativeBits <= ShortWidth &&
  12523. NumPositiveBits < ShortWidth) {
  12524. BestType = Context.ShortTy;
  12525. BestWidth = ShortWidth;
  12526. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  12527. BestType = Context.IntTy;
  12528. BestWidth = IntWidth;
  12529. } else {
  12530. BestWidth = Context.getTargetInfo().getLongWidth();
  12531. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  12532. BestType = Context.LongTy;
  12533. } else {
  12534. BestWidth = Context.getTargetInfo().getLongLongWidth();
  12535. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  12536. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  12537. BestType = Context.LongLongTy;
  12538. }
  12539. }
  12540. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  12541. } else {
  12542. // If there is no negative value, figure out the smallest type that fits
  12543. // all of the enumerator values.
  12544. // If it's packed, check also if it fits a char or a short.
  12545. if (Packed && NumPositiveBits <= CharWidth) {
  12546. BestType = Context.UnsignedCharTy;
  12547. BestPromotionType = Context.IntTy;
  12548. BestWidth = CharWidth;
  12549. } else if (Packed && NumPositiveBits <= ShortWidth) {
  12550. BestType = Context.UnsignedShortTy;
  12551. BestPromotionType = Context.IntTy;
  12552. BestWidth = ShortWidth;
  12553. } else if (NumPositiveBits <= IntWidth) {
  12554. BestType = Context.UnsignedIntTy;
  12555. BestWidth = IntWidth;
  12556. BestPromotionType
  12557. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  12558. ? Context.UnsignedIntTy : Context.IntTy;
  12559. } else if (NumPositiveBits <=
  12560. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  12561. BestType = Context.UnsignedLongTy;
  12562. BestPromotionType
  12563. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  12564. ? Context.UnsignedLongTy : Context.LongTy;
  12565. } else {
  12566. BestWidth = Context.getTargetInfo().getLongLongWidth();
  12567. assert(NumPositiveBits <= BestWidth &&
  12568. "How could an initializer get larger than ULL?");
  12569. BestType = Context.UnsignedLongLongTy;
  12570. BestPromotionType
  12571. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  12572. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  12573. }
  12574. }
  12575. FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>();
  12576. if (FEAttr)
  12577. FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0);
  12578. // Loop over all of the enumerator constants, changing their types to match
  12579. // the type of the enum if needed. If we have a flag type, we also prepare the
  12580. // FlagBits cache.
  12581. for (auto *D : Elements) {
  12582. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  12583. if (!ECD) continue; // Already issued a diagnostic.
  12584. // Standard C says the enumerators have int type, but we allow, as an
  12585. // extension, the enumerators to be larger than int size. If each
  12586. // enumerator value fits in an int, type it as an int, otherwise type it the
  12587. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  12588. // that X has type 'int', not 'unsigned'.
  12589. // Determine whether the value fits into an int.
  12590. llvm::APSInt InitVal = ECD->getInitVal();
  12591. // If it fits into an integer type, force it. Otherwise force it to match
  12592. // the enum decl type.
  12593. QualType NewTy;
  12594. unsigned NewWidth;
  12595. bool NewSign;
  12596. if (!getLangOpts().CPlusPlus &&
  12597. !Enum->isFixed() &&
  12598. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  12599. NewTy = Context.IntTy;
  12600. NewWidth = IntWidth;
  12601. NewSign = true;
  12602. } else if (ECD->getType() == BestType) {
  12603. // Already the right type!
  12604. if (getLangOpts().CPlusPlus)
  12605. // C++ [dcl.enum]p4: Following the closing brace of an
  12606. // enum-specifier, each enumerator has the type of its
  12607. // enumeration.
  12608. ECD->setType(EnumType);
  12609. goto flagbits;
  12610. } else {
  12611. NewTy = BestType;
  12612. NewWidth = BestWidth;
  12613. NewSign = BestType->isSignedIntegerOrEnumerationType();
  12614. }
  12615. // Adjust the APSInt value.
  12616. InitVal = InitVal.extOrTrunc(NewWidth);
  12617. InitVal.setIsSigned(NewSign);
  12618. ECD->setInitVal(InitVal);
  12619. // Adjust the Expr initializer and type.
  12620. if (ECD->getInitExpr() &&
  12621. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  12622. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  12623. CK_IntegralCast,
  12624. ECD->getInitExpr(),
  12625. /*base paths*/ nullptr,
  12626. VK_RValue));
  12627. if (getLangOpts().CPlusPlus)
  12628. // C++ [dcl.enum]p4: Following the closing brace of an
  12629. // enum-specifier, each enumerator has the type of its
  12630. // enumeration.
  12631. ECD->setType(EnumType);
  12632. else
  12633. ECD->setType(NewTy);
  12634. flagbits:
  12635. // Check to see if we have a constant with exactly one bit set. Note that x
  12636. // & (x - 1) will be nonzero if and only if x has more than one bit set.
  12637. if (FEAttr) {
  12638. llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth);
  12639. if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) {
  12640. FEAttr->getFlagBits() |= ExtVal;
  12641. }
  12642. }
  12643. }
  12644. if (FEAttr) {
  12645. for (Decl *D : Elements) {
  12646. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  12647. if (!ECD) continue; // Already issued a diagnostic.
  12648. llvm::APSInt InitVal = ECD->getInitVal();
  12649. if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true))
  12650. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  12651. << ECD << Enum;
  12652. }
  12653. }
  12654. Enum->completeDefinition(BestType, BestPromotionType,
  12655. NumPositiveBits, NumNegativeBits);
  12656. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  12657. // Now that the enum type is defined, ensure it's not been underaligned.
  12658. if (Enum->hasAttrs())
  12659. CheckAlignasUnderalignment(Enum);
  12660. }
  12661. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  12662. SourceLocation StartLoc,
  12663. SourceLocation EndLoc) {
  12664. #if 1 // HLSL Change
  12665. llvm_unreachable("HLSL parser does not produce file scope asm decl");
  12666. #else
  12667. StringLiteral *AsmString = cast<StringLiteral>(expr);
  12668. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  12669. AsmString, StartLoc,
  12670. EndLoc);
  12671. CurContext->addDecl(New);
  12672. return New;
  12673. #endif // HLSL Change
  12674. }
  12675. static void checkModuleImportContext(Sema &S, Module *M,
  12676. SourceLocation ImportLoc,
  12677. DeclContext *DC) {
  12678. if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
  12679. switch (LSD->getLanguage()) {
  12680. case LinkageSpecDecl::lang_c:
  12681. if (!M->IsExternC) {
  12682. S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
  12683. << M->getFullModuleName();
  12684. S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
  12685. return;
  12686. }
  12687. break;
  12688. case LinkageSpecDecl::lang_cxx:
  12689. break;
  12690. }
  12691. DC = LSD->getParent();
  12692. }
  12693. while (isa<LinkageSpecDecl>(DC))
  12694. DC = DC->getParent();
  12695. if (!isa<TranslationUnitDecl>(DC)) {
  12696. S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
  12697. << M->getFullModuleName() << DC;
  12698. S.Diag(cast<Decl>(DC)->getLocStart(),
  12699. diag::note_module_import_not_at_top_level)
  12700. << DC;
  12701. }
  12702. }
  12703. DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
  12704. SourceLocation ImportLoc,
  12705. ModuleIdPath Path) {
  12706. Module *Mod =
  12707. getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
  12708. /*IsIncludeDirective=*/false);
  12709. if (!Mod)
  12710. return true;
  12711. VisibleModules.setVisible(Mod, ImportLoc);
  12712. checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
  12713. // FIXME: we should support importing a submodule within a different submodule
  12714. // of the same top-level module. Until we do, make it an error rather than
  12715. // silently ignoring the import.
  12716. if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
  12717. Diag(ImportLoc, diag::err_module_self_import)
  12718. << Mod->getFullModuleName() << getLangOpts().CurrentModule;
  12719. else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
  12720. Diag(ImportLoc, diag::err_module_import_in_implementation)
  12721. << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
  12722. SmallVector<SourceLocation, 2> IdentifierLocs;
  12723. Module *ModCheck = Mod;
  12724. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  12725. // If we've run out of module parents, just drop the remaining identifiers.
  12726. // We need the length to be consistent.
  12727. if (!ModCheck)
  12728. break;
  12729. ModCheck = ModCheck->Parent;
  12730. IdentifierLocs.push_back(Path[I].second);
  12731. }
  12732. ImportDecl *Import = ImportDecl::Create(Context,
  12733. Context.getTranslationUnitDecl(),
  12734. AtLoc.isValid()? AtLoc : ImportLoc,
  12735. Mod, IdentifierLocs);
  12736. Context.getTranslationUnitDecl()->addDecl(Import);
  12737. return Import;
  12738. }
  12739. void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  12740. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
  12741. // Determine whether we're in the #include buffer for a module. The #includes
  12742. // in that buffer do not qualify as module imports; they're just an
  12743. // implementation detail of us building the module.
  12744. //
  12745. // FIXME: Should we even get ActOnModuleInclude calls for those?
  12746. bool IsInModuleIncludes =
  12747. TUKind == TU_Module &&
  12748. getSourceManager().isWrittenInMainFile(DirectiveLoc);
  12749. // If this module import was due to an inclusion directive, create an
  12750. // implicit import declaration to capture it in the AST.
  12751. if (!IsInModuleIncludes) {
  12752. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  12753. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  12754. DirectiveLoc, Mod,
  12755. DirectiveLoc);
  12756. TU->addDecl(ImportD);
  12757. Consumer.HandleImplicitImportDecl(ImportD);
  12758. }
  12759. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
  12760. VisibleModules.setVisible(Mod, DirectiveLoc);
  12761. }
  12762. void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
  12763. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
  12764. if (getLangOpts().ModulesLocalVisibility)
  12765. VisibleModulesStack.push_back(std::move(VisibleModules));
  12766. VisibleModules.setVisible(Mod, DirectiveLoc);
  12767. }
  12768. void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
  12769. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
  12770. if (getLangOpts().ModulesLocalVisibility) {
  12771. VisibleModules = std::move(VisibleModulesStack.back());
  12772. VisibleModulesStack.pop_back();
  12773. VisibleModules.setVisible(Mod, DirectiveLoc);
  12774. }
  12775. }
  12776. void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
  12777. Module *Mod) {
  12778. // Bail if we're not allowed to implicitly import a module here.
  12779. if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
  12780. return;
  12781. // Create the implicit import declaration.
  12782. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  12783. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  12784. Loc, Mod, Loc);
  12785. TU->addDecl(ImportD);
  12786. Consumer.HandleImplicitImportDecl(ImportD);
  12787. // Make the module visible.
  12788. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
  12789. VisibleModules.setVisible(Mod, Loc);
  12790. }
  12791. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  12792. IdentifierInfo* AliasName,
  12793. SourceLocation PragmaLoc,
  12794. SourceLocation NameLoc,
  12795. SourceLocation AliasNameLoc) {
  12796. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  12797. LookupOrdinaryName);
  12798. AsmLabelAttr *Attr =
  12799. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  12800. // If a declaration that:
  12801. // 1) declares a function or a variable
  12802. // 2) has external linkage
  12803. // already exists, add a label attribute to it.
  12804. if (PrevDecl &&
  12805. (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)) &&
  12806. PrevDecl->hasExternalFormalLinkage())
  12807. PrevDecl->addAttr(Attr);
  12808. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  12809. else
  12810. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  12811. }
  12812. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  12813. SourceLocation PragmaLoc,
  12814. SourceLocation NameLoc) {
  12815. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  12816. if (PrevDecl) {
  12817. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  12818. } else {
  12819. (void)WeakUndeclaredIdentifiers.insert(
  12820. std::pair<IdentifierInfo*,WeakInfo>
  12821. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  12822. }
  12823. }
  12824. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  12825. IdentifierInfo* AliasName,
  12826. SourceLocation PragmaLoc,
  12827. SourceLocation NameLoc,
  12828. SourceLocation AliasNameLoc) {
  12829. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  12830. LookupOrdinaryName);
  12831. WeakInfo W = WeakInfo(Name, NameLoc);
  12832. if (PrevDecl) {
  12833. if (!PrevDecl->hasAttr<AliasAttr>())
  12834. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  12835. DeclApplyPragmaWeak(TUScope, ND, W);
  12836. } else {
  12837. (void)WeakUndeclaredIdentifiers.insert(
  12838. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  12839. }
  12840. }
  12841. Decl *Sema::getObjCDeclContext() const {
  12842. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  12843. }
  12844. AvailabilityResult Sema::getCurContextAvailability() const {
  12845. const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
  12846. if (!D)
  12847. return AR_Available;
  12848. // If we are within an Objective-C method, we should consult
  12849. // both the availability of the method as well as the
  12850. // enclosing class. If the class is (say) deprecated,
  12851. // the entire method is considered deprecated from the
  12852. // purpose of checking if the current context is deprecated.
  12853. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  12854. AvailabilityResult R = MD->getAvailability();
  12855. if (R != AR_Available)
  12856. return R;
  12857. D = MD->getClassInterface();
  12858. }
  12859. // If we are within an Objective-c @implementation, it
  12860. // gets the same availability context as the @interface.
  12861. else if (const ObjCImplementationDecl *ID =
  12862. dyn_cast<ObjCImplementationDecl>(D)) {
  12863. D = ID->getClassInterface();
  12864. }
  12865. // Recover from user error.
  12866. return D ? D->getAvailability() : AR_Available;
  12867. }