SemaDecl.cpp 393 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170
  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 "clang/Sema/Initialization.h"
  15. #include "clang/Sema/Lookup.h"
  16. #include "clang/Sema/CXXFieldCollector.h"
  17. #include "clang/Sema/Scope.h"
  18. #include "clang/Sema/ScopeInfo.h"
  19. #include "TypeLocBuilder.h"
  20. #include "clang/AST/ASTConsumer.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/CXXInheritance.h"
  23. #include "clang/AST/DeclCXX.h"
  24. #include "clang/AST/DeclObjC.h"
  25. #include "clang/AST/DeclTemplate.h"
  26. #include "clang/AST/EvaluatedExprVisitor.h"
  27. #include "clang/AST/ExprCXX.h"
  28. #include "clang/AST/StmtCXX.h"
  29. #include "clang/AST/CharUnits.h"
  30. #include "clang/Sema/DeclSpec.h"
  31. #include "clang/Sema/ParsedTemplate.h"
  32. #include "clang/Parse/ParseDiagnostic.h"
  33. #include "clang/Basic/PartialDiagnostic.h"
  34. #include "clang/Sema/DelayedDiagnostic.h"
  35. #include "clang/Basic/SourceManager.h"
  36. #include "clang/Basic/TargetInfo.h"
  37. // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
  38. #include "clang/Lex/Preprocessor.h"
  39. #include "clang/Lex/HeaderSearch.h"
  40. #include "clang/Lex/ModuleLoader.h"
  41. #include "llvm/ADT/SmallString.h"
  42. #include "llvm/ADT/Triple.h"
  43. #include <algorithm>
  44. #include <cstring>
  45. #include <functional>
  46. using namespace clang;
  47. using namespace sema;
  48. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  49. if (OwnedType) {
  50. Decl *Group[2] = { OwnedType, Ptr };
  51. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  52. }
  53. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  54. }
  55. namespace {
  56. class TypeNameValidatorCCC : public CorrectionCandidateCallback {
  57. public:
  58. TypeNameValidatorCCC(bool AllowInvalid) : AllowInvalidDecl(AllowInvalid) {
  59. WantExpressionKeywords = false;
  60. WantCXXNamedCasts = false;
  61. WantRemainingKeywords = false;
  62. }
  63. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  64. if (NamedDecl *ND = candidate.getCorrectionDecl())
  65. return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
  66. (AllowInvalidDecl || !ND->isInvalidDecl());
  67. else
  68. return candidate.isKeyword();
  69. }
  70. private:
  71. bool AllowInvalidDecl;
  72. };
  73. }
  74. /// \brief If the identifier refers to a type name within this scope,
  75. /// return the declaration of that type.
  76. ///
  77. /// This routine performs ordinary name lookup of the identifier II
  78. /// within the given scope, with optional C++ scope specifier SS, to
  79. /// determine whether the name refers to a type. If so, returns an
  80. /// opaque pointer (actually a QualType) corresponding to that
  81. /// type. Otherwise, returns NULL.
  82. ///
  83. /// If name lookup results in an ambiguity, this routine will complain
  84. /// and then return NULL.
  85. ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
  86. Scope *S, CXXScopeSpec *SS,
  87. bool isClassName, bool HasTrailingDot,
  88. ParsedType ObjectTypePtr,
  89. bool IsCtorOrDtorName,
  90. bool WantNontrivialTypeSourceInfo,
  91. IdentifierInfo **CorrectedII) {
  92. // Determine where we will perform name lookup.
  93. DeclContext *LookupCtx = 0;
  94. if (ObjectTypePtr) {
  95. QualType ObjectType = ObjectTypePtr.get();
  96. if (ObjectType->isRecordType())
  97. LookupCtx = computeDeclContext(ObjectType);
  98. } else if (SS && SS->isNotEmpty()) {
  99. LookupCtx = computeDeclContext(*SS, false);
  100. if (!LookupCtx) {
  101. if (isDependentScopeSpecifier(*SS)) {
  102. // C++ [temp.res]p3:
  103. // A qualified-id that refers to a type and in which the
  104. // nested-name-specifier depends on a template-parameter (14.6.2)
  105. // shall be prefixed by the keyword typename to indicate that the
  106. // qualified-id denotes a type, forming an
  107. // elaborated-type-specifier (7.1.5.3).
  108. //
  109. // We therefore do not perform any name lookup if the result would
  110. // refer to a member of an unknown specialization.
  111. if (!isClassName)
  112. return ParsedType();
  113. // We know from the grammar that this name refers to a type,
  114. // so build a dependent node to describe the type.
  115. if (WantNontrivialTypeSourceInfo)
  116. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  117. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  118. QualType T =
  119. CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  120. II, NameLoc);
  121. return ParsedType::make(T);
  122. }
  123. return ParsedType();
  124. }
  125. if (!LookupCtx->isDependentContext() &&
  126. RequireCompleteDeclContext(*SS, LookupCtx))
  127. return ParsedType();
  128. }
  129. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  130. // lookup for class-names.
  131. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  132. LookupOrdinaryName;
  133. LookupResult Result(*this, &II, NameLoc, Kind);
  134. if (LookupCtx) {
  135. // Perform "qualified" name lookup into the declaration context we
  136. // computed, which is either the type of the base of a member access
  137. // expression or the declaration context associated with a prior
  138. // nested-name-specifier.
  139. LookupQualifiedName(Result, LookupCtx);
  140. if (ObjectTypePtr && Result.empty()) {
  141. // C++ [basic.lookup.classref]p3:
  142. // If the unqualified-id is ~type-name, the type-name is looked up
  143. // in the context of the entire postfix-expression. If the type T of
  144. // the object expression is of a class type C, the type-name is also
  145. // looked up in the scope of class C. At least one of the lookups shall
  146. // find a name that refers to (possibly cv-qualified) T.
  147. LookupName(Result, S);
  148. }
  149. } else {
  150. // Perform unqualified name lookup.
  151. LookupName(Result, S);
  152. }
  153. NamedDecl *IIDecl = 0;
  154. switch (Result.getResultKind()) {
  155. case LookupResult::NotFound:
  156. case LookupResult::NotFoundInCurrentInstantiation:
  157. if (CorrectedII) {
  158. TypeNameValidatorCCC Validator(true);
  159. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
  160. Kind, S, SS, Validator);
  161. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  162. TemplateTy Template;
  163. bool MemberOfUnknownSpecialization;
  164. UnqualifiedId TemplateName;
  165. TemplateName.setIdentifier(NewII, NameLoc);
  166. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  167. CXXScopeSpec NewSS, *NewSSPtr = SS;
  168. if (SS && NNS) {
  169. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  170. NewSSPtr = &NewSS;
  171. }
  172. if (Correction && (NNS || NewII != &II) &&
  173. // Ignore a correction to a template type as the to-be-corrected
  174. // identifier is not a template (typo correction for template names
  175. // is handled elsewhere).
  176. !(getLangOptions().CPlusPlus && NewSSPtr &&
  177. isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
  178. false, Template, MemberOfUnknownSpecialization))) {
  179. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  180. isClassName, HasTrailingDot, ObjectTypePtr,
  181. IsCtorOrDtorName,
  182. WantNontrivialTypeSourceInfo);
  183. if (Ty) {
  184. std::string CorrectedStr(Correction.getAsString(getLangOptions()));
  185. std::string CorrectedQuotedStr(
  186. Correction.getQuoted(getLangOptions()));
  187. Diag(NameLoc, diag::err_unknown_typename_suggest)
  188. << Result.getLookupName() << CorrectedQuotedStr
  189. << FixItHint::CreateReplacement(SourceRange(NameLoc),
  190. CorrectedStr);
  191. if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
  192. Diag(FirstDecl->getLocation(), diag::note_previous_decl)
  193. << CorrectedQuotedStr;
  194. if (SS && NNS)
  195. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  196. *CorrectedII = NewII;
  197. return Ty;
  198. }
  199. }
  200. }
  201. // If typo correction failed or was not performed, fall through
  202. case LookupResult::FoundOverloaded:
  203. case LookupResult::FoundUnresolvedValue:
  204. Result.suppressDiagnostics();
  205. return ParsedType();
  206. case LookupResult::Ambiguous:
  207. // Recover from type-hiding ambiguities by hiding the type. We'll
  208. // do the lookup again when looking for an object, and we can
  209. // diagnose the error then. If we don't do this, then the error
  210. // about hiding the type will be immediately followed by an error
  211. // that only makes sense if the identifier was treated like a type.
  212. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  213. Result.suppressDiagnostics();
  214. return ParsedType();
  215. }
  216. // Look to see if we have a type anywhere in the list of results.
  217. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  218. Res != ResEnd; ++Res) {
  219. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
  220. if (!IIDecl ||
  221. (*Res)->getLocation().getRawEncoding() <
  222. IIDecl->getLocation().getRawEncoding())
  223. IIDecl = *Res;
  224. }
  225. }
  226. if (!IIDecl) {
  227. // None of the entities we found is a type, so there is no way
  228. // to even assume that the result is a type. In this case, don't
  229. // complain about the ambiguity. The parser will either try to
  230. // perform this lookup again (e.g., as an object name), which
  231. // will produce the ambiguity, or will complain that it expected
  232. // a type name.
  233. Result.suppressDiagnostics();
  234. return ParsedType();
  235. }
  236. // We found a type within the ambiguous lookup; diagnose the
  237. // ambiguity and then return that type. This might be the right
  238. // answer, or it might not be, but it suppresses any attempt to
  239. // perform the name lookup again.
  240. break;
  241. case LookupResult::Found:
  242. IIDecl = Result.getFoundDecl();
  243. break;
  244. }
  245. assert(IIDecl && "Didn't find decl");
  246. QualType T;
  247. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  248. DiagnoseUseOfDecl(IIDecl, NameLoc);
  249. if (T.isNull())
  250. T = Context.getTypeDeclType(TD);
  251. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  252. // constructor or destructor name (in such a case, the scope specifier
  253. // will be attached to the enclosing Expr or Decl node).
  254. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
  255. if (WantNontrivialTypeSourceInfo) {
  256. // Construct a type with type-source information.
  257. TypeLocBuilder Builder;
  258. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  259. T = getElaboratedType(ETK_None, *SS, T);
  260. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  261. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  262. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  263. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  264. } else {
  265. T = getElaboratedType(ETK_None, *SS, T);
  266. }
  267. }
  268. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  269. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  270. if (!HasTrailingDot)
  271. T = Context.getObjCInterfaceType(IDecl);
  272. }
  273. if (T.isNull()) {
  274. // If it's not plausibly a type, suppress diagnostics.
  275. Result.suppressDiagnostics();
  276. return ParsedType();
  277. }
  278. return ParsedType::make(T);
  279. }
  280. /// isTagName() - This method is called *for error recovery purposes only*
  281. /// to determine if the specified name is a valid tag name ("struct foo"). If
  282. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  283. /// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
  284. /// where the user forgot to specify the tag.
  285. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  286. // Do a tag name lookup in this scope.
  287. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  288. LookupName(R, S, false);
  289. R.suppressDiagnostics();
  290. if (R.getResultKind() == LookupResult::Found)
  291. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  292. switch (TD->getTagKind()) {
  293. case TTK_Struct: return DeclSpec::TST_struct;
  294. case TTK_Union: return DeclSpec::TST_union;
  295. case TTK_Class: return DeclSpec::TST_class;
  296. case TTK_Enum: return DeclSpec::TST_enum;
  297. }
  298. }
  299. return DeclSpec::TST_unspecified;
  300. }
  301. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  302. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  303. /// then downgrade the missing typename error to a warning.
  304. /// This is needed for MSVC compatibility; Example:
  305. /// @code
  306. /// template<class T> class A {
  307. /// public:
  308. /// typedef int TYPE;
  309. /// };
  310. /// template<class T> class B : public A<T> {
  311. /// public:
  312. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  313. /// };
  314. /// @endcode
  315. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  316. if (CurContext->isRecord()) {
  317. const Type *Ty = SS->getScopeRep()->getAsType();
  318. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  319. for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
  320. BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
  321. if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
  322. return true;
  323. return S->isFunctionPrototypeScope();
  324. }
  325. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  326. }
  327. bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
  328. SourceLocation IILoc,
  329. Scope *S,
  330. CXXScopeSpec *SS,
  331. ParsedType &SuggestedType) {
  332. // We don't have anything to suggest (yet).
  333. SuggestedType = ParsedType();
  334. // There may have been a typo in the name of the type. Look up typo
  335. // results, in case we have something that we can suggest.
  336. TypeNameValidatorCCC Validator(false);
  337. if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc),
  338. LookupOrdinaryName, S, SS,
  339. Validator)) {
  340. std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
  341. std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
  342. if (Corrected.isKeyword()) {
  343. // We corrected to a keyword.
  344. // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
  345. Diag(IILoc, diag::err_unknown_typename_suggest)
  346. << &II << CorrectedQuotedStr;
  347. } else {
  348. NamedDecl *Result = Corrected.getCorrectionDecl();
  349. // We found a similarly-named type or interface; suggest that.
  350. if (!SS || !SS->isSet())
  351. Diag(IILoc, diag::err_unknown_typename_suggest)
  352. << &II << CorrectedQuotedStr
  353. << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
  354. else if (DeclContext *DC = computeDeclContext(*SS, false))
  355. Diag(IILoc, diag::err_unknown_nested_typename_suggest)
  356. << &II << DC << CorrectedQuotedStr << SS->getRange()
  357. << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
  358. else
  359. llvm_unreachable("could not have corrected a typo here");
  360. Diag(Result->getLocation(), diag::note_previous_decl)
  361. << CorrectedQuotedStr;
  362. SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
  363. false, false, ParsedType(),
  364. /*IsCtorOrDtorName=*/false,
  365. /*NonTrivialTypeSourceInfo=*/true);
  366. }
  367. return true;
  368. }
  369. if (getLangOptions().CPlusPlus) {
  370. // See if II is a class template that the user forgot to pass arguments to.
  371. UnqualifiedId Name;
  372. Name.setIdentifier(&II, IILoc);
  373. CXXScopeSpec EmptySS;
  374. TemplateTy TemplateResult;
  375. bool MemberOfUnknownSpecialization;
  376. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  377. Name, ParsedType(), true, TemplateResult,
  378. MemberOfUnknownSpecialization) == TNK_Type_template) {
  379. TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
  380. Diag(IILoc, diag::err_template_missing_args) << TplName;
  381. if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
  382. Diag(TplDecl->getLocation(), diag::note_template_decl_here)
  383. << TplDecl->getTemplateParameters()->getSourceRange();
  384. }
  385. return true;
  386. }
  387. }
  388. // FIXME: Should we move the logic that tries to recover from a missing tag
  389. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  390. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  391. Diag(IILoc, diag::err_unknown_typename) << &II;
  392. else if (DeclContext *DC = computeDeclContext(*SS, false))
  393. Diag(IILoc, diag::err_typename_nested_not_found)
  394. << &II << DC << SS->getRange();
  395. else if (isDependentScopeSpecifier(*SS)) {
  396. unsigned DiagID = diag::err_typename_missing;
  397. if (getLangOptions().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
  398. DiagID = diag::warn_typename_missing;
  399. Diag(SS->getRange().getBegin(), DiagID)
  400. << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
  401. << SourceRange(SS->getRange().getBegin(), IILoc)
  402. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  403. SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc)
  404. .get();
  405. } else {
  406. assert(SS && SS->isInvalid() &&
  407. "Invalid scope specifier has already been diagnosed");
  408. }
  409. return true;
  410. }
  411. /// \brief Determine whether the given result set contains either a type name
  412. /// or
  413. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  414. bool CheckTemplate = R.getSema().getLangOptions().CPlusPlus &&
  415. NextToken.is(tok::less);
  416. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  417. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  418. return true;
  419. if (CheckTemplate && isa<TemplateDecl>(*I))
  420. return true;
  421. }
  422. return false;
  423. }
  424. Sema::NameClassification Sema::ClassifyName(Scope *S,
  425. CXXScopeSpec &SS,
  426. IdentifierInfo *&Name,
  427. SourceLocation NameLoc,
  428. const Token &NextToken) {
  429. DeclarationNameInfo NameInfo(Name, NameLoc);
  430. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  431. if (NextToken.is(tok::coloncolon)) {
  432. BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
  433. QualType(), false, SS, 0, false);
  434. }
  435. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  436. LookupParsedName(Result, S, &SS, !CurMethod);
  437. // Perform lookup for Objective-C instance variables (including automatically
  438. // synthesized instance variables), if we're in an Objective-C method.
  439. // FIXME: This lookup really, really needs to be folded in to the normal
  440. // unqualified lookup mechanism.
  441. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  442. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  443. if (E.get() || E.isInvalid())
  444. return E;
  445. }
  446. bool SecondTry = false;
  447. bool IsFilteredTemplateName = false;
  448. Corrected:
  449. switch (Result.getResultKind()) {
  450. case LookupResult::NotFound:
  451. // If an unqualified-id is followed by a '(', then we have a function
  452. // call.
  453. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  454. // In C++, this is an ADL-only call.
  455. // FIXME: Reference?
  456. if (getLangOptions().CPlusPlus)
  457. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  458. // C90 6.3.2.2:
  459. // If the expression that precedes the parenthesized argument list in a
  460. // function call consists solely of an identifier, and if no
  461. // declaration is visible for this identifier, the identifier is
  462. // implicitly declared exactly as if, in the innermost block containing
  463. // the function call, the declaration
  464. //
  465. // extern int identifier ();
  466. //
  467. // appeared.
  468. //
  469. // We also allow this in C99 as an extension.
  470. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  471. Result.addDecl(D);
  472. Result.resolveKind();
  473. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  474. }
  475. }
  476. // In C, we first see whether there is a tag type by the same name, in
  477. // which case it's likely that the user just forget to write "enum",
  478. // "struct", or "union".
  479. if (!getLangOptions().CPlusPlus && !SecondTry) {
  480. Result.clear(LookupTagName);
  481. LookupParsedName(Result, S, &SS);
  482. if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
  483. const char *TagName = 0;
  484. const char *FixItTagName = 0;
  485. switch (Tag->getTagKind()) {
  486. case TTK_Class:
  487. TagName = "class";
  488. FixItTagName = "class ";
  489. break;
  490. case TTK_Enum:
  491. TagName = "enum";
  492. FixItTagName = "enum ";
  493. break;
  494. case TTK_Struct:
  495. TagName = "struct";
  496. FixItTagName = "struct ";
  497. break;
  498. case TTK_Union:
  499. TagName = "union";
  500. FixItTagName = "union ";
  501. break;
  502. }
  503. Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  504. << Name << TagName << getLangOptions().CPlusPlus
  505. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  506. break;
  507. }
  508. Result.clear(LookupOrdinaryName);
  509. }
  510. // Perform typo correction to determine if there is another name that is
  511. // close to this name.
  512. if (!SecondTry) {
  513. SecondTry = true;
  514. CorrectionCandidateCallback DefaultValidator;
  515. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  516. Result.getLookupKind(), S,
  517. &SS, DefaultValidator)) {
  518. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  519. unsigned QualifiedDiag = diag::err_no_member_suggest;
  520. std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
  521. std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
  522. NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
  523. NamedDecl *UnderlyingFirstDecl
  524. = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
  525. if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
  526. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  527. UnqualifiedDiag = diag::err_no_template_suggest;
  528. QualifiedDiag = diag::err_no_member_template_suggest;
  529. } else if (UnderlyingFirstDecl &&
  530. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  531. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  532. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  533. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  534. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  535. }
  536. if (SS.isEmpty())
  537. Diag(NameLoc, UnqualifiedDiag)
  538. << Name << CorrectedQuotedStr
  539. << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
  540. else
  541. Diag(NameLoc, QualifiedDiag)
  542. << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
  543. << SS.getRange()
  544. << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
  545. // Update the name, so that the caller has the new name.
  546. Name = Corrected.getCorrectionAsIdentifierInfo();
  547. // Typo correction corrected to a keyword.
  548. if (Corrected.isKeyword())
  549. return Corrected.getCorrectionAsIdentifierInfo();
  550. // Also update the LookupResult...
  551. // FIXME: This should probably go away at some point
  552. Result.clear();
  553. Result.setLookupName(Corrected.getCorrection());
  554. if (FirstDecl) {
  555. Result.addDecl(FirstDecl);
  556. Diag(FirstDecl->getLocation(), diag::note_previous_decl)
  557. << CorrectedQuotedStr;
  558. }
  559. // If we found an Objective-C instance variable, let
  560. // LookupInObjCMethod build the appropriate expression to
  561. // reference the ivar.
  562. // FIXME: This is a gross hack.
  563. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  564. Result.clear();
  565. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  566. return move(E);
  567. }
  568. goto Corrected;
  569. }
  570. }
  571. // We failed to correct; just fall through and let the parser deal with it.
  572. Result.suppressDiagnostics();
  573. return NameClassification::Unknown();
  574. case LookupResult::NotFoundInCurrentInstantiation: {
  575. // We performed name lookup into the current instantiation, and there were
  576. // dependent bases, so we treat this result the same way as any other
  577. // dependent nested-name-specifier.
  578. // C++ [temp.res]p2:
  579. // A name used in a template declaration or definition and that is
  580. // dependent on a template-parameter is assumed not to name a type
  581. // unless the applicable name lookup finds a type name or the name is
  582. // qualified by the keyword typename.
  583. //
  584. // FIXME: If the next token is '<', we might want to ask the parser to
  585. // perform some heroics to see if we actually have a
  586. // template-argument-list, which would indicate a missing 'template'
  587. // keyword here.
  588. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  589. NameInfo, /*TemplateArgs=*/0);
  590. }
  591. case LookupResult::Found:
  592. case LookupResult::FoundOverloaded:
  593. case LookupResult::FoundUnresolvedValue:
  594. break;
  595. case LookupResult::Ambiguous:
  596. if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
  597. hasAnyAcceptableTemplateNames(Result)) {
  598. // C++ [temp.local]p3:
  599. // A lookup that finds an injected-class-name (10.2) can result in an
  600. // ambiguity in certain cases (for example, if it is found in more than
  601. // one base class). If all of the injected-class-names that are found
  602. // refer to specializations of the same class template, and if the name
  603. // is followed by a template-argument-list, the reference refers to the
  604. // class template itself and not a specialization thereof, and is not
  605. // ambiguous.
  606. //
  607. // This filtering can make an ambiguous result into an unambiguous one,
  608. // so try again after filtering out template names.
  609. FilterAcceptableTemplateNames(Result);
  610. if (!Result.isAmbiguous()) {
  611. IsFilteredTemplateName = true;
  612. break;
  613. }
  614. }
  615. // Diagnose the ambiguity and return an error.
  616. return NameClassification::Error();
  617. }
  618. if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
  619. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  620. // C++ [temp.names]p3:
  621. // After name lookup (3.4) finds that a name is a template-name or that
  622. // an operator-function-id or a literal- operator-id refers to a set of
  623. // overloaded functions any member of which is a function template if
  624. // this is followed by a <, the < is always taken as the delimiter of a
  625. // template-argument-list and never as the less-than operator.
  626. if (!IsFilteredTemplateName)
  627. FilterAcceptableTemplateNames(Result);
  628. if (!Result.empty()) {
  629. bool IsFunctionTemplate;
  630. TemplateName Template;
  631. if (Result.end() - Result.begin() > 1) {
  632. IsFunctionTemplate = true;
  633. Template = Context.getOverloadedTemplateName(Result.begin(),
  634. Result.end());
  635. } else {
  636. TemplateDecl *TD
  637. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  638. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  639. if (SS.isSet() && !SS.isInvalid())
  640. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  641. /*TemplateKeyword=*/false,
  642. TD);
  643. else
  644. Template = TemplateName(TD);
  645. }
  646. if (IsFunctionTemplate) {
  647. // Function templates always go through overload resolution, at which
  648. // point we'll perform the various checks (e.g., accessibility) we need
  649. // to based on which function we selected.
  650. Result.suppressDiagnostics();
  651. return NameClassification::FunctionTemplate(Template);
  652. }
  653. return NameClassification::TypeTemplate(Template);
  654. }
  655. }
  656. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  657. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  658. DiagnoseUseOfDecl(Type, NameLoc);
  659. QualType T = Context.getTypeDeclType(Type);
  660. return ParsedType::make(T);
  661. }
  662. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  663. if (!Class) {
  664. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  665. if (ObjCCompatibleAliasDecl *Alias
  666. = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  667. Class = Alias->getClassInterface();
  668. }
  669. if (Class) {
  670. DiagnoseUseOfDecl(Class, NameLoc);
  671. if (NextToken.is(tok::period)) {
  672. // Interface. <something> is parsed as a property reference expression.
  673. // Just return "unknown" as a fall-through for now.
  674. Result.suppressDiagnostics();
  675. return NameClassification::Unknown();
  676. }
  677. QualType T = Context.getObjCInterfaceType(Class);
  678. return ParsedType::make(T);
  679. }
  680. if (!Result.empty() && (*Result.begin())->isCXXClassMember())
  681. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
  682. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  683. return BuildDeclarationNameExpr(SS, Result, ADL);
  684. }
  685. // Determines the context to return to after temporarily entering a
  686. // context. This depends in an unnecessarily complicated way on the
  687. // exact ordering of callbacks from the parser.
  688. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  689. // Functions defined inline within classes aren't parsed until we've
  690. // finished parsing the top-level class, so the top-level class is
  691. // the context we'll need to return to.
  692. if (isa<FunctionDecl>(DC)) {
  693. DC = DC->getLexicalParent();
  694. // A function not defined within a class will always return to its
  695. // lexical context.
  696. if (!isa<CXXRecordDecl>(DC))
  697. return DC;
  698. // A C++ inline method/friend is parsed *after* the topmost class
  699. // it was declared in is fully parsed ("complete"); the topmost
  700. // class is the context we need to return to.
  701. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  702. DC = RD;
  703. // Return the declaration context of the topmost class the inline method is
  704. // declared in.
  705. return DC;
  706. }
  707. return DC->getLexicalParent();
  708. }
  709. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  710. assert(getContainingDC(DC) == CurContext &&
  711. "The next DeclContext should be lexically contained in the current one.");
  712. CurContext = DC;
  713. S->setEntity(DC);
  714. }
  715. void Sema::PopDeclContext() {
  716. assert(CurContext && "DeclContext imbalance!");
  717. CurContext = getContainingDC(CurContext);
  718. assert(CurContext && "Popped translation unit!");
  719. }
  720. /// EnterDeclaratorContext - Used when we must lookup names in the context
  721. /// of a declarator's nested name specifier.
  722. ///
  723. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  724. // C++0x [basic.lookup.unqual]p13:
  725. // A name used in the definition of a static data member of class
  726. // X (after the qualified-id of the static member) is looked up as
  727. // if the name was used in a member function of X.
  728. // C++0x [basic.lookup.unqual]p14:
  729. // If a variable member of a namespace is defined outside of the
  730. // scope of its namespace then any name used in the definition of
  731. // the variable member (after the declarator-id) is looked up as
  732. // if the definition of the variable member occurred in its
  733. // namespace.
  734. // Both of these imply that we should push a scope whose context
  735. // is the semantic context of the declaration. We can't use
  736. // PushDeclContext here because that context is not necessarily
  737. // lexically contained in the current context. Fortunately,
  738. // the containing scope should have the appropriate information.
  739. assert(!S->getEntity() && "scope already has entity");
  740. #ifndef NDEBUG
  741. Scope *Ancestor = S->getParent();
  742. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  743. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  744. #endif
  745. CurContext = DC;
  746. S->setEntity(DC);
  747. }
  748. void Sema::ExitDeclaratorContext(Scope *S) {
  749. assert(S->getEntity() == CurContext && "Context imbalance!");
  750. // Switch back to the lexical context. The safety of this is
  751. // enforced by an assert in EnterDeclaratorContext.
  752. Scope *Ancestor = S->getParent();
  753. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  754. CurContext = (DeclContext*) Ancestor->getEntity();
  755. // We don't need to do anything with the scope, which is going to
  756. // disappear.
  757. }
  758. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  759. FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  760. if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
  761. // We assume that the caller has already called
  762. // ActOnReenterTemplateScope
  763. FD = TFD->getTemplatedDecl();
  764. }
  765. if (!FD)
  766. return;
  767. PushDeclContext(S, FD);
  768. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  769. ParmVarDecl *Param = FD->getParamDecl(P);
  770. // If the parameter has an identifier, then add it to the scope
  771. if (Param->getIdentifier()) {
  772. S->AddDecl(Param);
  773. IdResolver.AddDecl(Param);
  774. }
  775. }
  776. }
  777. /// \brief Determine whether we allow overloading of the function
  778. /// PrevDecl with another declaration.
  779. ///
  780. /// This routine determines whether overloading is possible, not
  781. /// whether some new function is actually an overload. It will return
  782. /// true in C++ (where we can always provide overloads) or, as an
  783. /// extension, in C when the previous function is already an
  784. /// overloaded function declaration or has the "overloadable"
  785. /// attribute.
  786. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  787. ASTContext &Context) {
  788. if (Context.getLangOptions().CPlusPlus)
  789. return true;
  790. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  791. return true;
  792. return (Previous.getResultKind() == LookupResult::Found
  793. && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
  794. }
  795. /// Add this decl to the scope shadowed decl chains.
  796. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  797. // Move up the scope chain until we find the nearest enclosing
  798. // non-transparent context. The declaration will be introduced into this
  799. // scope.
  800. while (S->getEntity() &&
  801. ((DeclContext *)S->getEntity())->isTransparentContext())
  802. S = S->getParent();
  803. // Add scoped declarations into their context, so that they can be
  804. // found later. Declarations without a context won't be inserted
  805. // into any context.
  806. if (AddToContext)
  807. CurContext->addDecl(D);
  808. // Out-of-line definitions shouldn't be pushed into scope in C++.
  809. // Out-of-line variable and function definitions shouldn't even in C.
  810. if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
  811. D->isOutOfLine() &&
  812. !D->getDeclContext()->getRedeclContext()->Equals(
  813. D->getLexicalDeclContext()->getRedeclContext()))
  814. return;
  815. // Template instantiations should also not be pushed into scope.
  816. if (isa<FunctionDecl>(D) &&
  817. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  818. return;
  819. // If this replaces anything in the current scope,
  820. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  821. IEnd = IdResolver.end();
  822. for (; I != IEnd; ++I) {
  823. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  824. S->RemoveDecl(*I);
  825. IdResolver.RemoveDecl(*I);
  826. // Should only need to replace one decl.
  827. break;
  828. }
  829. }
  830. S->AddDecl(D);
  831. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  832. // Implicitly-generated labels may end up getting generated in an order that
  833. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  834. // the label at the appropriate place in the identifier chain.
  835. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  836. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  837. if (IDC == CurContext) {
  838. if (!S->isDeclScope(*I))
  839. continue;
  840. } else if (IDC->Encloses(CurContext))
  841. break;
  842. }
  843. IdResolver.InsertDeclAfter(I, D);
  844. } else {
  845. IdResolver.AddDecl(D);
  846. }
  847. }
  848. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  849. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  850. TUScope->AddDecl(D);
  851. }
  852. bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
  853. bool ExplicitInstantiationOrSpecialization) {
  854. return IdResolver.isDeclInScope(D, Ctx, Context, S,
  855. ExplicitInstantiationOrSpecialization);
  856. }
  857. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  858. DeclContext *TargetDC = DC->getPrimaryContext();
  859. do {
  860. if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
  861. if (ScopeDC->getPrimaryContext() == TargetDC)
  862. return S;
  863. } while ((S = S->getParent()));
  864. return 0;
  865. }
  866. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  867. DeclContext*,
  868. ASTContext&);
  869. /// Filters out lookup results that don't fall within the given scope
  870. /// as determined by isDeclInScope.
  871. void Sema::FilterLookupForScope(LookupResult &R,
  872. DeclContext *Ctx, Scope *S,
  873. bool ConsiderLinkage,
  874. bool ExplicitInstantiationOrSpecialization) {
  875. LookupResult::Filter F = R.makeFilter();
  876. while (F.hasNext()) {
  877. NamedDecl *D = F.next();
  878. if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
  879. continue;
  880. if (ConsiderLinkage &&
  881. isOutOfScopePreviousDeclaration(D, Ctx, Context))
  882. continue;
  883. F.erase();
  884. }
  885. F.done();
  886. }
  887. static bool isUsingDecl(NamedDecl *D) {
  888. return isa<UsingShadowDecl>(D) ||
  889. isa<UnresolvedUsingTypenameDecl>(D) ||
  890. isa<UnresolvedUsingValueDecl>(D);
  891. }
  892. /// Removes using shadow declarations from the lookup results.
  893. static void RemoveUsingDecls(LookupResult &R) {
  894. LookupResult::Filter F = R.makeFilter();
  895. while (F.hasNext())
  896. if (isUsingDecl(F.next()))
  897. F.erase();
  898. F.done();
  899. }
  900. /// \brief Check for this common pattern:
  901. /// @code
  902. /// class S {
  903. /// S(const S&); // DO NOT IMPLEMENT
  904. /// void operator=(const S&); // DO NOT IMPLEMENT
  905. /// };
  906. /// @endcode
  907. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  908. // FIXME: Should check for private access too but access is set after we get
  909. // the decl here.
  910. if (D->doesThisDeclarationHaveABody())
  911. return false;
  912. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  913. return CD->isCopyConstructor();
  914. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  915. return Method->isCopyAssignmentOperator();
  916. return false;
  917. }
  918. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  919. assert(D);
  920. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  921. return false;
  922. // Ignore class templates.
  923. if (D->getDeclContext()->isDependentContext() ||
  924. D->getLexicalDeclContext()->isDependentContext())
  925. return false;
  926. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  927. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  928. return false;
  929. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  930. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  931. return false;
  932. } else {
  933. // 'static inline' functions are used in headers; don't warn.
  934. if (FD->getStorageClass() == SC_Static &&
  935. FD->isInlineSpecified())
  936. return false;
  937. }
  938. if (FD->doesThisDeclarationHaveABody() &&
  939. Context.DeclMustBeEmitted(FD))
  940. return false;
  941. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  942. if (!VD->isFileVarDecl() ||
  943. VD->getType().isConstant(Context) ||
  944. Context.DeclMustBeEmitted(VD))
  945. return false;
  946. if (VD->isStaticDataMember() &&
  947. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  948. return false;
  949. } else {
  950. return false;
  951. }
  952. // Only warn for unused decls internal to the translation unit.
  953. if (D->getLinkage() == ExternalLinkage)
  954. return false;
  955. return true;
  956. }
  957. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  958. if (!D)
  959. return;
  960. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  961. const FunctionDecl *First = FD->getFirstDeclaration();
  962. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  963. return; // First should already be in the vector.
  964. }
  965. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  966. const VarDecl *First = VD->getFirstDeclaration();
  967. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  968. return; // First should already be in the vector.
  969. }
  970. if (ShouldWarnIfUnusedFileScopedDecl(D))
  971. UnusedFileScopedDecls.push_back(D);
  972. }
  973. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  974. if (D->isInvalidDecl())
  975. return false;
  976. if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
  977. return false;
  978. if (isa<LabelDecl>(D))
  979. return true;
  980. // White-list anything that isn't a local variable.
  981. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
  982. !D->getDeclContext()->isFunctionOrMethod())
  983. return false;
  984. // Types of valid local variables should be complete, so this should succeed.
  985. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  986. // White-list anything with an __attribute__((unused)) type.
  987. QualType Ty = VD->getType();
  988. // Only look at the outermost level of typedef.
  989. if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
  990. if (TT->getDecl()->hasAttr<UnusedAttr>())
  991. return false;
  992. }
  993. // If we failed to complete the type for some reason, or if the type is
  994. // dependent, don't diagnose the variable.
  995. if (Ty->isIncompleteType() || Ty->isDependentType())
  996. return false;
  997. if (const TagType *TT = Ty->getAs<TagType>()) {
  998. const TagDecl *Tag = TT->getDecl();
  999. if (Tag->hasAttr<UnusedAttr>())
  1000. return false;
  1001. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1002. if (!RD->hasTrivialDestructor())
  1003. return false;
  1004. if (const Expr *Init = VD->getInit()) {
  1005. const CXXConstructExpr *Construct =
  1006. dyn_cast<CXXConstructExpr>(Init);
  1007. if (Construct && !Construct->isElidable()) {
  1008. CXXConstructorDecl *CD = Construct->getConstructor();
  1009. if (!CD->isTrivial())
  1010. return false;
  1011. }
  1012. }
  1013. }
  1014. }
  1015. // TODO: __attribute__((unused)) templates?
  1016. }
  1017. return true;
  1018. }
  1019. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1020. FixItHint &Hint) {
  1021. if (isa<LabelDecl>(D)) {
  1022. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1023. tok::colon, Ctx.getSourceManager(), Ctx.getLangOptions(), true);
  1024. if (AfterColon.isInvalid())
  1025. return;
  1026. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1027. getCharRange(D->getLocStart(), AfterColon));
  1028. }
  1029. return;
  1030. }
  1031. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1032. /// unless they are marked attr(unused).
  1033. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1034. FixItHint Hint;
  1035. if (!ShouldDiagnoseUnusedDecl(D))
  1036. return;
  1037. GenerateFixForUnusedDecl(D, Context, Hint);
  1038. unsigned DiagID;
  1039. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1040. DiagID = diag::warn_unused_exception_param;
  1041. else if (isa<LabelDecl>(D))
  1042. DiagID = diag::warn_unused_label;
  1043. else
  1044. DiagID = diag::warn_unused_variable;
  1045. Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
  1046. }
  1047. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1048. // Verify that we have no forward references left. If so, there was a goto
  1049. // or address of a label taken, but no definition of it. Label fwd
  1050. // definitions are indicated with a null substmt.
  1051. if (L->getStmt() == 0)
  1052. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1053. }
  1054. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1055. if (S->decl_empty()) return;
  1056. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1057. "Scope shouldn't contain decls!");
  1058. for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
  1059. I != E; ++I) {
  1060. Decl *TmpD = (*I);
  1061. assert(TmpD && "This decl didn't get pushed??");
  1062. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1063. NamedDecl *D = cast<NamedDecl>(TmpD);
  1064. if (!D->getDeclName()) continue;
  1065. // Diagnose unused variables in this scope.
  1066. if (!S->hasErrorOccurred())
  1067. DiagnoseUnusedDecl(D);
  1068. // If this was a forward reference to a label, verify it was defined.
  1069. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1070. CheckPoppedLabel(LD, *this);
  1071. // Remove this name from our lexical scope.
  1072. IdResolver.RemoveDecl(D);
  1073. }
  1074. }
  1075. /// \brief Look for an Objective-C class in the translation unit.
  1076. ///
  1077. /// \param Id The name of the Objective-C class we're looking for. If
  1078. /// typo-correction fixes this name, the Id will be updated
  1079. /// to the fixed name.
  1080. ///
  1081. /// \param IdLoc The location of the name in the translation unit.
  1082. ///
  1083. /// \param TypoCorrection If true, this routine will attempt typo correction
  1084. /// if there is no class with the given name.
  1085. ///
  1086. /// \returns The declaration of the named Objective-C class, or NULL if the
  1087. /// class could not be found.
  1088. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1089. SourceLocation IdLoc,
  1090. bool DoTypoCorrection) {
  1091. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1092. // creation from this context.
  1093. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1094. if (!IDecl && DoTypoCorrection) {
  1095. // Perform typo correction at the given location, but only if we
  1096. // find an Objective-C class name.
  1097. DeclFilterCCC<ObjCInterfaceDecl> Validator;
  1098. if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
  1099. LookupOrdinaryName, TUScope, NULL,
  1100. Validator)) {
  1101. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1102. Diag(IdLoc, diag::err_undef_interface_suggest)
  1103. << Id << IDecl->getDeclName()
  1104. << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
  1105. Diag(IDecl->getLocation(), diag::note_previous_decl)
  1106. << IDecl->getDeclName();
  1107. Id = IDecl->getIdentifier();
  1108. }
  1109. }
  1110. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1111. // This routine must always return a class definition, if any.
  1112. if (Def && Def->getDefinition())
  1113. Def = Def->getDefinition();
  1114. return Def;
  1115. }
  1116. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1117. /// from S, where a non-field would be declared. This routine copes
  1118. /// with the difference between C and C++ scoping rules in structs and
  1119. /// unions. For example, the following code is well-formed in C but
  1120. /// ill-formed in C++:
  1121. /// @code
  1122. /// struct S6 {
  1123. /// enum { BAR } e;
  1124. /// };
  1125. ///
  1126. /// void test_S6() {
  1127. /// struct S6 a;
  1128. /// a.e = BAR;
  1129. /// }
  1130. /// @endcode
  1131. /// For the declaration of BAR, this routine will return a different
  1132. /// scope. The scope S will be the scope of the unnamed enumeration
  1133. /// within S6. In C++, this routine will return the scope associated
  1134. /// with S6, because the enumeration's scope is a transparent
  1135. /// context but structures can contain non-field names. In C, this
  1136. /// routine will return the translation unit scope, since the
  1137. /// enumeration's scope is a transparent context and structures cannot
  1138. /// contain non-field names.
  1139. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1140. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1141. (S->getEntity() &&
  1142. ((DeclContext *)S->getEntity())->isTransparentContext()) ||
  1143. (S->isClassScope() && !getLangOptions().CPlusPlus))
  1144. S = S->getParent();
  1145. return S;
  1146. }
  1147. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1148. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1149. /// if we're creating this built-in in anticipation of redeclaring the
  1150. /// built-in.
  1151. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
  1152. Scope *S, bool ForRedeclaration,
  1153. SourceLocation Loc) {
  1154. Builtin::ID BID = (Builtin::ID)bid;
  1155. ASTContext::GetBuiltinTypeError Error;
  1156. QualType R = Context.GetBuiltinType(BID, Error);
  1157. switch (Error) {
  1158. case ASTContext::GE_None:
  1159. // Okay
  1160. break;
  1161. case ASTContext::GE_Missing_stdio:
  1162. if (ForRedeclaration)
  1163. Diag(Loc, diag::warn_implicit_decl_requires_stdio)
  1164. << Context.BuiltinInfo.GetName(BID);
  1165. return 0;
  1166. case ASTContext::GE_Missing_setjmp:
  1167. if (ForRedeclaration)
  1168. Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
  1169. << Context.BuiltinInfo.GetName(BID);
  1170. return 0;
  1171. case ASTContext::GE_Missing_ucontext:
  1172. if (ForRedeclaration)
  1173. Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
  1174. << Context.BuiltinInfo.GetName(BID);
  1175. return 0;
  1176. }
  1177. if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  1178. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1179. << Context.BuiltinInfo.GetName(BID)
  1180. << R;
  1181. if (Context.BuiltinInfo.getHeaderName(BID) &&
  1182. Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
  1183. != DiagnosticsEngine::Ignored)
  1184. Diag(Loc, diag::note_please_include_header)
  1185. << Context.BuiltinInfo.getHeaderName(BID)
  1186. << Context.BuiltinInfo.GetName(BID);
  1187. }
  1188. FunctionDecl *New = FunctionDecl::Create(Context,
  1189. Context.getTranslationUnitDecl(),
  1190. Loc, Loc, II, R, /*TInfo=*/0,
  1191. SC_Extern,
  1192. SC_None, false,
  1193. /*hasPrototype=*/true);
  1194. New->setImplicit();
  1195. // Create Decl objects for each parameter, adding them to the
  1196. // FunctionDecl.
  1197. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1198. SmallVector<ParmVarDecl*, 16> Params;
  1199. for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
  1200. ParmVarDecl *parm =
  1201. ParmVarDecl::Create(Context, New, SourceLocation(),
  1202. SourceLocation(), 0,
  1203. FT->getArgType(i), /*TInfo=*/0,
  1204. SC_None, SC_None, 0);
  1205. parm->setScopeInfo(0, i);
  1206. Params.push_back(parm);
  1207. }
  1208. New->setParams(Params);
  1209. }
  1210. AddKnownFunctionAttributes(New);
  1211. // TUScope is the translation-unit scope to insert this function into.
  1212. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1213. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1214. // entirely, but we're not there yet.
  1215. DeclContext *SavedContext = CurContext;
  1216. CurContext = Context.getTranslationUnitDecl();
  1217. PushOnScopeChains(New, TUScope);
  1218. CurContext = SavedContext;
  1219. return New;
  1220. }
  1221. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1222. QualType OldType;
  1223. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1224. OldType = OldTypedef->getUnderlyingType();
  1225. else
  1226. OldType = Context.getTypeDeclType(Old);
  1227. QualType NewType = New->getUnderlyingType();
  1228. if (NewType->isVariablyModifiedType()) {
  1229. // Must not redefine a typedef with a variably-modified type.
  1230. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1231. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1232. << Kind << NewType;
  1233. if (Old->getLocation().isValid())
  1234. Diag(Old->getLocation(), diag::note_previous_definition);
  1235. New->setInvalidDecl();
  1236. return true;
  1237. }
  1238. if (OldType != NewType &&
  1239. !OldType->isDependentType() &&
  1240. !NewType->isDependentType() &&
  1241. !Context.hasSameType(OldType, NewType)) {
  1242. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1243. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1244. << Kind << NewType << OldType;
  1245. if (Old->getLocation().isValid())
  1246. Diag(Old->getLocation(), diag::note_previous_definition);
  1247. New->setInvalidDecl();
  1248. return true;
  1249. }
  1250. return false;
  1251. }
  1252. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1253. /// same name and scope as a previous declaration 'Old'. Figure out
  1254. /// how to resolve this situation, merging decls or emitting
  1255. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1256. ///
  1257. void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
  1258. // If the new decl is known invalid already, don't bother doing any
  1259. // merging checks.
  1260. if (New->isInvalidDecl()) return;
  1261. // Allow multiple definitions for ObjC built-in typedefs.
  1262. // FIXME: Verify the underlying types are equivalent!
  1263. if (getLangOptions().ObjC1) {
  1264. const IdentifierInfo *TypeID = New->getIdentifier();
  1265. switch (TypeID->getLength()) {
  1266. default: break;
  1267. case 2:
  1268. if (!TypeID->isStr("id"))
  1269. break;
  1270. Context.setObjCIdRedefinitionType(New->getUnderlyingType());
  1271. // Install the built-in type for 'id', ignoring the current definition.
  1272. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1273. return;
  1274. case 5:
  1275. if (!TypeID->isStr("Class"))
  1276. break;
  1277. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1278. // Install the built-in type for 'Class', ignoring the current definition.
  1279. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1280. return;
  1281. case 3:
  1282. if (!TypeID->isStr("SEL"))
  1283. break;
  1284. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1285. // Install the built-in type for 'SEL', ignoring the current definition.
  1286. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1287. return;
  1288. }
  1289. // Fall through - the typedef name was not a builtin type.
  1290. }
  1291. // Verify the old decl was also a type.
  1292. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1293. if (!Old) {
  1294. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1295. << New->getDeclName();
  1296. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1297. if (OldD->getLocation().isValid())
  1298. Diag(OldD->getLocation(), diag::note_previous_definition);
  1299. return New->setInvalidDecl();
  1300. }
  1301. // If the old declaration is invalid, just give up here.
  1302. if (Old->isInvalidDecl())
  1303. return New->setInvalidDecl();
  1304. // If the typedef types are not identical, reject them in all languages and
  1305. // with any extensions enabled.
  1306. if (isIncompatibleTypedef(Old, New))
  1307. return;
  1308. // The types match. Link up the redeclaration chain if the old
  1309. // declaration was a typedef.
  1310. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
  1311. New->setPreviousDeclaration(Typedef);
  1312. if (getLangOptions().MicrosoftExt)
  1313. return;
  1314. if (getLangOptions().CPlusPlus) {
  1315. // C++ [dcl.typedef]p2:
  1316. // In a given non-class scope, a typedef specifier can be used to
  1317. // redefine the name of any type declared in that scope to refer
  1318. // to the type to which it already refers.
  1319. if (!isa<CXXRecordDecl>(CurContext))
  1320. return;
  1321. // C++0x [dcl.typedef]p4:
  1322. // In a given class scope, a typedef specifier can be used to redefine
  1323. // any class-name declared in that scope that is not also a typedef-name
  1324. // to refer to the type to which it already refers.
  1325. //
  1326. // This wording came in via DR424, which was a correction to the
  1327. // wording in DR56, which accidentally banned code like:
  1328. //
  1329. // struct S {
  1330. // typedef struct A { } A;
  1331. // };
  1332. //
  1333. // in the C++03 standard. We implement the C++0x semantics, which
  1334. // allow the above but disallow
  1335. //
  1336. // struct S {
  1337. // typedef int I;
  1338. // typedef int I;
  1339. // };
  1340. //
  1341. // since that was the intent of DR56.
  1342. if (!isa<TypedefNameDecl>(Old))
  1343. return;
  1344. Diag(New->getLocation(), diag::err_redefinition)
  1345. << New->getDeclName();
  1346. Diag(Old->getLocation(), diag::note_previous_definition);
  1347. return New->setInvalidDecl();
  1348. }
  1349. // Modules always permit redefinition of typedefs, as does C11.
  1350. if (getLangOptions().Modules || getLangOptions().C11)
  1351. return;
  1352. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1353. // is normally mapped to an error, but can be controlled with
  1354. // -Wtypedef-redefinition. If either the original or the redefinition is
  1355. // in a system header, don't emit this for compatibility with GCC.
  1356. if (getDiagnostics().getSuppressSystemWarnings() &&
  1357. (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1358. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1359. return;
  1360. Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
  1361. << New->getDeclName();
  1362. Diag(Old->getLocation(), diag::note_previous_definition);
  1363. return;
  1364. }
  1365. /// DeclhasAttr - returns true if decl Declaration already has the target
  1366. /// attribute.
  1367. static bool
  1368. DeclHasAttr(const Decl *D, const Attr *A) {
  1369. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  1370. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  1371. for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
  1372. if ((*i)->getKind() == A->getKind()) {
  1373. if (Ann) {
  1374. if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
  1375. return true;
  1376. continue;
  1377. }
  1378. // FIXME: Don't hardcode this check
  1379. if (OA && isa<OwnershipAttr>(*i))
  1380. return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
  1381. return true;
  1382. }
  1383. return false;
  1384. }
  1385. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  1386. void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
  1387. bool MergeDeprecation) {
  1388. if (!Old->hasAttrs())
  1389. return;
  1390. bool foundAny = New->hasAttrs();
  1391. // Ensure that any moving of objects within the allocated map is done before
  1392. // we process them.
  1393. if (!foundAny) New->setAttrs(AttrVec());
  1394. for (specific_attr_iterator<InheritableAttr>
  1395. i = Old->specific_attr_begin<InheritableAttr>(),
  1396. e = Old->specific_attr_end<InheritableAttr>();
  1397. i != e; ++i) {
  1398. // Ignore deprecated/unavailable/availability attributes if requested.
  1399. if (!MergeDeprecation &&
  1400. (isa<DeprecatedAttr>(*i) ||
  1401. isa<UnavailableAttr>(*i) ||
  1402. isa<AvailabilityAttr>(*i)))
  1403. continue;
  1404. if (!DeclHasAttr(New, *i)) {
  1405. InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(Context));
  1406. newAttr->setInherited(true);
  1407. New->addAttr(newAttr);
  1408. foundAny = true;
  1409. }
  1410. }
  1411. if (!foundAny) New->dropAttrs();
  1412. }
  1413. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  1414. /// to the new one.
  1415. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  1416. const ParmVarDecl *oldDecl,
  1417. ASTContext &C) {
  1418. if (!oldDecl->hasAttrs())
  1419. return;
  1420. bool foundAny = newDecl->hasAttrs();
  1421. // Ensure that any moving of objects within the allocated map is
  1422. // done before we process them.
  1423. if (!foundAny) newDecl->setAttrs(AttrVec());
  1424. for (specific_attr_iterator<InheritableParamAttr>
  1425. i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
  1426. e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
  1427. if (!DeclHasAttr(newDecl, *i)) {
  1428. InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
  1429. newAttr->setInherited(true);
  1430. newDecl->addAttr(newAttr);
  1431. foundAny = true;
  1432. }
  1433. }
  1434. if (!foundAny) newDecl->dropAttrs();
  1435. }
  1436. namespace {
  1437. /// Used in MergeFunctionDecl to keep track of function parameters in
  1438. /// C.
  1439. struct GNUCompatibleParamWarning {
  1440. ParmVarDecl *OldParm;
  1441. ParmVarDecl *NewParm;
  1442. QualType PromotedType;
  1443. };
  1444. }
  1445. /// getSpecialMember - get the special member enum for a method.
  1446. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  1447. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  1448. if (Ctor->isDefaultConstructor())
  1449. return Sema::CXXDefaultConstructor;
  1450. if (Ctor->isCopyConstructor())
  1451. return Sema::CXXCopyConstructor;
  1452. if (Ctor->isMoveConstructor())
  1453. return Sema::CXXMoveConstructor;
  1454. } else if (isa<CXXDestructorDecl>(MD)) {
  1455. return Sema::CXXDestructor;
  1456. } else if (MD->isCopyAssignmentOperator()) {
  1457. return Sema::CXXCopyAssignment;
  1458. } else if (MD->isMoveAssignmentOperator()) {
  1459. return Sema::CXXMoveAssignment;
  1460. }
  1461. return Sema::CXXInvalid;
  1462. }
  1463. /// canRedefineFunction - checks if a function can be redefined. Currently,
  1464. /// only extern inline functions can be redefined, and even then only in
  1465. /// GNU89 mode.
  1466. static bool canRedefineFunction(const FunctionDecl *FD,
  1467. const LangOptions& LangOpts) {
  1468. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  1469. !LangOpts.CPlusPlus &&
  1470. FD->isInlineSpecified() &&
  1471. FD->getStorageClass() == SC_Extern);
  1472. }
  1473. /// MergeFunctionDecl - We just parsed a function 'New' from
  1474. /// declarator D which has the same name and scope as a previous
  1475. /// declaration 'Old'. Figure out how to resolve this situation,
  1476. /// merging decls or emitting diagnostics as appropriate.
  1477. ///
  1478. /// In C++, New and Old must be declarations that are not
  1479. /// overloaded. Use IsOverload to determine whether New and Old are
  1480. /// overloaded, and to select the Old declaration that New should be
  1481. /// merged with.
  1482. ///
  1483. /// Returns true if there was an error, false otherwise.
  1484. bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
  1485. // Verify the old decl was also a function.
  1486. FunctionDecl *Old = 0;
  1487. if (FunctionTemplateDecl *OldFunctionTemplate
  1488. = dyn_cast<FunctionTemplateDecl>(OldD))
  1489. Old = OldFunctionTemplate->getTemplatedDecl();
  1490. else
  1491. Old = dyn_cast<FunctionDecl>(OldD);
  1492. if (!Old) {
  1493. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  1494. Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  1495. Diag(Shadow->getTargetDecl()->getLocation(),
  1496. diag::note_using_decl_target);
  1497. Diag(Shadow->getUsingDecl()->getLocation(),
  1498. diag::note_using_decl) << 0;
  1499. return true;
  1500. }
  1501. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1502. << New->getDeclName();
  1503. Diag(OldD->getLocation(), diag::note_previous_definition);
  1504. return true;
  1505. }
  1506. // Determine whether the previous declaration was a definition,
  1507. // implicit declaration, or a declaration.
  1508. diag::kind PrevDiag;
  1509. if (Old->isThisDeclarationADefinition())
  1510. PrevDiag = diag::note_previous_definition;
  1511. else if (Old->isImplicit())
  1512. PrevDiag = diag::note_previous_implicit_declaration;
  1513. else
  1514. PrevDiag = diag::note_previous_declaration;
  1515. QualType OldQType = Context.getCanonicalType(Old->getType());
  1516. QualType NewQType = Context.getCanonicalType(New->getType());
  1517. // Don't complain about this if we're in GNU89 mode and the old function
  1518. // is an extern inline function.
  1519. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  1520. New->getStorageClass() == SC_Static &&
  1521. Old->getStorageClass() != SC_Static &&
  1522. !canRedefineFunction(Old, getLangOptions())) {
  1523. if (getLangOptions().MicrosoftExt) {
  1524. Diag(New->getLocation(), diag::warn_static_non_static) << New;
  1525. Diag(Old->getLocation(), PrevDiag);
  1526. } else {
  1527. Diag(New->getLocation(), diag::err_static_non_static) << New;
  1528. Diag(Old->getLocation(), PrevDiag);
  1529. return true;
  1530. }
  1531. }
  1532. // If a function is first declared with a calling convention, but is
  1533. // later declared or defined without one, the second decl assumes the
  1534. // calling convention of the first.
  1535. //
  1536. // For the new decl, we have to look at the NON-canonical type to tell the
  1537. // difference between a function that really doesn't have a calling
  1538. // convention and one that is declared cdecl. That's because in
  1539. // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
  1540. // because it is the default calling convention.
  1541. //
  1542. // Note also that we DO NOT return at this point, because we still have
  1543. // other tests to run.
  1544. const FunctionType *OldType = cast<FunctionType>(OldQType);
  1545. const FunctionType *NewType = New->getType()->getAs<FunctionType>();
  1546. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  1547. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  1548. bool RequiresAdjustment = false;
  1549. if (OldTypeInfo.getCC() != CC_Default &&
  1550. NewTypeInfo.getCC() == CC_Default) {
  1551. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  1552. RequiresAdjustment = true;
  1553. } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
  1554. NewTypeInfo.getCC())) {
  1555. // Calling conventions really aren't compatible, so complain.
  1556. Diag(New->getLocation(), diag::err_cconv_change)
  1557. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  1558. << (OldTypeInfo.getCC() == CC_Default)
  1559. << (OldTypeInfo.getCC() == CC_Default ? "" :
  1560. FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
  1561. Diag(Old->getLocation(), diag::note_previous_declaration);
  1562. return true;
  1563. }
  1564. // FIXME: diagnose the other way around?
  1565. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  1566. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  1567. RequiresAdjustment = true;
  1568. }
  1569. // Merge regparm attribute.
  1570. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  1571. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  1572. if (NewTypeInfo.getHasRegParm()) {
  1573. Diag(New->getLocation(), diag::err_regparm_mismatch)
  1574. << NewType->getRegParmType()
  1575. << OldType->getRegParmType();
  1576. Diag(Old->getLocation(), diag::note_previous_declaration);
  1577. return true;
  1578. }
  1579. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  1580. RequiresAdjustment = true;
  1581. }
  1582. // Merge ns_returns_retained attribute.
  1583. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  1584. if (NewTypeInfo.getProducesResult()) {
  1585. Diag(New->getLocation(), diag::err_returns_retained_mismatch);
  1586. Diag(Old->getLocation(), diag::note_previous_declaration);
  1587. return true;
  1588. }
  1589. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  1590. RequiresAdjustment = true;
  1591. }
  1592. if (RequiresAdjustment) {
  1593. NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
  1594. New->setType(QualType(NewType, 0));
  1595. NewQType = Context.getCanonicalType(New->getType());
  1596. }
  1597. if (getLangOptions().CPlusPlus) {
  1598. // (C++98 13.1p2):
  1599. // Certain function declarations cannot be overloaded:
  1600. // -- Function declarations that differ only in the return type
  1601. // cannot be overloaded.
  1602. QualType OldReturnType = OldType->getResultType();
  1603. QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
  1604. QualType ResQT;
  1605. if (OldReturnType != NewReturnType) {
  1606. if (NewReturnType->isObjCObjectPointerType()
  1607. && OldReturnType->isObjCObjectPointerType())
  1608. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  1609. if (ResQT.isNull()) {
  1610. if (New->isCXXClassMember() && New->isOutOfLine())
  1611. Diag(New->getLocation(),
  1612. diag::err_member_def_does_not_match_ret_type) << New;
  1613. else
  1614. Diag(New->getLocation(), diag::err_ovl_diff_return_type);
  1615. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1616. return true;
  1617. }
  1618. else
  1619. NewQType = ResQT;
  1620. }
  1621. const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
  1622. CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
  1623. if (OldMethod && NewMethod) {
  1624. // Preserve triviality.
  1625. NewMethod->setTrivial(OldMethod->isTrivial());
  1626. // MSVC allows explicit template specialization at class scope:
  1627. // 2 CXMethodDecls referring to the same function will be injected.
  1628. // We don't want a redeclartion error.
  1629. bool IsClassScopeExplicitSpecialization =
  1630. OldMethod->isFunctionTemplateSpecialization() &&
  1631. NewMethod->isFunctionTemplateSpecialization();
  1632. bool isFriend = NewMethod->getFriendObjectKind();
  1633. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  1634. !IsClassScopeExplicitSpecialization) {
  1635. // -- Member function declarations with the same name and the
  1636. // same parameter types cannot be overloaded if any of them
  1637. // is a static member function declaration.
  1638. if (OldMethod->isStatic() || NewMethod->isStatic()) {
  1639. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  1640. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1641. return true;
  1642. }
  1643. // C++ [class.mem]p1:
  1644. // [...] A member shall not be declared twice in the
  1645. // member-specification, except that a nested class or member
  1646. // class template can be declared and then later defined.
  1647. unsigned NewDiag;
  1648. if (isa<CXXConstructorDecl>(OldMethod))
  1649. NewDiag = diag::err_constructor_redeclared;
  1650. else if (isa<CXXDestructorDecl>(NewMethod))
  1651. NewDiag = diag::err_destructor_redeclared;
  1652. else if (isa<CXXConversionDecl>(NewMethod))
  1653. NewDiag = diag::err_conv_function_redeclared;
  1654. else
  1655. NewDiag = diag::err_member_redeclared;
  1656. Diag(New->getLocation(), NewDiag);
  1657. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1658. // Complain if this is an explicit declaration of a special
  1659. // member that was initially declared implicitly.
  1660. //
  1661. // As an exception, it's okay to befriend such methods in order
  1662. // to permit the implicit constructor/destructor/operator calls.
  1663. } else if (OldMethod->isImplicit()) {
  1664. if (isFriend) {
  1665. NewMethod->setImplicit();
  1666. } else {
  1667. Diag(NewMethod->getLocation(),
  1668. diag::err_definition_of_implicitly_declared_member)
  1669. << New << getSpecialMember(OldMethod);
  1670. return true;
  1671. }
  1672. } else if (OldMethod->isExplicitlyDefaulted()) {
  1673. Diag(NewMethod->getLocation(),
  1674. diag::err_definition_of_explicitly_defaulted_member)
  1675. << getSpecialMember(OldMethod);
  1676. return true;
  1677. }
  1678. }
  1679. // (C++98 8.3.5p3):
  1680. // All declarations for a function shall agree exactly in both the
  1681. // return type and the parameter-type-list.
  1682. // We also want to respect all the extended bits except noreturn.
  1683. // noreturn should now match unless the old type info didn't have it.
  1684. QualType OldQTypeForComparison = OldQType;
  1685. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  1686. assert(OldQType == QualType(OldType, 0));
  1687. const FunctionType *OldTypeForComparison
  1688. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  1689. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  1690. assert(OldQTypeForComparison.isCanonical());
  1691. }
  1692. if (OldQTypeForComparison == NewQType)
  1693. return MergeCompatibleFunctionDecls(New, Old);
  1694. // Fall through for conflicting redeclarations and redefinitions.
  1695. }
  1696. // C: Function types need to be compatible, not identical. This handles
  1697. // duplicate function decls like "void f(int); void f(enum X);" properly.
  1698. if (!getLangOptions().CPlusPlus &&
  1699. Context.typesAreCompatible(OldQType, NewQType)) {
  1700. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  1701. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  1702. const FunctionProtoType *OldProto = 0;
  1703. if (isa<FunctionNoProtoType>(NewFuncType) &&
  1704. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  1705. // The old declaration provided a function prototype, but the
  1706. // new declaration does not. Merge in the prototype.
  1707. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  1708. SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
  1709. OldProto->arg_type_end());
  1710. NewQType = Context.getFunctionType(NewFuncType->getResultType(),
  1711. ParamTypes.data(), ParamTypes.size(),
  1712. OldProto->getExtProtoInfo());
  1713. New->setType(NewQType);
  1714. New->setHasInheritedPrototype();
  1715. // Synthesize a parameter for each argument type.
  1716. SmallVector<ParmVarDecl*, 16> Params;
  1717. for (FunctionProtoType::arg_type_iterator
  1718. ParamType = OldProto->arg_type_begin(),
  1719. ParamEnd = OldProto->arg_type_end();
  1720. ParamType != ParamEnd; ++ParamType) {
  1721. ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
  1722. SourceLocation(),
  1723. SourceLocation(), 0,
  1724. *ParamType, /*TInfo=*/0,
  1725. SC_None, SC_None,
  1726. 0);
  1727. Param->setScopeInfo(0, Params.size());
  1728. Param->setImplicit();
  1729. Params.push_back(Param);
  1730. }
  1731. New->setParams(Params);
  1732. }
  1733. return MergeCompatibleFunctionDecls(New, Old);
  1734. }
  1735. // GNU C permits a K&R definition to follow a prototype declaration
  1736. // if the declared types of the parameters in the K&R definition
  1737. // match the types in the prototype declaration, even when the
  1738. // promoted types of the parameters from the K&R definition differ
  1739. // from the types in the prototype. GCC then keeps the types from
  1740. // the prototype.
  1741. //
  1742. // If a variadic prototype is followed by a non-variadic K&R definition,
  1743. // the K&R definition becomes variadic. This is sort of an edge case, but
  1744. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  1745. // C99 6.9.1p8.
  1746. if (!getLangOptions().CPlusPlus &&
  1747. Old->hasPrototype() && !New->hasPrototype() &&
  1748. New->getType()->getAs<FunctionProtoType>() &&
  1749. Old->getNumParams() == New->getNumParams()) {
  1750. SmallVector<QualType, 16> ArgTypes;
  1751. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  1752. const FunctionProtoType *OldProto
  1753. = Old->getType()->getAs<FunctionProtoType>();
  1754. const FunctionProtoType *NewProto
  1755. = New->getType()->getAs<FunctionProtoType>();
  1756. // Determine whether this is the GNU C extension.
  1757. QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
  1758. NewProto->getResultType());
  1759. bool LooseCompatible = !MergedReturn.isNull();
  1760. for (unsigned Idx = 0, End = Old->getNumParams();
  1761. LooseCompatible && Idx != End; ++Idx) {
  1762. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  1763. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  1764. if (Context.typesAreCompatible(OldParm->getType(),
  1765. NewProto->getArgType(Idx))) {
  1766. ArgTypes.push_back(NewParm->getType());
  1767. } else if (Context.typesAreCompatible(OldParm->getType(),
  1768. NewParm->getType(),
  1769. /*CompareUnqualified=*/true)) {
  1770. GNUCompatibleParamWarning Warn
  1771. = { OldParm, NewParm, NewProto->getArgType(Idx) };
  1772. Warnings.push_back(Warn);
  1773. ArgTypes.push_back(NewParm->getType());
  1774. } else
  1775. LooseCompatible = false;
  1776. }
  1777. if (LooseCompatible) {
  1778. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  1779. Diag(Warnings[Warn].NewParm->getLocation(),
  1780. diag::ext_param_promoted_not_compatible_with_prototype)
  1781. << Warnings[Warn].PromotedType
  1782. << Warnings[Warn].OldParm->getType();
  1783. if (Warnings[Warn].OldParm->getLocation().isValid())
  1784. Diag(Warnings[Warn].OldParm->getLocation(),
  1785. diag::note_previous_declaration);
  1786. }
  1787. New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
  1788. ArgTypes.size(),
  1789. OldProto->getExtProtoInfo()));
  1790. return MergeCompatibleFunctionDecls(New, Old);
  1791. }
  1792. // Fall through to diagnose conflicting types.
  1793. }
  1794. // A function that has already been declared has been redeclared or defined
  1795. // with a different type- show appropriate diagnostic
  1796. if (unsigned BuiltinID = Old->getBuiltinID()) {
  1797. // The user has declared a builtin function with an incompatible
  1798. // signature.
  1799. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  1800. // The function the user is redeclaring is a library-defined
  1801. // function like 'malloc' or 'printf'. Warn about the
  1802. // redeclaration, then pretend that we don't know about this
  1803. // library built-in.
  1804. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  1805. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  1806. << Old << Old->getType();
  1807. New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
  1808. Old->setInvalidDecl();
  1809. return false;
  1810. }
  1811. PrevDiag = diag::note_previous_builtin_declaration;
  1812. }
  1813. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  1814. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1815. return true;
  1816. }
  1817. /// \brief Completes the merge of two function declarations that are
  1818. /// known to be compatible.
  1819. ///
  1820. /// This routine handles the merging of attributes and other
  1821. /// properties of function declarations form the old declaration to
  1822. /// the new declaration, once we know that New is in fact a
  1823. /// redeclaration of Old.
  1824. ///
  1825. /// \returns false
  1826. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
  1827. // Merge the attributes
  1828. mergeDeclAttributes(New, Old);
  1829. // Merge the storage class.
  1830. if (Old->getStorageClass() != SC_Extern &&
  1831. Old->getStorageClass() != SC_None)
  1832. New->setStorageClass(Old->getStorageClass());
  1833. // Merge "pure" flag.
  1834. if (Old->isPure())
  1835. New->setPure();
  1836. // Merge attributes from the parameters. These can mismatch with K&R
  1837. // declarations.
  1838. if (New->getNumParams() == Old->getNumParams())
  1839. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
  1840. mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
  1841. Context);
  1842. if (getLangOptions().CPlusPlus)
  1843. return MergeCXXFunctionDecl(New, Old);
  1844. return false;
  1845. }
  1846. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  1847. ObjCMethodDecl *oldMethod) {
  1848. // We don't want to merge unavailable and deprecated attributes
  1849. // except from interface to implementation.
  1850. bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext());
  1851. // Merge the attributes.
  1852. mergeDeclAttributes(newMethod, oldMethod, mergeDeprecation);
  1853. // Merge attributes from the parameters.
  1854. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin();
  1855. for (ObjCMethodDecl::param_iterator
  1856. ni = newMethod->param_begin(), ne = newMethod->param_end();
  1857. ni != ne; ++ni, ++oi)
  1858. mergeParamDeclAttributes(*ni, *oi, Context);
  1859. CheckObjCMethodOverride(newMethod, oldMethod, true);
  1860. }
  1861. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  1862. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  1863. /// emitting diagnostics as appropriate.
  1864. ///
  1865. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  1866. /// to here in AddInitializerToDecl. We can't check them before the initializer
  1867. /// is attached.
  1868. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
  1869. if (New->isInvalidDecl() || Old->isInvalidDecl())
  1870. return;
  1871. QualType MergedT;
  1872. if (getLangOptions().CPlusPlus) {
  1873. AutoType *AT = New->getType()->getContainedAutoType();
  1874. if (AT && !AT->isDeduced()) {
  1875. // We don't know what the new type is until the initializer is attached.
  1876. return;
  1877. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  1878. // These could still be something that needs exception specs checked.
  1879. return MergeVarDeclExceptionSpecs(New, Old);
  1880. }
  1881. // C++ [basic.link]p10:
  1882. // [...] the types specified by all declarations referring to a given
  1883. // object or function shall be identical, except that declarations for an
  1884. // array object can specify array types that differ by the presence or
  1885. // absence of a major array bound (8.3.4).
  1886. else if (Old->getType()->isIncompleteArrayType() &&
  1887. New->getType()->isArrayType()) {
  1888. CanQual<ArrayType> OldArray
  1889. = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
  1890. CanQual<ArrayType> NewArray
  1891. = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
  1892. if (OldArray->getElementType() == NewArray->getElementType())
  1893. MergedT = New->getType();
  1894. } else if (Old->getType()->isArrayType() &&
  1895. New->getType()->isIncompleteArrayType()) {
  1896. CanQual<ArrayType> OldArray
  1897. = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
  1898. CanQual<ArrayType> NewArray
  1899. = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
  1900. if (OldArray->getElementType() == NewArray->getElementType())
  1901. MergedT = Old->getType();
  1902. } else if (New->getType()->isObjCObjectPointerType()
  1903. && Old->getType()->isObjCObjectPointerType()) {
  1904. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  1905. Old->getType());
  1906. }
  1907. } else {
  1908. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  1909. }
  1910. if (MergedT.isNull()) {
  1911. Diag(New->getLocation(), diag::err_redefinition_different_type)
  1912. << New->getDeclName();
  1913. Diag(Old->getLocation(), diag::note_previous_definition);
  1914. return New->setInvalidDecl();
  1915. }
  1916. New->setType(MergedT);
  1917. }
  1918. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  1919. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  1920. /// situation, merging decls or emitting diagnostics as appropriate.
  1921. ///
  1922. /// Tentative definition rules (C99 6.9.2p2) are checked by
  1923. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  1924. /// definitions here, since the initializer hasn't been attached.
  1925. ///
  1926. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  1927. // If the new decl is already invalid, don't do any other checking.
  1928. if (New->isInvalidDecl())
  1929. return;
  1930. // Verify the old decl was also a variable.
  1931. VarDecl *Old = 0;
  1932. if (!Previous.isSingleResult() ||
  1933. !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
  1934. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1935. << New->getDeclName();
  1936. Diag(Previous.getRepresentativeDecl()->getLocation(),
  1937. diag::note_previous_definition);
  1938. return New->setInvalidDecl();
  1939. }
  1940. // C++ [class.mem]p1:
  1941. // A member shall not be declared twice in the member-specification [...]
  1942. //
  1943. // Here, we need only consider static data members.
  1944. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  1945. Diag(New->getLocation(), diag::err_duplicate_member)
  1946. << New->getIdentifier();
  1947. Diag(Old->getLocation(), diag::note_previous_declaration);
  1948. New->setInvalidDecl();
  1949. }
  1950. mergeDeclAttributes(New, Old);
  1951. // Warn if an already-declared variable is made a weak_import in a subsequent
  1952. // declaration
  1953. if (New->getAttr<WeakImportAttr>() &&
  1954. Old->getStorageClass() == SC_None &&
  1955. !Old->getAttr<WeakImportAttr>()) {
  1956. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  1957. Diag(Old->getLocation(), diag::note_previous_definition);
  1958. // Remove weak_import attribute on new declaration.
  1959. New->dropAttr<WeakImportAttr>();
  1960. }
  1961. // Merge the types.
  1962. MergeVarDeclTypes(New, Old);
  1963. if (New->isInvalidDecl())
  1964. return;
  1965. // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
  1966. if (New->getStorageClass() == SC_Static &&
  1967. (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
  1968. Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
  1969. Diag(Old->getLocation(), diag::note_previous_definition);
  1970. return New->setInvalidDecl();
  1971. }
  1972. // C99 6.2.2p4:
  1973. // For an identifier declared with the storage-class specifier
  1974. // extern in a scope in which a prior declaration of that
  1975. // identifier is visible,23) if the prior declaration specifies
  1976. // internal or external linkage, the linkage of the identifier at
  1977. // the later declaration is the same as the linkage specified at
  1978. // the prior declaration. If no prior declaration is visible, or
  1979. // if the prior declaration specifies no linkage, then the
  1980. // identifier has external linkage.
  1981. if (New->hasExternalStorage() && Old->hasLinkage())
  1982. /* Okay */;
  1983. else if (New->getStorageClass() != SC_Static &&
  1984. Old->getStorageClass() == SC_Static) {
  1985. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  1986. Diag(Old->getLocation(), diag::note_previous_definition);
  1987. return New->setInvalidDecl();
  1988. }
  1989. // Check if extern is followed by non-extern and vice-versa.
  1990. if (New->hasExternalStorage() &&
  1991. !Old->hasLinkage() && Old->isLocalVarDecl()) {
  1992. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  1993. Diag(Old->getLocation(), diag::note_previous_definition);
  1994. return New->setInvalidDecl();
  1995. }
  1996. if (Old->hasExternalStorage() &&
  1997. !New->hasLinkage() && New->isLocalVarDecl()) {
  1998. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  1999. Diag(Old->getLocation(), diag::note_previous_definition);
  2000. return New->setInvalidDecl();
  2001. }
  2002. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  2003. // FIXME: The test for external storage here seems wrong? We still
  2004. // need to check for mismatches.
  2005. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  2006. // Don't complain about out-of-line definitions of static members.
  2007. !(Old->getLexicalDeclContext()->isRecord() &&
  2008. !New->getLexicalDeclContext()->isRecord())) {
  2009. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  2010. Diag(Old->getLocation(), diag::note_previous_definition);
  2011. return New->setInvalidDecl();
  2012. }
  2013. if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
  2014. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  2015. Diag(Old->getLocation(), diag::note_previous_definition);
  2016. } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
  2017. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  2018. Diag(Old->getLocation(), diag::note_previous_definition);
  2019. }
  2020. // C++ doesn't have tentative definitions, so go right ahead and check here.
  2021. const VarDecl *Def;
  2022. if (getLangOptions().CPlusPlus &&
  2023. New->isThisDeclarationADefinition() == VarDecl::Definition &&
  2024. (Def = Old->getDefinition())) {
  2025. Diag(New->getLocation(), diag::err_redefinition)
  2026. << New->getDeclName();
  2027. Diag(Def->getLocation(), diag::note_previous_definition);
  2028. New->setInvalidDecl();
  2029. return;
  2030. }
  2031. // c99 6.2.2 P4.
  2032. // For an identifier declared with the storage-class specifier extern in a
  2033. // scope in which a prior declaration of that identifier is visible, if
  2034. // the prior declaration specifies internal or external linkage, the linkage
  2035. // of the identifier at the later declaration is the same as the linkage
  2036. // specified at the prior declaration.
  2037. // FIXME. revisit this code.
  2038. if (New->hasExternalStorage() &&
  2039. Old->getLinkage() == InternalLinkage &&
  2040. New->getDeclContext() == Old->getDeclContext())
  2041. New->setStorageClass(Old->getStorageClass());
  2042. // Keep a chain of previous declarations.
  2043. New->setPreviousDeclaration(Old);
  2044. // Inherit access appropriately.
  2045. New->setAccess(Old->getAccess());
  2046. }
  2047. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  2048. /// no declarator (e.g. "struct foo;") is parsed.
  2049. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  2050. DeclSpec &DS) {
  2051. return ParsedFreeStandingDeclSpec(S, AS, DS,
  2052. MultiTemplateParamsArg(*this, 0, 0));
  2053. }
  2054. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  2055. /// no declarator (e.g. "struct foo;") is parsed. It also accopts template
  2056. /// parameters to cope with template friend declarations.
  2057. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  2058. DeclSpec &DS,
  2059. MultiTemplateParamsArg TemplateParams) {
  2060. Decl *TagD = 0;
  2061. TagDecl *Tag = 0;
  2062. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  2063. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  2064. DS.getTypeSpecType() == DeclSpec::TST_union ||
  2065. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  2066. TagD = DS.getRepAsDecl();
  2067. if (!TagD) // We probably had an error
  2068. return 0;
  2069. // Note that the above type specs guarantee that the
  2070. // type rep is a Decl, whereas in many of the others
  2071. // it's a Type.
  2072. if (isa<TagDecl>(TagD))
  2073. Tag = cast<TagDecl>(TagD);
  2074. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  2075. Tag = CTD->getTemplatedDecl();
  2076. }
  2077. if (Tag)
  2078. Tag->setFreeStanding();
  2079. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  2080. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  2081. // or incomplete types shall not be restrict-qualified."
  2082. if (TypeQuals & DeclSpec::TQ_restrict)
  2083. Diag(DS.getRestrictSpecLoc(),
  2084. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  2085. << DS.getSourceRange();
  2086. }
  2087. if (DS.isConstexprSpecified()) {
  2088. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  2089. // and definitions of functions and variables.
  2090. if (Tag)
  2091. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  2092. << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
  2093. DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
  2094. DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3);
  2095. else
  2096. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  2097. // Don't emit warnings after this error.
  2098. return TagD;
  2099. }
  2100. if (DS.isFriendSpecified()) {
  2101. // If we're dealing with a decl but not a TagDecl, assume that
  2102. // whatever routines created it handled the friendship aspect.
  2103. if (TagD && !Tag)
  2104. return 0;
  2105. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  2106. }
  2107. // Track whether we warned about the fact that there aren't any
  2108. // declarators.
  2109. bool emittedWarning = false;
  2110. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  2111. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  2112. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  2113. if (getLangOptions().CPlusPlus ||
  2114. Record->getDeclContext()->isRecord())
  2115. return BuildAnonymousStructOrUnion(S, DS, AS, Record);
  2116. Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
  2117. << DS.getSourceRange();
  2118. emittedWarning = true;
  2119. }
  2120. }
  2121. // Check for Microsoft C extension: anonymous struct.
  2122. if (getLangOptions().MicrosoftExt && !getLangOptions().CPlusPlus &&
  2123. CurContext->isRecord() &&
  2124. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  2125. // Handle 2 kinds of anonymous struct:
  2126. // struct STRUCT;
  2127. // and
  2128. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  2129. RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
  2130. if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
  2131. (DS.getTypeSpecType() == DeclSpec::TST_typename &&
  2132. DS.getRepAsType().get()->isStructureType())) {
  2133. Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct)
  2134. << DS.getSourceRange();
  2135. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  2136. }
  2137. }
  2138. if (getLangOptions().CPlusPlus &&
  2139. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  2140. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  2141. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  2142. !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
  2143. Diag(Enum->getLocation(), diag::ext_no_declarators)
  2144. << DS.getSourceRange();
  2145. emittedWarning = true;
  2146. }
  2147. // Skip all the checks below if we have a type error.
  2148. if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
  2149. if (!DS.isMissingDeclaratorOk()) {
  2150. // Warn about typedefs of enums without names, since this is an
  2151. // extension in both Microsoft and GNU.
  2152. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
  2153. Tag && isa<EnumDecl>(Tag)) {
  2154. Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
  2155. << DS.getSourceRange();
  2156. return Tag;
  2157. }
  2158. Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
  2159. << DS.getSourceRange();
  2160. emittedWarning = true;
  2161. }
  2162. // We're going to complain about a bunch of spurious specifiers;
  2163. // only do this if we're declaring a tag, because otherwise we
  2164. // should be getting diag::ext_no_declarators.
  2165. if (emittedWarning || (TagD && TagD->isInvalidDecl()))
  2166. return TagD;
  2167. // Note that a linkage-specification sets a storage class, but
  2168. // 'extern "C" struct foo;' is actually valid and not theoretically
  2169. // useless.
  2170. if (DeclSpec::SCS scs = DS.getStorageClassSpec())
  2171. if (!DS.isExternInLinkageSpec())
  2172. Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
  2173. << DeclSpec::getSpecifierName(scs);
  2174. if (DS.isThreadSpecified())
  2175. Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
  2176. if (DS.getTypeQualifiers()) {
  2177. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  2178. Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
  2179. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  2180. Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
  2181. // Restrict is covered above.
  2182. }
  2183. if (DS.isInlineSpecified())
  2184. Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
  2185. if (DS.isVirtualSpecified())
  2186. Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
  2187. if (DS.isExplicitSpecified())
  2188. Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
  2189. if (DS.isModulePrivateSpecified() &&
  2190. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  2191. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  2192. << Tag->getTagKind()
  2193. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  2194. // Warn about ignored type attributes, for example:
  2195. // __attribute__((aligned)) struct A;
  2196. // Attributes should be placed after tag to apply to type declaration.
  2197. if (!DS.getAttributes().empty()) {
  2198. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  2199. if (TypeSpecType == DeclSpec::TST_class ||
  2200. TypeSpecType == DeclSpec::TST_struct ||
  2201. TypeSpecType == DeclSpec::TST_union ||
  2202. TypeSpecType == DeclSpec::TST_enum) {
  2203. AttributeList* attrs = DS.getAttributes().getList();
  2204. while (attrs) {
  2205. Diag(attrs->getScopeLoc(),
  2206. diag::warn_declspec_attribute_ignored)
  2207. << attrs->getName()
  2208. << (TypeSpecType == DeclSpec::TST_class ? 0 :
  2209. TypeSpecType == DeclSpec::TST_struct ? 1 :
  2210. TypeSpecType == DeclSpec::TST_union ? 2 : 3);
  2211. attrs = attrs->getNext();
  2212. }
  2213. }
  2214. }
  2215. return TagD;
  2216. }
  2217. /// We are trying to inject an anonymous member into the given scope;
  2218. /// check if there's an existing declaration that can't be overloaded.
  2219. ///
  2220. /// \return true if this is a forbidden redeclaration
  2221. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  2222. Scope *S,
  2223. DeclContext *Owner,
  2224. DeclarationName Name,
  2225. SourceLocation NameLoc,
  2226. unsigned diagnostic) {
  2227. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  2228. Sema::ForRedeclaration);
  2229. if (!SemaRef.LookupName(R, S)) return false;
  2230. if (R.getAsSingle<TagDecl>())
  2231. return false;
  2232. // Pick a representative declaration.
  2233. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  2234. assert(PrevDecl && "Expected a non-null Decl");
  2235. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  2236. return false;
  2237. SemaRef.Diag(NameLoc, diagnostic) << Name;
  2238. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  2239. return true;
  2240. }
  2241. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  2242. /// anonymous struct or union AnonRecord into the owning context Owner
  2243. /// and scope S. This routine will be invoked just after we realize
  2244. /// that an unnamed union or struct is actually an anonymous union or
  2245. /// struct, e.g.,
  2246. ///
  2247. /// @code
  2248. /// union {
  2249. /// int i;
  2250. /// float f;
  2251. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  2252. /// // f into the surrounding scope.x
  2253. /// @endcode
  2254. ///
  2255. /// This routine is recursive, injecting the names of nested anonymous
  2256. /// structs/unions into the owning context and scope as well.
  2257. static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
  2258. DeclContext *Owner,
  2259. RecordDecl *AnonRecord,
  2260. AccessSpecifier AS,
  2261. SmallVector<NamedDecl*, 2> &Chaining,
  2262. bool MSAnonStruct) {
  2263. unsigned diagKind
  2264. = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
  2265. : diag::err_anonymous_struct_member_redecl;
  2266. bool Invalid = false;
  2267. // Look every FieldDecl and IndirectFieldDecl with a name.
  2268. for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
  2269. DEnd = AnonRecord->decls_end();
  2270. D != DEnd; ++D) {
  2271. if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
  2272. cast<NamedDecl>(*D)->getDeclName()) {
  2273. ValueDecl *VD = cast<ValueDecl>(*D);
  2274. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  2275. VD->getLocation(), diagKind)) {
  2276. // C++ [class.union]p2:
  2277. // The names of the members of an anonymous union shall be
  2278. // distinct from the names of any other entity in the
  2279. // scope in which the anonymous union is declared.
  2280. Invalid = true;
  2281. } else {
  2282. // C++ [class.union]p2:
  2283. // For the purpose of name lookup, after the anonymous union
  2284. // definition, the members of the anonymous union are
  2285. // considered to have been defined in the scope in which the
  2286. // anonymous union is declared.
  2287. unsigned OldChainingSize = Chaining.size();
  2288. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  2289. for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
  2290. PE = IF->chain_end(); PI != PE; ++PI)
  2291. Chaining.push_back(*PI);
  2292. else
  2293. Chaining.push_back(VD);
  2294. assert(Chaining.size() >= 2);
  2295. NamedDecl **NamedChain =
  2296. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  2297. for (unsigned i = 0; i < Chaining.size(); i++)
  2298. NamedChain[i] = Chaining[i];
  2299. IndirectFieldDecl* IndirectField =
  2300. IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
  2301. VD->getIdentifier(), VD->getType(),
  2302. NamedChain, Chaining.size());
  2303. IndirectField->setAccess(AS);
  2304. IndirectField->setImplicit();
  2305. SemaRef.PushOnScopeChains(IndirectField, S);
  2306. // That includes picking up the appropriate access specifier.
  2307. if (AS != AS_none) IndirectField->setAccess(AS);
  2308. Chaining.resize(OldChainingSize);
  2309. }
  2310. }
  2311. }
  2312. return Invalid;
  2313. }
  2314. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  2315. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  2316. /// illegal input values are mapped to SC_None.
  2317. static StorageClass
  2318. StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
  2319. switch (StorageClassSpec) {
  2320. case DeclSpec::SCS_unspecified: return SC_None;
  2321. case DeclSpec::SCS_extern: return SC_Extern;
  2322. case DeclSpec::SCS_static: return SC_Static;
  2323. case DeclSpec::SCS_auto: return SC_Auto;
  2324. case DeclSpec::SCS_register: return SC_Register;
  2325. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  2326. // Illegal SCSs map to None: error reporting is up to the caller.
  2327. case DeclSpec::SCS_mutable: // Fall through.
  2328. case DeclSpec::SCS_typedef: return SC_None;
  2329. }
  2330. llvm_unreachable("unknown storage class specifier");
  2331. }
  2332. /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
  2333. /// a StorageClass. Any error reporting is up to the caller:
  2334. /// illegal input values are mapped to SC_None.
  2335. static StorageClass
  2336. StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
  2337. switch (StorageClassSpec) {
  2338. case DeclSpec::SCS_unspecified: return SC_None;
  2339. case DeclSpec::SCS_extern: return SC_Extern;
  2340. case DeclSpec::SCS_static: return SC_Static;
  2341. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  2342. // Illegal SCSs map to None: error reporting is up to the caller.
  2343. case DeclSpec::SCS_auto: // Fall through.
  2344. case DeclSpec::SCS_mutable: // Fall through.
  2345. case DeclSpec::SCS_register: // Fall through.
  2346. case DeclSpec::SCS_typedef: return SC_None;
  2347. }
  2348. llvm_unreachable("unknown storage class specifier");
  2349. }
  2350. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  2351. /// anonymous structure or union. Anonymous unions are a C++ feature
  2352. /// (C++ [class.union]) and a C11 feature; anonymous structures
  2353. /// are a C11 feature and GNU C++ extension.
  2354. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  2355. AccessSpecifier AS,
  2356. RecordDecl *Record) {
  2357. DeclContext *Owner = Record->getDeclContext();
  2358. // Diagnose whether this anonymous struct/union is an extension.
  2359. if (Record->isUnion() && !getLangOptions().CPlusPlus && !getLangOptions().C11)
  2360. Diag(Record->getLocation(), diag::ext_anonymous_union);
  2361. else if (!Record->isUnion() && getLangOptions().CPlusPlus)
  2362. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  2363. else if (!Record->isUnion() && !getLangOptions().C11)
  2364. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  2365. // C and C++ require different kinds of checks for anonymous
  2366. // structs/unions.
  2367. bool Invalid = false;
  2368. if (getLangOptions().CPlusPlus) {
  2369. const char* PrevSpec = 0;
  2370. unsigned DiagID;
  2371. if (Record->isUnion()) {
  2372. // C++ [class.union]p6:
  2373. // Anonymous unions declared in a named namespace or in the
  2374. // global namespace shall be declared static.
  2375. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  2376. (isa<TranslationUnitDecl>(Owner) ||
  2377. (isa<NamespaceDecl>(Owner) &&
  2378. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  2379. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  2380. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  2381. // Recover by adding 'static'.
  2382. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  2383. PrevSpec, DiagID);
  2384. }
  2385. // C++ [class.union]p6:
  2386. // A storage class is not allowed in a declaration of an
  2387. // anonymous union in a class scope.
  2388. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  2389. isa<RecordDecl>(Owner)) {
  2390. Diag(DS.getStorageClassSpecLoc(),
  2391. diag::err_anonymous_union_with_storage_spec)
  2392. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  2393. // Recover by removing the storage specifier.
  2394. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  2395. SourceLocation(),
  2396. PrevSpec, DiagID);
  2397. }
  2398. }
  2399. // Ignore const/volatile/restrict qualifiers.
  2400. if (DS.getTypeQualifiers()) {
  2401. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  2402. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  2403. << Record->isUnion() << 0
  2404. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  2405. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  2406. Diag(DS.getVolatileSpecLoc(),
  2407. diag::ext_anonymous_struct_union_qualified)
  2408. << Record->isUnion() << 1
  2409. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  2410. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  2411. Diag(DS.getRestrictSpecLoc(),
  2412. diag::ext_anonymous_struct_union_qualified)
  2413. << Record->isUnion() << 2
  2414. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  2415. DS.ClearTypeQualifiers();
  2416. }
  2417. // C++ [class.union]p2:
  2418. // The member-specification of an anonymous union shall only
  2419. // define non-static data members. [Note: nested types and
  2420. // functions cannot be declared within an anonymous union. ]
  2421. for (DeclContext::decl_iterator Mem = Record->decls_begin(),
  2422. MemEnd = Record->decls_end();
  2423. Mem != MemEnd; ++Mem) {
  2424. if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
  2425. // C++ [class.union]p3:
  2426. // An anonymous union shall not have private or protected
  2427. // members (clause 11).
  2428. assert(FD->getAccess() != AS_none);
  2429. if (FD->getAccess() != AS_public) {
  2430. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  2431. << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
  2432. Invalid = true;
  2433. }
  2434. // C++ [class.union]p1
  2435. // An object of a class with a non-trivial constructor, a non-trivial
  2436. // copy constructor, a non-trivial destructor, or a non-trivial copy
  2437. // assignment operator cannot be a member of a union, nor can an
  2438. // array of such objects.
  2439. if (CheckNontrivialField(FD))
  2440. Invalid = true;
  2441. } else if ((*Mem)->isImplicit()) {
  2442. // Any implicit members are fine.
  2443. } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
  2444. // This is a type that showed up in an
  2445. // elaborated-type-specifier inside the anonymous struct or
  2446. // union, but which actually declares a type outside of the
  2447. // anonymous struct or union. It's okay.
  2448. } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
  2449. if (!MemRecord->isAnonymousStructOrUnion() &&
  2450. MemRecord->getDeclName()) {
  2451. // Visual C++ allows type definition in anonymous struct or union.
  2452. if (getLangOptions().MicrosoftExt)
  2453. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  2454. << (int)Record->isUnion();
  2455. else {
  2456. // This is a nested type declaration.
  2457. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  2458. << (int)Record->isUnion();
  2459. Invalid = true;
  2460. }
  2461. }
  2462. } else if (isa<AccessSpecDecl>(*Mem)) {
  2463. // Any access specifier is fine.
  2464. } else {
  2465. // We have something that isn't a non-static data
  2466. // member. Complain about it.
  2467. unsigned DK = diag::err_anonymous_record_bad_member;
  2468. if (isa<TypeDecl>(*Mem))
  2469. DK = diag::err_anonymous_record_with_type;
  2470. else if (isa<FunctionDecl>(*Mem))
  2471. DK = diag::err_anonymous_record_with_function;
  2472. else if (isa<VarDecl>(*Mem))
  2473. DK = diag::err_anonymous_record_with_static;
  2474. // Visual C++ allows type definition in anonymous struct or union.
  2475. if (getLangOptions().MicrosoftExt &&
  2476. DK == diag::err_anonymous_record_with_type)
  2477. Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
  2478. << (int)Record->isUnion();
  2479. else {
  2480. Diag((*Mem)->getLocation(), DK)
  2481. << (int)Record->isUnion();
  2482. Invalid = true;
  2483. }
  2484. }
  2485. }
  2486. }
  2487. if (!Record->isUnion() && !Owner->isRecord()) {
  2488. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  2489. << (int)getLangOptions().CPlusPlus;
  2490. Invalid = true;
  2491. }
  2492. // Mock up a declarator.
  2493. Declarator Dc(DS, Declarator::MemberContext);
  2494. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  2495. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  2496. // Create a declaration for this anonymous struct/union.
  2497. NamedDecl *Anon = 0;
  2498. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  2499. Anon = FieldDecl::Create(Context, OwningClass,
  2500. DS.getSourceRange().getBegin(),
  2501. Record->getLocation(),
  2502. /*IdentifierInfo=*/0,
  2503. Context.getTypeDeclType(Record),
  2504. TInfo,
  2505. /*BitWidth=*/0, /*Mutable=*/false,
  2506. /*HasInit=*/false);
  2507. Anon->setAccess(AS);
  2508. if (getLangOptions().CPlusPlus)
  2509. FieldCollector->Add(cast<FieldDecl>(Anon));
  2510. } else {
  2511. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  2512. assert(SCSpec != DeclSpec::SCS_typedef &&
  2513. "Parser allowed 'typedef' as storage class VarDecl.");
  2514. VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
  2515. if (SCSpec == DeclSpec::SCS_mutable) {
  2516. // mutable can only appear on non-static class members, so it's always
  2517. // an error here
  2518. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  2519. Invalid = true;
  2520. SC = SC_None;
  2521. }
  2522. SCSpec = DS.getStorageClassSpecAsWritten();
  2523. VarDecl::StorageClass SCAsWritten
  2524. = StorageClassSpecToVarDeclStorageClass(SCSpec);
  2525. Anon = VarDecl::Create(Context, Owner,
  2526. DS.getSourceRange().getBegin(),
  2527. Record->getLocation(), /*IdentifierInfo=*/0,
  2528. Context.getTypeDeclType(Record),
  2529. TInfo, SC, SCAsWritten);
  2530. // Default-initialize the implicit variable. This initialization will be
  2531. // trivial in almost all cases, except if a union member has an in-class
  2532. // initializer:
  2533. // union { int n = 0; };
  2534. ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
  2535. }
  2536. Anon->setImplicit();
  2537. // Add the anonymous struct/union object to the current
  2538. // context. We'll be referencing this object when we refer to one of
  2539. // its members.
  2540. Owner->addDecl(Anon);
  2541. // Inject the members of the anonymous struct/union into the owning
  2542. // context and into the identifier resolver chain for name lookup
  2543. // purposes.
  2544. SmallVector<NamedDecl*, 2> Chain;
  2545. Chain.push_back(Anon);
  2546. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
  2547. Chain, false))
  2548. Invalid = true;
  2549. // Mark this as an anonymous struct/union type. Note that we do not
  2550. // do this until after we have already checked and injected the
  2551. // members of this anonymous struct/union type, because otherwise
  2552. // the members could be injected twice: once by DeclContext when it
  2553. // builds its lookup table, and once by
  2554. // InjectAnonymousStructOrUnionMembers.
  2555. Record->setAnonymousStructOrUnion(true);
  2556. if (Invalid)
  2557. Anon->setInvalidDecl();
  2558. return Anon;
  2559. }
  2560. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  2561. /// Microsoft C anonymous structure.
  2562. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  2563. /// Example:
  2564. ///
  2565. /// struct A { int a; };
  2566. /// struct B { struct A; int b; };
  2567. ///
  2568. /// void foo() {
  2569. /// B var;
  2570. /// var.a = 3;
  2571. /// }
  2572. ///
  2573. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  2574. RecordDecl *Record) {
  2575. // If there is no Record, get the record via the typedef.
  2576. if (!Record)
  2577. Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
  2578. // Mock up a declarator.
  2579. Declarator Dc(DS, Declarator::TypeNameContext);
  2580. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  2581. assert(TInfo && "couldn't build declarator info for anonymous struct");
  2582. // Create a declaration for this anonymous struct.
  2583. NamedDecl* Anon = FieldDecl::Create(Context,
  2584. cast<RecordDecl>(CurContext),
  2585. DS.getSourceRange().getBegin(),
  2586. DS.getSourceRange().getBegin(),
  2587. /*IdentifierInfo=*/0,
  2588. Context.getTypeDeclType(Record),
  2589. TInfo,
  2590. /*BitWidth=*/0, /*Mutable=*/false,
  2591. /*HasInit=*/false);
  2592. Anon->setImplicit();
  2593. // Add the anonymous struct object to the current context.
  2594. CurContext->addDecl(Anon);
  2595. // Inject the members of the anonymous struct into the current
  2596. // context and into the identifier resolver chain for name lookup
  2597. // purposes.
  2598. SmallVector<NamedDecl*, 2> Chain;
  2599. Chain.push_back(Anon);
  2600. RecordDecl *RecordDef = Record->getDefinition();
  2601. if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
  2602. RecordDef, AS_none,
  2603. Chain, true))
  2604. Anon->setInvalidDecl();
  2605. return Anon;
  2606. }
  2607. /// GetNameForDeclarator - Determine the full declaration name for the
  2608. /// given Declarator.
  2609. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  2610. return GetNameFromUnqualifiedId(D.getName());
  2611. }
  2612. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  2613. DeclarationNameInfo
  2614. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  2615. DeclarationNameInfo NameInfo;
  2616. NameInfo.setLoc(Name.StartLocation);
  2617. switch (Name.getKind()) {
  2618. case UnqualifiedId::IK_ImplicitSelfParam:
  2619. case UnqualifiedId::IK_Identifier:
  2620. NameInfo.setName(Name.Identifier);
  2621. NameInfo.setLoc(Name.StartLocation);
  2622. return NameInfo;
  2623. case UnqualifiedId::IK_OperatorFunctionId:
  2624. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  2625. Name.OperatorFunctionId.Operator));
  2626. NameInfo.setLoc(Name.StartLocation);
  2627. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  2628. = Name.OperatorFunctionId.SymbolLocations[0];
  2629. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  2630. = Name.EndLocation.getRawEncoding();
  2631. return NameInfo;
  2632. case UnqualifiedId::IK_LiteralOperatorId:
  2633. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  2634. Name.Identifier));
  2635. NameInfo.setLoc(Name.StartLocation);
  2636. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  2637. return NameInfo;
  2638. case UnqualifiedId::IK_ConversionFunctionId: {
  2639. TypeSourceInfo *TInfo;
  2640. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  2641. if (Ty.isNull())
  2642. return DeclarationNameInfo();
  2643. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  2644. Context.getCanonicalType(Ty)));
  2645. NameInfo.setLoc(Name.StartLocation);
  2646. NameInfo.setNamedTypeInfo(TInfo);
  2647. return NameInfo;
  2648. }
  2649. case UnqualifiedId::IK_ConstructorName: {
  2650. TypeSourceInfo *TInfo;
  2651. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  2652. if (Ty.isNull())
  2653. return DeclarationNameInfo();
  2654. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  2655. Context.getCanonicalType(Ty)));
  2656. NameInfo.setLoc(Name.StartLocation);
  2657. NameInfo.setNamedTypeInfo(TInfo);
  2658. return NameInfo;
  2659. }
  2660. case UnqualifiedId::IK_ConstructorTemplateId: {
  2661. // In well-formed code, we can only have a constructor
  2662. // template-id that refers to the current context, so go there
  2663. // to find the actual type being constructed.
  2664. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  2665. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  2666. return DeclarationNameInfo();
  2667. // Determine the type of the class being constructed.
  2668. QualType CurClassType = Context.getTypeDeclType(CurClass);
  2669. // FIXME: Check two things: that the template-id names the same type as
  2670. // CurClassType, and that the template-id does not occur when the name
  2671. // was qualified.
  2672. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  2673. Context.getCanonicalType(CurClassType)));
  2674. NameInfo.setLoc(Name.StartLocation);
  2675. // FIXME: should we retrieve TypeSourceInfo?
  2676. NameInfo.setNamedTypeInfo(0);
  2677. return NameInfo;
  2678. }
  2679. case UnqualifiedId::IK_DestructorName: {
  2680. TypeSourceInfo *TInfo;
  2681. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  2682. if (Ty.isNull())
  2683. return DeclarationNameInfo();
  2684. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  2685. Context.getCanonicalType(Ty)));
  2686. NameInfo.setLoc(Name.StartLocation);
  2687. NameInfo.setNamedTypeInfo(TInfo);
  2688. return NameInfo;
  2689. }
  2690. case UnqualifiedId::IK_TemplateId: {
  2691. TemplateName TName = Name.TemplateId->Template.get();
  2692. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  2693. return Context.getNameForTemplate(TName, TNameLoc);
  2694. }
  2695. } // switch (Name.getKind())
  2696. llvm_unreachable("Unknown name kind");
  2697. }
  2698. static QualType getCoreType(QualType Ty) {
  2699. do {
  2700. if (Ty->isPointerType() || Ty->isReferenceType())
  2701. Ty = Ty->getPointeeType();
  2702. else if (Ty->isArrayType())
  2703. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  2704. else
  2705. return Ty.withoutLocalFastQualifiers();
  2706. } while (true);
  2707. }
  2708. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  2709. /// and Definition have "nearly" matching parameters. This heuristic is
  2710. /// used to improve diagnostics in the case where an out-of-line function
  2711. /// definition doesn't match any declaration within the class or namespace.
  2712. /// Also sets Params to the list of indices to the parameters that differ
  2713. /// between the declaration and the definition. If hasSimilarParameters
  2714. /// returns true and Params is empty, then all of the parameters match.
  2715. static bool hasSimilarParameters(ASTContext &Context,
  2716. FunctionDecl *Declaration,
  2717. FunctionDecl *Definition,
  2718. llvm::SmallVectorImpl<unsigned> &Params) {
  2719. Params.clear();
  2720. if (Declaration->param_size() != Definition->param_size())
  2721. return false;
  2722. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  2723. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  2724. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  2725. // The parameter types are identical
  2726. if (Context.hasSameType(DefParamTy, DeclParamTy))
  2727. continue;
  2728. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  2729. QualType DefParamBaseTy = getCoreType(DefParamTy);
  2730. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  2731. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  2732. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  2733. (DeclTyName && DeclTyName == DefTyName))
  2734. Params.push_back(Idx);
  2735. else // The two parameters aren't even close
  2736. return false;
  2737. }
  2738. return true;
  2739. }
  2740. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  2741. /// declarator needs to be rebuilt in the current instantiation.
  2742. /// Any bits of declarator which appear before the name are valid for
  2743. /// consideration here. That's specifically the type in the decl spec
  2744. /// and the base type in any member-pointer chunks.
  2745. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  2746. DeclarationName Name) {
  2747. // The types we specifically need to rebuild are:
  2748. // - typenames, typeofs, and decltypes
  2749. // - types which will become injected class names
  2750. // Of course, we also need to rebuild any type referencing such a
  2751. // type. It's safest to just say "dependent", but we call out a
  2752. // few cases here.
  2753. DeclSpec &DS = D.getMutableDeclSpec();
  2754. switch (DS.getTypeSpecType()) {
  2755. case DeclSpec::TST_typename:
  2756. case DeclSpec::TST_typeofType:
  2757. case DeclSpec::TST_decltype:
  2758. case DeclSpec::TST_underlyingType:
  2759. case DeclSpec::TST_atomic: {
  2760. // Grab the type from the parser.
  2761. TypeSourceInfo *TSI = 0;
  2762. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  2763. if (T.isNull() || !T->isDependentType()) break;
  2764. // Make sure there's a type source info. This isn't really much
  2765. // of a waste; most dependent types should have type source info
  2766. // attached already.
  2767. if (!TSI)
  2768. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  2769. // Rebuild the type in the current instantiation.
  2770. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  2771. if (!TSI) return true;
  2772. // Store the new type back in the decl spec.
  2773. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  2774. DS.UpdateTypeRep(LocType);
  2775. break;
  2776. }
  2777. case DeclSpec::TST_typeofExpr: {
  2778. Expr *E = DS.getRepAsExpr();
  2779. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  2780. if (Result.isInvalid()) return true;
  2781. DS.UpdateExprRep(Result.get());
  2782. break;
  2783. }
  2784. default:
  2785. // Nothing to do for these decl specs.
  2786. break;
  2787. }
  2788. // It doesn't matter what order we do this in.
  2789. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  2790. DeclaratorChunk &Chunk = D.getTypeObject(I);
  2791. // The only type information in the declarator which can come
  2792. // before the declaration name is the base type of a member
  2793. // pointer.
  2794. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  2795. continue;
  2796. // Rebuild the scope specifier in-place.
  2797. CXXScopeSpec &SS = Chunk.Mem.Scope();
  2798. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  2799. return true;
  2800. }
  2801. return false;
  2802. }
  2803. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  2804. D.setFunctionDefinitionKind(FDK_Declaration);
  2805. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this));
  2806. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  2807. Dcl->getDeclContext()->isFileContext())
  2808. Dcl->setTopLevelDeclInObjCContainer();
  2809. return Dcl;
  2810. }
  2811. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  2812. /// If T is the name of a class, then each of the following shall have a
  2813. /// name different from T:
  2814. /// - every static data member of class T;
  2815. /// - every member function of class T
  2816. /// - every member of class T that is itself a type;
  2817. /// \returns true if the declaration name violates these rules.
  2818. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  2819. DeclarationNameInfo NameInfo) {
  2820. DeclarationName Name = NameInfo.getName();
  2821. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  2822. if (Record->getIdentifier() && Record->getDeclName() == Name) {
  2823. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  2824. return true;
  2825. }
  2826. return false;
  2827. }
  2828. Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  2829. MultiTemplateParamsArg TemplateParamLists) {
  2830. // TODO: consider using NameInfo for diagnostic.
  2831. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  2832. DeclarationName Name = NameInfo.getName();
  2833. // All of these full declarators require an identifier. If it doesn't have
  2834. // one, the ParsedFreeStandingDeclSpec action should be used.
  2835. if (!Name) {
  2836. if (!D.isInvalidType()) // Reject this if we think it is valid.
  2837. Diag(D.getDeclSpec().getSourceRange().getBegin(),
  2838. diag::err_declarator_need_ident)
  2839. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  2840. return 0;
  2841. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  2842. return 0;
  2843. // The scope passed in may not be a decl scope. Zip up the scope tree until
  2844. // we find one that is.
  2845. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  2846. (S->getFlags() & Scope::TemplateParamScope) != 0)
  2847. S = S->getParent();
  2848. DeclContext *DC = CurContext;
  2849. if (D.getCXXScopeSpec().isInvalid())
  2850. D.setInvalidType();
  2851. else if (D.getCXXScopeSpec().isSet()) {
  2852. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  2853. UPPC_DeclarationQualifier))
  2854. return 0;
  2855. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  2856. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  2857. if (!DC) {
  2858. // If we could not compute the declaration context, it's because the
  2859. // declaration context is dependent but does not refer to a class,
  2860. // class template, or class template partial specialization. Complain
  2861. // and return early, to avoid the coming semantic disaster.
  2862. Diag(D.getIdentifierLoc(),
  2863. diag::err_template_qualified_declarator_no_match)
  2864. << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
  2865. << D.getCXXScopeSpec().getRange();
  2866. return 0;
  2867. }
  2868. bool IsDependentContext = DC->isDependentContext();
  2869. if (!IsDependentContext &&
  2870. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  2871. return 0;
  2872. if (isa<CXXRecordDecl>(DC)) {
  2873. if (!cast<CXXRecordDecl>(DC)->hasDefinition()) {
  2874. Diag(D.getIdentifierLoc(),
  2875. diag::err_member_def_undefined_record)
  2876. << Name << DC << D.getCXXScopeSpec().getRange();
  2877. D.setInvalidType();
  2878. } else if (isa<CXXRecordDecl>(CurContext) &&
  2879. !D.getDeclSpec().isFriendSpecified()) {
  2880. // The user provided a superfluous scope specifier inside a class
  2881. // definition:
  2882. //
  2883. // class X {
  2884. // void X::f();
  2885. // };
  2886. if (CurContext->Equals(DC)) {
  2887. Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
  2888. << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange());
  2889. } else {
  2890. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  2891. << Name << D.getCXXScopeSpec().getRange();
  2892. // C++ constructors and destructors with incorrect scopes can break
  2893. // our AST invariants by having the wrong underlying types. If
  2894. // that's the case, then drop this declaration entirely.
  2895. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  2896. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  2897. !Context.hasSameType(Name.getCXXNameType(),
  2898. Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))))
  2899. return 0;
  2900. }
  2901. // Pretend that this qualifier was not here.
  2902. D.getCXXScopeSpec().clear();
  2903. }
  2904. }
  2905. // Check whether we need to rebuild the type of the given
  2906. // declaration in the current instantiation.
  2907. if (EnteringContext && IsDependentContext &&
  2908. TemplateParamLists.size() != 0) {
  2909. ContextRAII SavedContext(*this, DC);
  2910. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  2911. D.setInvalidType();
  2912. }
  2913. }
  2914. if (DiagnoseClassNameShadow(DC, NameInfo))
  2915. // If this is a typedef, we'll end up spewing multiple diagnostics.
  2916. // Just return early; it's safer.
  2917. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  2918. return 0;
  2919. NamedDecl *New;
  2920. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  2921. QualType R = TInfo->getType();
  2922. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  2923. UPPC_DeclarationType))
  2924. D.setInvalidType();
  2925. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  2926. ForRedeclaration);
  2927. // See if this is a redefinition of a variable in the same scope.
  2928. if (!D.getCXXScopeSpec().isSet()) {
  2929. bool IsLinkageLookup = false;
  2930. // If the declaration we're planning to build will be a function
  2931. // or object with linkage, then look for another declaration with
  2932. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  2933. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  2934. /* Do nothing*/;
  2935. else if (R->isFunctionType()) {
  2936. if (CurContext->isFunctionOrMethod() ||
  2937. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  2938. IsLinkageLookup = true;
  2939. } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
  2940. IsLinkageLookup = true;
  2941. else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  2942. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  2943. IsLinkageLookup = true;
  2944. if (IsLinkageLookup)
  2945. Previous.clear(LookupRedeclarationWithLinkage);
  2946. LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
  2947. } else { // Something like "int foo::x;"
  2948. LookupQualifiedName(Previous, DC);
  2949. // Don't consider using declarations as previous declarations for
  2950. // out-of-line members.
  2951. RemoveUsingDecls(Previous);
  2952. // C++ 7.3.1.2p2:
  2953. // Members (including explicit specializations of templates) of a named
  2954. // namespace can also be defined outside that namespace by explicit
  2955. // qualification of the name being defined, provided that the entity being
  2956. // defined was already declared in the namespace and the definition appears
  2957. // after the point of declaration in a namespace that encloses the
  2958. // declarations namespace.
  2959. //
  2960. // Note that we only check the context at this point. We don't yet
  2961. // have enough information to make sure that PrevDecl is actually
  2962. // the declaration we want to match. For example, given:
  2963. //
  2964. // class X {
  2965. // void f();
  2966. // void f(float);
  2967. // };
  2968. //
  2969. // void X::f(int) { } // ill-formed
  2970. //
  2971. // In this case, PrevDecl will point to the overload set
  2972. // containing the two f's declared in X, but neither of them
  2973. // matches.
  2974. // First check whether we named the global scope.
  2975. if (isa<TranslationUnitDecl>(DC)) {
  2976. Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
  2977. << Name << D.getCXXScopeSpec().getRange();
  2978. } else {
  2979. DeclContext *Cur = CurContext;
  2980. while (isa<LinkageSpecDecl>(Cur))
  2981. Cur = Cur->getParent();
  2982. if (!Cur->Encloses(DC)) {
  2983. // The qualifying scope doesn't enclose the original declaration.
  2984. // Emit diagnostic based on current scope.
  2985. SourceLocation L = D.getIdentifierLoc();
  2986. SourceRange R = D.getCXXScopeSpec().getRange();
  2987. if (isa<FunctionDecl>(Cur))
  2988. Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
  2989. else
  2990. Diag(L, diag::err_invalid_declarator_scope)
  2991. << Name << cast<NamedDecl>(DC) << R;
  2992. D.setInvalidType();
  2993. }
  2994. // C++11 8.3p1:
  2995. // ... "The nested-name-specifier of the qualified declarator-id shall
  2996. // not begin with a decltype-specifer"
  2997. NestedNameSpecifierLoc SpecLoc =
  2998. D.getCXXScopeSpec().getWithLocInContext(Context);
  2999. assert(SpecLoc && "A non-empty CXXScopeSpec should have a non-empty "
  3000. "NestedNameSpecifierLoc");
  3001. while (SpecLoc.getPrefix())
  3002. SpecLoc = SpecLoc.getPrefix();
  3003. if (dyn_cast_or_null<DecltypeType>(
  3004. SpecLoc.getNestedNameSpecifier()->getAsType()))
  3005. Diag(SpecLoc.getBeginLoc(), diag::err_decltype_in_declarator)
  3006. << SpecLoc.getTypeLoc().getSourceRange();
  3007. }
  3008. }
  3009. if (Previous.isSingleResult() &&
  3010. Previous.getFoundDecl()->isTemplateParameter()) {
  3011. // Maybe we will complain about the shadowed template parameter.
  3012. if (!D.isInvalidType())
  3013. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  3014. Previous.getFoundDecl());
  3015. // Just pretend that we didn't see the previous declaration.
  3016. Previous.clear();
  3017. }
  3018. // In C++, the previous declaration we find might be a tag type
  3019. // (class or enum). In this case, the new declaration will hide the
  3020. // tag type. Note that this does does not apply if we're declaring a
  3021. // typedef (C++ [dcl.typedef]p4).
  3022. if (Previous.isSingleTagDecl() &&
  3023. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
  3024. Previous.clear();
  3025. bool AddToScope = true;
  3026. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  3027. if (TemplateParamLists.size()) {
  3028. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  3029. return 0;
  3030. }
  3031. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  3032. } else if (R->isFunctionType()) {
  3033. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  3034. move(TemplateParamLists),
  3035. AddToScope);
  3036. } else {
  3037. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
  3038. move(TemplateParamLists));
  3039. }
  3040. if (New == 0)
  3041. return 0;
  3042. // If this has an identifier and is not an invalid redeclaration or
  3043. // function template specialization, add it to the scope stack.
  3044. if (New->getDeclName() && AddToScope &&
  3045. !(D.isRedeclaration() && New->isInvalidDecl()))
  3046. PushOnScopeChains(New, S);
  3047. return New;
  3048. }
  3049. /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
  3050. /// types into constant array types in certain situations which would otherwise
  3051. /// be errors (for GCC compatibility).
  3052. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  3053. ASTContext &Context,
  3054. bool &SizeIsNegative,
  3055. llvm::APSInt &Oversized) {
  3056. // This method tries to turn a variable array into a constant
  3057. // array even when the size isn't an ICE. This is necessary
  3058. // for compatibility with code that depends on gcc's buggy
  3059. // constant expression folding, like struct {char x[(int)(char*)2];}
  3060. SizeIsNegative = false;
  3061. Oversized = 0;
  3062. if (T->isDependentType())
  3063. return QualType();
  3064. QualifierCollector Qs;
  3065. const Type *Ty = Qs.strip(T);
  3066. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  3067. QualType Pointee = PTy->getPointeeType();
  3068. QualType FixedType =
  3069. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  3070. Oversized);
  3071. if (FixedType.isNull()) return FixedType;
  3072. FixedType = Context.getPointerType(FixedType);
  3073. return Qs.apply(Context, FixedType);
  3074. }
  3075. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  3076. QualType Inner = PTy->getInnerType();
  3077. QualType FixedType =
  3078. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  3079. Oversized);
  3080. if (FixedType.isNull()) return FixedType;
  3081. FixedType = Context.getParenType(FixedType);
  3082. return Qs.apply(Context, FixedType);
  3083. }
  3084. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  3085. if (!VLATy)
  3086. return QualType();
  3087. // FIXME: We should probably handle this case
  3088. if (VLATy->getElementType()->isVariablyModifiedType())
  3089. return QualType();
  3090. llvm::APSInt Res;
  3091. if (!VLATy->getSizeExpr() ||
  3092. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  3093. return QualType();
  3094. // Check whether the array size is negative.
  3095. if (Res.isSigned() && Res.isNegative()) {
  3096. SizeIsNegative = true;
  3097. return QualType();
  3098. }
  3099. // Check whether the array is too large to be addressed.
  3100. unsigned ActiveSizeBits
  3101. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  3102. Res);
  3103. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  3104. Oversized = Res;
  3105. return QualType();
  3106. }
  3107. return Context.getConstantArrayType(VLATy->getElementType(),
  3108. Res, ArrayType::Normal, 0);
  3109. }
  3110. /// \brief Register the given locally-scoped external C declaration so
  3111. /// that it can be found later for redeclarations
  3112. void
  3113. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
  3114. const LookupResult &Previous,
  3115. Scope *S) {
  3116. assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
  3117. "Decl is not a locally-scoped decl!");
  3118. // Note that we have a locally-scoped external with this name.
  3119. LocallyScopedExternalDecls[ND->getDeclName()] = ND;
  3120. if (!Previous.isSingleResult())
  3121. return;
  3122. NamedDecl *PrevDecl = Previous.getFoundDecl();
  3123. // If there was a previous declaration of this variable, it may be
  3124. // in our identifier chain. Update the identifier chain with the new
  3125. // declaration.
  3126. if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
  3127. // The previous declaration was found on the identifer resolver
  3128. // chain, so remove it from its scope.
  3129. if (S->isDeclScope(PrevDecl)) {
  3130. // Special case for redeclarations in the SAME scope.
  3131. // Because this declaration is going to be added to the identifier chain
  3132. // later, we should temporarily take it OFF the chain.
  3133. IdResolver.RemoveDecl(ND);
  3134. } else {
  3135. // Find the scope for the original declaration.
  3136. while (S && !S->isDeclScope(PrevDecl))
  3137. S = S->getParent();
  3138. }
  3139. if (S)
  3140. S->RemoveDecl(PrevDecl);
  3141. }
  3142. }
  3143. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
  3144. Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
  3145. if (ExternalSource) {
  3146. // Load locally-scoped external decls from the external source.
  3147. SmallVector<NamedDecl *, 4> Decls;
  3148. ExternalSource->ReadLocallyScopedExternalDecls(Decls);
  3149. for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
  3150. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  3151. = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
  3152. if (Pos == LocallyScopedExternalDecls.end())
  3153. LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
  3154. }
  3155. }
  3156. return LocallyScopedExternalDecls.find(Name);
  3157. }
  3158. /// \brief Diagnose function specifiers on a declaration of an identifier that
  3159. /// does not identify a function.
  3160. void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
  3161. // FIXME: We should probably indicate the identifier in question to avoid
  3162. // confusion for constructs like "inline int a(), b;"
  3163. if (D.getDeclSpec().isInlineSpecified())
  3164. Diag(D.getDeclSpec().getInlineSpecLoc(),
  3165. diag::err_inline_non_function);
  3166. if (D.getDeclSpec().isVirtualSpecified())
  3167. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  3168. diag::err_virtual_non_function);
  3169. if (D.getDeclSpec().isExplicitSpecified())
  3170. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  3171. diag::err_explicit_non_function);
  3172. }
  3173. NamedDecl*
  3174. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  3175. TypeSourceInfo *TInfo, LookupResult &Previous) {
  3176. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  3177. if (D.getCXXScopeSpec().isSet()) {
  3178. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  3179. << D.getCXXScopeSpec().getRange();
  3180. D.setInvalidType();
  3181. // Pretend we didn't see the scope specifier.
  3182. DC = CurContext;
  3183. Previous.clear();
  3184. }
  3185. if (getLangOptions().CPlusPlus) {
  3186. // Check that there are no default arguments (C++ only).
  3187. CheckExtraCXXDefaultArguments(D);
  3188. }
  3189. DiagnoseFunctionSpecifiers(D);
  3190. if (D.getDeclSpec().isThreadSpecified())
  3191. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  3192. if (D.getDeclSpec().isConstexprSpecified())
  3193. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  3194. << 1;
  3195. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  3196. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  3197. << D.getName().getSourceRange();
  3198. return 0;
  3199. }
  3200. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  3201. if (!NewTD) return 0;
  3202. // Handle attributes prior to checking for duplicates in MergeVarDecl
  3203. ProcessDeclAttributes(S, NewTD, D);
  3204. CheckTypedefForVariablyModifiedType(S, NewTD);
  3205. bool Redeclaration = D.isRedeclaration();
  3206. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  3207. D.setRedeclaration(Redeclaration);
  3208. return ND;
  3209. }
  3210. void
  3211. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  3212. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  3213. // then it shall have block scope.
  3214. // Note that variably modified types must be fixed before merging the decl so
  3215. // that redeclarations will match.
  3216. QualType T = NewTD->getUnderlyingType();
  3217. if (T->isVariablyModifiedType()) {
  3218. getCurFunction()->setHasBranchProtectedScope();
  3219. if (S->getFnParent() == 0) {
  3220. bool SizeIsNegative;
  3221. llvm::APSInt Oversized;
  3222. QualType FixedTy =
  3223. TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  3224. Oversized);
  3225. if (!FixedTy.isNull()) {
  3226. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  3227. NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
  3228. } else {
  3229. if (SizeIsNegative)
  3230. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  3231. else if (T->isVariableArrayType())
  3232. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  3233. else if (Oversized.getBoolValue())
  3234. Diag(NewTD->getLocation(), diag::err_array_too_large)
  3235. << Oversized.toString(10);
  3236. else
  3237. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  3238. NewTD->setInvalidDecl();
  3239. }
  3240. }
  3241. }
  3242. }
  3243. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  3244. /// declares a typedef-name, either using the 'typedef' type specifier or via
  3245. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  3246. NamedDecl*
  3247. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  3248. LookupResult &Previous, bool &Redeclaration) {
  3249. // Merge the decl with the existing one if appropriate. If the decl is
  3250. // in an outer scope, it isn't the same thing.
  3251. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
  3252. /*ExplicitInstantiationOrSpecialization=*/false);
  3253. if (!Previous.empty()) {
  3254. Redeclaration = true;
  3255. MergeTypedefNameDecl(NewTD, Previous);
  3256. }
  3257. // If this is the C FILE type, notify the AST context.
  3258. if (IdentifierInfo *II = NewTD->getIdentifier())
  3259. if (!NewTD->isInvalidDecl() &&
  3260. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  3261. if (II->isStr("FILE"))
  3262. Context.setFILEDecl(NewTD);
  3263. else if (II->isStr("jmp_buf"))
  3264. Context.setjmp_bufDecl(NewTD);
  3265. else if (II->isStr("sigjmp_buf"))
  3266. Context.setsigjmp_bufDecl(NewTD);
  3267. else if (II->isStr("ucontext_t"))
  3268. Context.setucontext_tDecl(NewTD);
  3269. else if (II->isStr("__builtin_va_list"))
  3270. Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
  3271. }
  3272. return NewTD;
  3273. }
  3274. /// \brief Determines whether the given declaration is an out-of-scope
  3275. /// previous declaration.
  3276. ///
  3277. /// This routine should be invoked when name lookup has found a
  3278. /// previous declaration (PrevDecl) that is not in the scope where a
  3279. /// new declaration by the same name is being introduced. If the new
  3280. /// declaration occurs in a local scope, previous declarations with
  3281. /// linkage may still be considered previous declarations (C99
  3282. /// 6.2.2p4-5, C++ [basic.link]p6).
  3283. ///
  3284. /// \param PrevDecl the previous declaration found by name
  3285. /// lookup
  3286. ///
  3287. /// \param DC the context in which the new declaration is being
  3288. /// declared.
  3289. ///
  3290. /// \returns true if PrevDecl is an out-of-scope previous declaration
  3291. /// for a new delcaration with the same name.
  3292. static bool
  3293. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  3294. ASTContext &Context) {
  3295. if (!PrevDecl)
  3296. return false;
  3297. if (!PrevDecl->hasLinkage())
  3298. return false;
  3299. if (Context.getLangOptions().CPlusPlus) {
  3300. // C++ [basic.link]p6:
  3301. // If there is a visible declaration of an entity with linkage
  3302. // having the same name and type, ignoring entities declared
  3303. // outside the innermost enclosing namespace scope, the block
  3304. // scope declaration declares that same entity and receives the
  3305. // linkage of the previous declaration.
  3306. DeclContext *OuterContext = DC->getRedeclContext();
  3307. if (!OuterContext->isFunctionOrMethod())
  3308. // This rule only applies to block-scope declarations.
  3309. return false;
  3310. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  3311. if (PrevOuterContext->isRecord())
  3312. // We found a member function: ignore it.
  3313. return false;
  3314. // Find the innermost enclosing namespace for the new and
  3315. // previous declarations.
  3316. OuterContext = OuterContext->getEnclosingNamespaceContext();
  3317. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  3318. // The previous declaration is in a different namespace, so it
  3319. // isn't the same function.
  3320. if (!OuterContext->Equals(PrevOuterContext))
  3321. return false;
  3322. }
  3323. return true;
  3324. }
  3325. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  3326. CXXScopeSpec &SS = D.getCXXScopeSpec();
  3327. if (!SS.isSet()) return;
  3328. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  3329. }
  3330. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  3331. QualType type = decl->getType();
  3332. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  3333. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  3334. // Various kinds of declaration aren't allowed to be __autoreleasing.
  3335. unsigned kind = -1U;
  3336. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  3337. if (var->hasAttr<BlocksAttr>())
  3338. kind = 0; // __block
  3339. else if (!var->hasLocalStorage())
  3340. kind = 1; // global
  3341. } else if (isa<ObjCIvarDecl>(decl)) {
  3342. kind = 3; // ivar
  3343. } else if (isa<FieldDecl>(decl)) {
  3344. kind = 2; // field
  3345. }
  3346. if (kind != -1U) {
  3347. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  3348. << kind;
  3349. }
  3350. } else if (lifetime == Qualifiers::OCL_None) {
  3351. // Try to infer lifetime.
  3352. if (!type->isObjCLifetimeType())
  3353. return false;
  3354. lifetime = type->getObjCARCImplicitLifetime();
  3355. type = Context.getLifetimeQualifiedType(type, lifetime);
  3356. decl->setType(type);
  3357. }
  3358. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  3359. // Thread-local variables cannot have lifetime.
  3360. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  3361. var->isThreadSpecified()) {
  3362. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  3363. << var->getType();
  3364. return true;
  3365. }
  3366. }
  3367. return false;
  3368. }
  3369. NamedDecl*
  3370. Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  3371. TypeSourceInfo *TInfo, LookupResult &Previous,
  3372. MultiTemplateParamsArg TemplateParamLists) {
  3373. QualType R = TInfo->getType();
  3374. DeclarationName Name = GetNameForDeclarator(D).getName();
  3375. // Check that there are no default arguments (C++ only).
  3376. if (getLangOptions().CPlusPlus)
  3377. CheckExtraCXXDefaultArguments(D);
  3378. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  3379. assert(SCSpec != DeclSpec::SCS_typedef &&
  3380. "Parser allowed 'typedef' as storage class VarDecl.");
  3381. VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
  3382. if (SCSpec == DeclSpec::SCS_mutable) {
  3383. // mutable can only appear on non-static class members, so it's always
  3384. // an error here
  3385. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  3386. D.setInvalidType();
  3387. SC = SC_None;
  3388. }
  3389. SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
  3390. VarDecl::StorageClass SCAsWritten
  3391. = StorageClassSpecToVarDeclStorageClass(SCSpec);
  3392. IdentifierInfo *II = Name.getAsIdentifierInfo();
  3393. if (!II) {
  3394. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
  3395. << Name;
  3396. return 0;
  3397. }
  3398. DiagnoseFunctionSpecifiers(D);
  3399. if (!DC->isRecord() && S->getFnParent() == 0) {
  3400. // C99 6.9p2: The storage-class specifiers auto and register shall not
  3401. // appear in the declaration specifiers in an external declaration.
  3402. if (SC == SC_Auto || SC == SC_Register) {
  3403. // If this is a register variable with an asm label specified, then this
  3404. // is a GNU extension.
  3405. if (SC == SC_Register && D.getAsmLabel())
  3406. Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
  3407. else
  3408. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  3409. D.setInvalidType();
  3410. }
  3411. }
  3412. if (getLangOptions().OpenCL) {
  3413. // Set up the special work-group-local storage class for variables in the
  3414. // OpenCL __local address space.
  3415. if (R.getAddressSpace() == LangAS::opencl_local)
  3416. SC = SC_OpenCLWorkGroupLocal;
  3417. }
  3418. bool isExplicitSpecialization = false;
  3419. VarDecl *NewVD;
  3420. if (!getLangOptions().CPlusPlus) {
  3421. NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
  3422. D.getIdentifierLoc(), II,
  3423. R, TInfo, SC, SCAsWritten);
  3424. if (D.isInvalidType())
  3425. NewVD->setInvalidDecl();
  3426. } else {
  3427. if (DC->isRecord() && !CurContext->isRecord()) {
  3428. // This is an out-of-line definition of a static data member.
  3429. if (SC == SC_Static) {
  3430. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  3431. diag::err_static_out_of_line)
  3432. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  3433. } else if (SC == SC_None)
  3434. SC = SC_Static;
  3435. }
  3436. if (SC == SC_Static) {
  3437. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  3438. if (RD->isLocalClass())
  3439. Diag(D.getIdentifierLoc(),
  3440. diag::err_static_data_member_not_allowed_in_local_class)
  3441. << Name << RD->getDeclName();
  3442. // C++ [class.union]p1: If a union contains a static data member,
  3443. // the program is ill-formed.
  3444. //
  3445. // We also disallow static data members in anonymous structs.
  3446. if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName()))
  3447. Diag(D.getIdentifierLoc(),
  3448. diag::err_static_data_member_not_allowed_in_union_or_anon_struct)
  3449. << Name << RD->isUnion();
  3450. }
  3451. }
  3452. // Match up the template parameter lists with the scope specifier, then
  3453. // determine whether we have a template or a template specialization.
  3454. isExplicitSpecialization = false;
  3455. bool Invalid = false;
  3456. if (TemplateParameterList *TemplateParams
  3457. = MatchTemplateParametersToScopeSpecifier(
  3458. D.getDeclSpec().getSourceRange().getBegin(),
  3459. D.getIdentifierLoc(),
  3460. D.getCXXScopeSpec(),
  3461. TemplateParamLists.get(),
  3462. TemplateParamLists.size(),
  3463. /*never a friend*/ false,
  3464. isExplicitSpecialization,
  3465. Invalid)) {
  3466. if (TemplateParams->size() > 0) {
  3467. // There is no such thing as a variable template.
  3468. Diag(D.getIdentifierLoc(), diag::err_template_variable)
  3469. << II
  3470. << SourceRange(TemplateParams->getTemplateLoc(),
  3471. TemplateParams->getRAngleLoc());
  3472. return 0;
  3473. } else {
  3474. // There is an extraneous 'template<>' for this variable. Complain
  3475. // about it, but allow the declaration of the variable.
  3476. Diag(TemplateParams->getTemplateLoc(),
  3477. diag::err_template_variable_noparams)
  3478. << II
  3479. << SourceRange(TemplateParams->getTemplateLoc(),
  3480. TemplateParams->getRAngleLoc());
  3481. }
  3482. }
  3483. NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
  3484. D.getIdentifierLoc(), II,
  3485. R, TInfo, SC, SCAsWritten);
  3486. // If this decl has an auto type in need of deduction, make a note of the
  3487. // Decl so we can diagnose uses of it in its own initializer.
  3488. if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
  3489. R->getContainedAutoType())
  3490. ParsingInitForAutoVars.insert(NewVD);
  3491. if (D.isInvalidType() || Invalid)
  3492. NewVD->setInvalidDecl();
  3493. SetNestedNameSpecifier(NewVD, D);
  3494. if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
  3495. NewVD->setTemplateParameterListsInfo(Context,
  3496. TemplateParamLists.size(),
  3497. TemplateParamLists.release());
  3498. }
  3499. if (D.getDeclSpec().isConstexprSpecified())
  3500. NewVD->setConstexpr(true);
  3501. }
  3502. // Set the lexical context. If the declarator has a C++ scope specifier, the
  3503. // lexical context will be different from the semantic context.
  3504. NewVD->setLexicalDeclContext(CurContext);
  3505. if (D.getDeclSpec().isThreadSpecified()) {
  3506. if (NewVD->hasLocalStorage())
  3507. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
  3508. else if (!Context.getTargetInfo().isTLSSupported())
  3509. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
  3510. else
  3511. NewVD->setThreadSpecified(true);
  3512. }
  3513. if (D.getDeclSpec().isModulePrivateSpecified()) {
  3514. if (isExplicitSpecialization)
  3515. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  3516. << 2
  3517. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  3518. else if (NewVD->hasLocalStorage())
  3519. Diag(NewVD->getLocation(), diag::err_module_private_local)
  3520. << 0 << NewVD->getDeclName()
  3521. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  3522. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  3523. else
  3524. NewVD->setModulePrivate();
  3525. }
  3526. // Handle attributes prior to checking for duplicates in MergeVarDecl
  3527. ProcessDeclAttributes(S, NewVD, D);
  3528. // In auto-retain/release, infer strong retension for variables of
  3529. // retainable type.
  3530. if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  3531. NewVD->setInvalidDecl();
  3532. // Handle GNU asm-label extension (encoded as an attribute).
  3533. if (Expr *E = (Expr*)D.getAsmLabel()) {
  3534. // The parser guarantees this is a string.
  3535. StringLiteral *SE = cast<StringLiteral>(E);
  3536. StringRef Label = SE->getString();
  3537. if (S->getFnParent() != 0) {
  3538. switch (SC) {
  3539. case SC_None:
  3540. case SC_Auto:
  3541. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  3542. break;
  3543. case SC_Register:
  3544. if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
  3545. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  3546. break;
  3547. case SC_Static:
  3548. case SC_Extern:
  3549. case SC_PrivateExtern:
  3550. case SC_OpenCLWorkGroupLocal:
  3551. break;
  3552. }
  3553. }
  3554. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  3555. Context, Label));
  3556. }
  3557. // Diagnose shadowed variables before filtering for scope.
  3558. if (!D.getCXXScopeSpec().isSet())
  3559. CheckShadow(S, NewVD, Previous);
  3560. // Don't consider existing declarations that are in a different
  3561. // scope and are out-of-semantic-context declarations (if the new
  3562. // declaration has linkage).
  3563. FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
  3564. isExplicitSpecialization);
  3565. if (!getLangOptions().CPlusPlus) {
  3566. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  3567. } else {
  3568. // Merge the decl with the existing one if appropriate.
  3569. if (!Previous.empty()) {
  3570. if (Previous.isSingleResult() &&
  3571. isa<FieldDecl>(Previous.getFoundDecl()) &&
  3572. D.getCXXScopeSpec().isSet()) {
  3573. // The user tried to define a non-static data member
  3574. // out-of-line (C++ [dcl.meaning]p1).
  3575. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  3576. << D.getCXXScopeSpec().getRange();
  3577. Previous.clear();
  3578. NewVD->setInvalidDecl();
  3579. }
  3580. } else if (D.getCXXScopeSpec().isSet()) {
  3581. // No previous declaration in the qualifying scope.
  3582. Diag(D.getIdentifierLoc(), diag::err_no_member)
  3583. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  3584. << D.getCXXScopeSpec().getRange();
  3585. NewVD->setInvalidDecl();
  3586. }
  3587. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  3588. // This is an explicit specialization of a static data member. Check it.
  3589. if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
  3590. CheckMemberSpecialization(NewVD, Previous))
  3591. NewVD->setInvalidDecl();
  3592. }
  3593. // attributes declared post-definition are currently ignored
  3594. // FIXME: This should be handled in attribute merging, not
  3595. // here.
  3596. if (Previous.isSingleResult()) {
  3597. VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3598. if (Def && (Def = Def->getDefinition()) &&
  3599. Def != NewVD && D.hasAttributes()) {
  3600. Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
  3601. Diag(Def->getLocation(), diag::note_previous_definition);
  3602. }
  3603. }
  3604. // If this is a locally-scoped extern C variable, update the map of
  3605. // such variables.
  3606. if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
  3607. !NewVD->isInvalidDecl())
  3608. RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
  3609. // If there's a #pragma GCC visibility in scope, and this isn't a class
  3610. // member, set the visibility of this variable.
  3611. if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
  3612. AddPushedVisibilityAttribute(NewVD);
  3613. MarkUnusedFileScopedDecl(NewVD);
  3614. return NewVD;
  3615. }
  3616. /// \brief Diagnose variable or built-in function shadowing. Implements
  3617. /// -Wshadow.
  3618. ///
  3619. /// This method is called whenever a VarDecl is added to a "useful"
  3620. /// scope.
  3621. ///
  3622. /// \param S the scope in which the shadowing name is being declared
  3623. /// \param R the lookup of the name
  3624. ///
  3625. void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
  3626. // Return if warning is ignored.
  3627. if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
  3628. DiagnosticsEngine::Ignored)
  3629. return;
  3630. // Don't diagnose declarations at file scope.
  3631. if (D->hasGlobalStorage())
  3632. return;
  3633. DeclContext *NewDC = D->getDeclContext();
  3634. // Only diagnose if we're shadowing an unambiguous field or variable.
  3635. if (R.getResultKind() != LookupResult::Found)
  3636. return;
  3637. NamedDecl* ShadowedDecl = R.getFoundDecl();
  3638. if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
  3639. return;
  3640. // Fields are not shadowed by variables in C++ static methods.
  3641. if (isa<FieldDecl>(ShadowedDecl))
  3642. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  3643. if (MD->isStatic())
  3644. return;
  3645. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  3646. if (shadowedVar->isExternC()) {
  3647. // For shadowing external vars, make sure that we point to the global
  3648. // declaration, not a locally scoped extern declaration.
  3649. for (VarDecl::redecl_iterator
  3650. I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
  3651. I != E; ++I)
  3652. if (I->isFileVarDecl()) {
  3653. ShadowedDecl = *I;
  3654. break;
  3655. }
  3656. }
  3657. DeclContext *OldDC = ShadowedDecl->getDeclContext();
  3658. // Only warn about certain kinds of shadowing for class members.
  3659. if (NewDC && NewDC->isRecord()) {
  3660. // In particular, don't warn about shadowing non-class members.
  3661. if (!OldDC->isRecord())
  3662. return;
  3663. // TODO: should we warn about static data members shadowing
  3664. // static data members from base classes?
  3665. // TODO: don't diagnose for inaccessible shadowed members.
  3666. // This is hard to do perfectly because we might friend the
  3667. // shadowing context, but that's just a false negative.
  3668. }
  3669. // Determine what kind of declaration we're shadowing.
  3670. unsigned Kind;
  3671. if (isa<RecordDecl>(OldDC)) {
  3672. if (isa<FieldDecl>(ShadowedDecl))
  3673. Kind = 3; // field
  3674. else
  3675. Kind = 2; // static data member
  3676. } else if (OldDC->isFileContext())
  3677. Kind = 1; // global
  3678. else
  3679. Kind = 0; // local
  3680. DeclarationName Name = R.getLookupName();
  3681. // Emit warning and note.
  3682. Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
  3683. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  3684. }
  3685. /// \brief Check -Wshadow without the advantage of a previous lookup.
  3686. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  3687. if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
  3688. DiagnosticsEngine::Ignored)
  3689. return;
  3690. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  3691. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  3692. LookupName(R, S);
  3693. CheckShadow(S, D, R);
  3694. }
  3695. /// \brief Perform semantic checking on a newly-created variable
  3696. /// declaration.
  3697. ///
  3698. /// This routine performs all of the type-checking required for a
  3699. /// variable declaration once it has been built. It is used both to
  3700. /// check variables after they have been parsed and their declarators
  3701. /// have been translated into a declaration, and to check variables
  3702. /// that have been instantiated from a template.
  3703. ///
  3704. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  3705. ///
  3706. /// Returns true if the variable declaration is a redeclaration.
  3707. bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
  3708. LookupResult &Previous) {
  3709. // If the decl is already known invalid, don't check it.
  3710. if (NewVD->isInvalidDecl())
  3711. return false;
  3712. QualType T = NewVD->getType();
  3713. if (T->isObjCObjectType()) {
  3714. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  3715. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  3716. T = Context.getObjCObjectPointerType(T);
  3717. NewVD->setType(T);
  3718. }
  3719. // Emit an error if an address space was applied to decl with local storage.
  3720. // This includes arrays of objects with address space qualifiers, but not
  3721. // automatic variables that point to other address spaces.
  3722. // ISO/IEC TR 18037 S5.1.2
  3723. if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
  3724. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
  3725. NewVD->setInvalidDecl();
  3726. return false;
  3727. }
  3728. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  3729. && !NewVD->hasAttr<BlocksAttr>()) {
  3730. if (getLangOptions().getGC() != LangOptions::NonGC)
  3731. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  3732. else
  3733. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  3734. }
  3735. bool isVM = T->isVariablyModifiedType();
  3736. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  3737. NewVD->hasAttr<BlocksAttr>())
  3738. getCurFunction()->setHasBranchProtectedScope();
  3739. if ((isVM && NewVD->hasLinkage()) ||
  3740. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  3741. bool SizeIsNegative;
  3742. llvm::APSInt Oversized;
  3743. QualType FixedTy =
  3744. TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  3745. Oversized);
  3746. if (FixedTy.isNull() && T->isVariableArrayType()) {
  3747. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  3748. // FIXME: This won't give the correct result for
  3749. // int a[10][n];
  3750. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  3751. if (NewVD->isFileVarDecl())
  3752. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  3753. << SizeRange;
  3754. else if (NewVD->getStorageClass() == SC_Static)
  3755. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  3756. << SizeRange;
  3757. else
  3758. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  3759. << SizeRange;
  3760. NewVD->setInvalidDecl();
  3761. return false;
  3762. }
  3763. if (FixedTy.isNull()) {
  3764. if (NewVD->isFileVarDecl())
  3765. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  3766. else
  3767. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  3768. NewVD->setInvalidDecl();
  3769. return false;
  3770. }
  3771. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  3772. NewVD->setType(FixedTy);
  3773. }
  3774. if (Previous.empty() && NewVD->isExternC()) {
  3775. // Since we did not find anything by this name and we're declaring
  3776. // an extern "C" variable, look for a non-visible extern "C"
  3777. // declaration with the same name.
  3778. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  3779. = findLocallyScopedExternalDecl(NewVD->getDeclName());
  3780. if (Pos != LocallyScopedExternalDecls.end())
  3781. Previous.addDecl(Pos->second);
  3782. }
  3783. if (T->isVoidType() && !NewVD->hasExternalStorage()) {
  3784. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  3785. << T;
  3786. NewVD->setInvalidDecl();
  3787. return false;
  3788. }
  3789. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  3790. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  3791. NewVD->setInvalidDecl();
  3792. return false;
  3793. }
  3794. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  3795. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  3796. NewVD->setInvalidDecl();
  3797. return false;
  3798. }
  3799. if (NewVD->isConstexpr() && !T->isDependentType() &&
  3800. RequireLiteralType(NewVD->getLocation(), T,
  3801. PDiag(diag::err_constexpr_var_non_literal))) {
  3802. NewVD->setInvalidDecl();
  3803. return false;
  3804. }
  3805. if (!Previous.empty()) {
  3806. MergeVarDecl(NewVD, Previous);
  3807. return true;
  3808. }
  3809. return false;
  3810. }
  3811. /// \brief Data used with FindOverriddenMethod
  3812. struct FindOverriddenMethodData {
  3813. Sema *S;
  3814. CXXMethodDecl *Method;
  3815. };
  3816. /// \brief Member lookup function that determines whether a given C++
  3817. /// method overrides a method in a base class, to be used with
  3818. /// CXXRecordDecl::lookupInBases().
  3819. static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
  3820. CXXBasePath &Path,
  3821. void *UserData) {
  3822. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  3823. FindOverriddenMethodData *Data
  3824. = reinterpret_cast<FindOverriddenMethodData*>(UserData);
  3825. DeclarationName Name = Data->Method->getDeclName();
  3826. // FIXME: Do we care about other names here too?
  3827. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  3828. // We really want to find the base class destructor here.
  3829. QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
  3830. CanQualType CT = Data->S->Context.getCanonicalType(T);
  3831. Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
  3832. }
  3833. for (Path.Decls = BaseRecord->lookup(Name);
  3834. Path.Decls.first != Path.Decls.second;
  3835. ++Path.Decls.first) {
  3836. NamedDecl *D = *Path.Decls.first;
  3837. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  3838. if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
  3839. return true;
  3840. }
  3841. }
  3842. return false;
  3843. }
  3844. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  3845. /// and if so, check that it's a valid override and remember it.
  3846. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  3847. // Look for virtual methods in base classes that this method might override.
  3848. CXXBasePaths Paths;
  3849. FindOverriddenMethodData Data;
  3850. Data.Method = MD;
  3851. Data.S = this;
  3852. bool AddedAny = false;
  3853. if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
  3854. for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
  3855. E = Paths.found_decls_end(); I != E; ++I) {
  3856. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
  3857. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  3858. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  3859. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  3860. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  3861. AddedAny = true;
  3862. }
  3863. }
  3864. }
  3865. }
  3866. return AddedAny;
  3867. }
  3868. namespace {
  3869. // Struct for holding all of the extra arguments needed by
  3870. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  3871. struct ActOnFDArgs {
  3872. Scope *S;
  3873. Declarator &D;
  3874. MultiTemplateParamsArg TemplateParamLists;
  3875. bool AddToScope;
  3876. };
  3877. }
  3878. namespace {
  3879. // Callback to only accept typo corrections that have a non-zero edit distance.
  3880. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  3881. public:
  3882. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  3883. return candidate.getEditDistance() > 0;
  3884. }
  3885. };
  3886. }
  3887. /// \brief Generate diagnostics for an invalid function redeclaration.
  3888. ///
  3889. /// This routine handles generating the diagnostic messages for an invalid
  3890. /// function redeclaration, including finding possible similar declarations
  3891. /// or performing typo correction if there are no previous declarations with
  3892. /// the same name.
  3893. ///
  3894. /// Returns a NamedDecl iff typo correction was performed and substituting in
  3895. /// the new declaration name does not cause new errors.
  3896. static NamedDecl* DiagnoseInvalidRedeclaration(
  3897. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  3898. ActOnFDArgs &ExtraArgs) {
  3899. NamedDecl *Result = NULL;
  3900. DeclarationName Name = NewFD->getDeclName();
  3901. DeclContext *NewDC = NewFD->getDeclContext();
  3902. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  3903. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  3904. llvm::SmallVector<unsigned, 1> MismatchedParams;
  3905. llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
  3906. TypoCorrection Correction;
  3907. bool isFriendDecl = (SemaRef.getLangOptions().CPlusPlus &&
  3908. ExtraArgs.D.getDeclSpec().isFriendSpecified());
  3909. unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
  3910. : diag::err_member_def_does_not_match;
  3911. NewFD->setInvalidDecl();
  3912. SemaRef.LookupQualifiedName(Prev, NewDC);
  3913. assert(!Prev.isAmbiguous() &&
  3914. "Cannot have an ambiguity in previous-declaration lookup");
  3915. DifferentNameValidatorCCC Validator;
  3916. if (!Prev.empty()) {
  3917. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  3918. Func != FuncEnd; ++Func) {
  3919. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  3920. if (FD &&
  3921. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  3922. // Add 1 to the index so that 0 can mean the mismatch didn't
  3923. // involve a parameter
  3924. unsigned ParamNum =
  3925. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  3926. NearMatches.push_back(std::make_pair(FD, ParamNum));
  3927. }
  3928. }
  3929. // If the qualified name lookup yielded nothing, try typo correction
  3930. } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
  3931. Prev.getLookupKind(), 0, 0,
  3932. Validator, NewDC))) {
  3933. // Trap errors.
  3934. Sema::SFINAETrap Trap(SemaRef);
  3935. // Set up everything for the call to ActOnFunctionDeclarator
  3936. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  3937. ExtraArgs.D.getIdentifierLoc());
  3938. Previous.clear();
  3939. Previous.setLookupName(Correction.getCorrection());
  3940. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  3941. CDeclEnd = Correction.end();
  3942. CDecl != CDeclEnd; ++CDecl) {
  3943. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  3944. if (FD && hasSimilarParameters(SemaRef.Context, FD, NewFD,
  3945. MismatchedParams)) {
  3946. Previous.addDecl(FD);
  3947. }
  3948. }
  3949. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  3950. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  3951. // pieces need to verify the typo-corrected C++ declaraction and hopefully
  3952. // eliminate the need for the parameter pack ExtraArgs.
  3953. Result = SemaRef.ActOnFunctionDeclarator(ExtraArgs.S, ExtraArgs.D,
  3954. NewFD->getDeclContext(),
  3955. NewFD->getTypeSourceInfo(),
  3956. Previous,
  3957. ExtraArgs.TemplateParamLists,
  3958. ExtraArgs.AddToScope);
  3959. if (Trap.hasErrorOccurred()) {
  3960. // Pretend the typo correction never occurred
  3961. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  3962. ExtraArgs.D.getIdentifierLoc());
  3963. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  3964. Previous.clear();
  3965. Previous.setLookupName(Name);
  3966. Result = NULL;
  3967. } else {
  3968. for (LookupResult::iterator Func = Previous.begin(),
  3969. FuncEnd = Previous.end();
  3970. Func != FuncEnd; ++Func) {
  3971. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
  3972. NearMatches.push_back(std::make_pair(FD, 0));
  3973. }
  3974. }
  3975. if (NearMatches.empty()) {
  3976. // Ignore the correction if it didn't yield any close FunctionDecl matches
  3977. Correction = TypoCorrection();
  3978. } else {
  3979. DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
  3980. : diag::err_member_def_does_not_match_suggest;
  3981. }
  3982. }
  3983. if (Correction)
  3984. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  3985. << Name << NewDC << Correction.getQuoted(SemaRef.getLangOptions())
  3986. << FixItHint::CreateReplacement(
  3987. NewFD->getLocation(),
  3988. Correction.getAsString(SemaRef.getLangOptions()));
  3989. else
  3990. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  3991. << Name << NewDC << NewFD->getLocation();
  3992. bool NewFDisConst = false;
  3993. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  3994. NewFDisConst = NewMD->getTypeQualifiers() & Qualifiers::Const;
  3995. for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
  3996. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  3997. NearMatch != NearMatchEnd; ++NearMatch) {
  3998. FunctionDecl *FD = NearMatch->first;
  3999. bool FDisConst = false;
  4000. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  4001. FDisConst = MD->getTypeQualifiers() & Qualifiers::Const;
  4002. if (unsigned Idx = NearMatch->second) {
  4003. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  4004. SemaRef.Diag(FDParam->getTypeSpecStartLoc(),
  4005. diag::note_member_def_close_param_match)
  4006. << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
  4007. } else if (Correction) {
  4008. SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
  4009. << Correction.getQuoted(SemaRef.getLangOptions());
  4010. } else if (FDisConst != NewFDisConst) {
  4011. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  4012. << NewFDisConst << FD->getSourceRange().getEnd();
  4013. } else
  4014. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
  4015. }
  4016. return Result;
  4017. }
  4018. static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
  4019. Declarator &D) {
  4020. switch (D.getDeclSpec().getStorageClassSpec()) {
  4021. default: llvm_unreachable("Unknown storage class!");
  4022. case DeclSpec::SCS_auto:
  4023. case DeclSpec::SCS_register:
  4024. case DeclSpec::SCS_mutable:
  4025. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4026. diag::err_typecheck_sclass_func);
  4027. D.setInvalidType();
  4028. break;
  4029. case DeclSpec::SCS_unspecified: break;
  4030. case DeclSpec::SCS_extern: return SC_Extern;
  4031. case DeclSpec::SCS_static: {
  4032. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  4033. // C99 6.7.1p5:
  4034. // The declaration of an identifier for a function that has
  4035. // block scope shall have no explicit storage-class specifier
  4036. // other than extern
  4037. // See also (C++ [dcl.stc]p4).
  4038. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4039. diag::err_static_block_func);
  4040. break;
  4041. } else
  4042. return SC_Static;
  4043. }
  4044. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4045. }
  4046. // No explicit storage class has already been returned
  4047. return SC_None;
  4048. }
  4049. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  4050. DeclContext *DC, QualType &R,
  4051. TypeSourceInfo *TInfo,
  4052. FunctionDecl::StorageClass SC,
  4053. bool &IsVirtualOkay) {
  4054. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  4055. DeclarationName Name = NameInfo.getName();
  4056. FunctionDecl *NewFD = 0;
  4057. bool isInline = D.getDeclSpec().isInlineSpecified();
  4058. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
  4059. FunctionDecl::StorageClass SCAsWritten
  4060. = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
  4061. if (!SemaRef.getLangOptions().CPlusPlus) {
  4062. // Determine whether the function was written with a
  4063. // prototype. This true when:
  4064. // - there is a prototype in the declarator, or
  4065. // - the type R of the function is some kind of typedef or other reference
  4066. // to a type name (which eventually refers to a function type).
  4067. bool HasPrototype =
  4068. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  4069. (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
  4070. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  4071. D.getSourceRange().getBegin(), NameInfo, R,
  4072. TInfo, SC, SCAsWritten, isInline,
  4073. HasPrototype);
  4074. if (D.isInvalidType())
  4075. NewFD->setInvalidDecl();
  4076. // Set the lexical context.
  4077. NewFD->setLexicalDeclContext(SemaRef.CurContext);
  4078. return NewFD;
  4079. }
  4080. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  4081. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  4082. // Check that the return type is not an abstract class type.
  4083. // For record types, this is done by the AbstractClassUsageDiagnoser once
  4084. // the class has been completely parsed.
  4085. if (!DC->isRecord() &&
  4086. SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
  4087. R->getAs<FunctionType>()->getResultType(),
  4088. diag::err_abstract_type_in_decl,
  4089. SemaRef.AbstractReturnType))
  4090. D.setInvalidType();
  4091. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  4092. // This is a C++ constructor declaration.
  4093. assert(DC->isRecord() &&
  4094. "Constructors can only be declared in a member context");
  4095. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  4096. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4097. D.getSourceRange().getBegin(), NameInfo,
  4098. R, TInfo, isExplicit, isInline,
  4099. /*isImplicitlyDeclared=*/false,
  4100. isConstexpr);
  4101. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  4102. // This is a C++ destructor declaration.
  4103. if (DC->isRecord()) {
  4104. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  4105. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  4106. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  4107. SemaRef.Context, Record,
  4108. D.getSourceRange().getBegin(),
  4109. NameInfo, R, TInfo, isInline,
  4110. /*isImplicitlyDeclared=*/false);
  4111. // If the class is complete, then we now create the implicit exception
  4112. // specification. If the class is incomplete or dependent, we can't do
  4113. // it yet.
  4114. if (SemaRef.getLangOptions().CPlusPlus0x && !Record->isDependentType() &&
  4115. Record->getDefinition() && !Record->isBeingDefined() &&
  4116. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  4117. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  4118. }
  4119. IsVirtualOkay = true;
  4120. return NewDD;
  4121. } else {
  4122. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  4123. D.setInvalidType();
  4124. // Create a FunctionDecl to satisfy the function definition parsing
  4125. // code path.
  4126. return FunctionDecl::Create(SemaRef.Context, DC,
  4127. D.getSourceRange().getBegin(),
  4128. D.getIdentifierLoc(), Name, R, TInfo,
  4129. SC, SCAsWritten, isInline,
  4130. /*hasPrototype=*/true, isConstexpr);
  4131. }
  4132. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  4133. if (!DC->isRecord()) {
  4134. SemaRef.Diag(D.getIdentifierLoc(),
  4135. diag::err_conv_function_not_member);
  4136. return 0;
  4137. }
  4138. SemaRef.CheckConversionDeclarator(D, R, SC);
  4139. IsVirtualOkay = true;
  4140. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4141. D.getSourceRange().getBegin(), NameInfo,
  4142. R, TInfo, isInline, isExplicit,
  4143. isConstexpr, SourceLocation());
  4144. } else if (DC->isRecord()) {
  4145. // If the name of the function is the same as the name of the record,
  4146. // then this must be an invalid constructor that has a return type.
  4147. // (The parser checks for a return type and makes the declarator a
  4148. // constructor if it has no return type).
  4149. if (Name.getAsIdentifierInfo() &&
  4150. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  4151. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  4152. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  4153. << SourceRange(D.getIdentifierLoc());
  4154. return 0;
  4155. }
  4156. bool isStatic = SC == SC_Static;
  4157. // [class.free]p1:
  4158. // Any allocation function for a class T is a static member
  4159. // (even if not explicitly declared static).
  4160. if (Name.getCXXOverloadedOperator() == OO_New ||
  4161. Name.getCXXOverloadedOperator() == OO_Array_New)
  4162. isStatic = true;
  4163. // [class.free]p6 Any deallocation function for a class X is a static member
  4164. // (even if not explicitly declared static).
  4165. if (Name.getCXXOverloadedOperator() == OO_Delete ||
  4166. Name.getCXXOverloadedOperator() == OO_Array_Delete)
  4167. isStatic = true;
  4168. IsVirtualOkay = !isStatic;
  4169. // This is a C++ method declaration.
  4170. return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4171. D.getSourceRange().getBegin(), NameInfo, R,
  4172. TInfo, isStatic, SCAsWritten, isInline,
  4173. isConstexpr, SourceLocation());
  4174. } else {
  4175. // Determine whether the function was written with a
  4176. // prototype. This true when:
  4177. // - we're in C++ (where every function has a prototype),
  4178. return FunctionDecl::Create(SemaRef.Context, DC,
  4179. D.getSourceRange().getBegin(),
  4180. NameInfo, R, TInfo, SC, SCAsWritten, isInline,
  4181. true/*HasPrototype*/, isConstexpr);
  4182. }
  4183. }
  4184. NamedDecl*
  4185. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  4186. TypeSourceInfo *TInfo, LookupResult &Previous,
  4187. MultiTemplateParamsArg TemplateParamLists,
  4188. bool &AddToScope) {
  4189. QualType R = TInfo->getType();
  4190. assert(R.getTypePtr()->isFunctionType());
  4191. // TODO: consider using NameInfo for diagnostic.
  4192. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4193. DeclarationName Name = NameInfo.getName();
  4194. FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
  4195. if (D.getDeclSpec().isThreadSpecified())
  4196. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  4197. // Do not allow returning a objc interface by-value.
  4198. if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
  4199. Diag(D.getIdentifierLoc(),
  4200. diag::err_object_cannot_be_passed_returned_by_value) << 0
  4201. << R->getAs<FunctionType>()->getResultType()
  4202. << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
  4203. QualType T = R->getAs<FunctionType>()->getResultType();
  4204. T = Context.getObjCObjectPointerType(T);
  4205. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
  4206. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  4207. R = Context.getFunctionType(T, FPT->arg_type_begin(),
  4208. FPT->getNumArgs(), EPI);
  4209. }
  4210. else if (isa<FunctionNoProtoType>(R))
  4211. R = Context.getFunctionNoProtoType(T);
  4212. }
  4213. bool isFriend = false;
  4214. FunctionTemplateDecl *FunctionTemplate = 0;
  4215. bool isExplicitSpecialization = false;
  4216. bool isFunctionTemplateSpecialization = false;
  4217. bool isDependentClassScopeExplicitSpecialization = false;
  4218. bool isVirtualOkay = false;
  4219. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  4220. isVirtualOkay);
  4221. if (!NewFD) return 0;
  4222. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  4223. NewFD->setTopLevelDeclInObjCContainer();
  4224. if (getLangOptions().CPlusPlus) {
  4225. bool isInline = D.getDeclSpec().isInlineSpecified();
  4226. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  4227. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  4228. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  4229. isFriend = D.getDeclSpec().isFriendSpecified();
  4230. if (isFriend && !isInline && D.isFunctionDefinition()) {
  4231. // C++ [class.friend]p5
  4232. // A function can be defined in a friend declaration of a
  4233. // class . . . . Such a function is implicitly inline.
  4234. NewFD->setImplicitlyInline();
  4235. }
  4236. SetNestedNameSpecifier(NewFD, D);
  4237. isExplicitSpecialization = false;
  4238. isFunctionTemplateSpecialization = false;
  4239. if (D.isInvalidType())
  4240. NewFD->setInvalidDecl();
  4241. // Set the lexical context. If the declarator has a C++
  4242. // scope specifier, or is the object of a friend declaration, the
  4243. // lexical context will be different from the semantic context.
  4244. NewFD->setLexicalDeclContext(CurContext);
  4245. // Match up the template parameter lists with the scope specifier, then
  4246. // determine whether we have a template or a template specialization.
  4247. bool Invalid = false;
  4248. if (TemplateParameterList *TemplateParams
  4249. = MatchTemplateParametersToScopeSpecifier(
  4250. D.getDeclSpec().getSourceRange().getBegin(),
  4251. D.getIdentifierLoc(),
  4252. D.getCXXScopeSpec(),
  4253. TemplateParamLists.get(),
  4254. TemplateParamLists.size(),
  4255. isFriend,
  4256. isExplicitSpecialization,
  4257. Invalid)) {
  4258. if (TemplateParams->size() > 0) {
  4259. // This is a function template
  4260. // Check that we can declare a template here.
  4261. if (CheckTemplateDeclScope(S, TemplateParams))
  4262. return 0;
  4263. // A destructor cannot be a template.
  4264. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  4265. Diag(NewFD->getLocation(), diag::err_destructor_template);
  4266. return 0;
  4267. }
  4268. // If we're adding a template to a dependent context, we may need to
  4269. // rebuilding some of the types used within the template parameter list,
  4270. // now that we know what the current instantiation is.
  4271. if (DC->isDependentContext()) {
  4272. ContextRAII SavedContext(*this, DC);
  4273. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  4274. Invalid = true;
  4275. }
  4276. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  4277. NewFD->getLocation(),
  4278. Name, TemplateParams,
  4279. NewFD);
  4280. FunctionTemplate->setLexicalDeclContext(CurContext);
  4281. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  4282. // For source fidelity, store the other template param lists.
  4283. if (TemplateParamLists.size() > 1) {
  4284. NewFD->setTemplateParameterListsInfo(Context,
  4285. TemplateParamLists.size() - 1,
  4286. TemplateParamLists.release());
  4287. }
  4288. } else {
  4289. // This is a function template specialization.
  4290. isFunctionTemplateSpecialization = true;
  4291. // For source fidelity, store all the template param lists.
  4292. NewFD->setTemplateParameterListsInfo(Context,
  4293. TemplateParamLists.size(),
  4294. TemplateParamLists.release());
  4295. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  4296. if (isFriend) {
  4297. // We want to remove the "template<>", found here.
  4298. SourceRange RemoveRange = TemplateParams->getSourceRange();
  4299. // If we remove the template<> and the name is not a
  4300. // template-id, we're actually silently creating a problem:
  4301. // the friend declaration will refer to an untemplated decl,
  4302. // and clearly the user wants a template specialization. So
  4303. // we need to insert '<>' after the name.
  4304. SourceLocation InsertLoc;
  4305. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  4306. InsertLoc = D.getName().getSourceRange().getEnd();
  4307. InsertLoc = PP.getLocForEndOfToken(InsertLoc);
  4308. }
  4309. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  4310. << Name << RemoveRange
  4311. << FixItHint::CreateRemoval(RemoveRange)
  4312. << FixItHint::CreateInsertion(InsertLoc, "<>");
  4313. }
  4314. }
  4315. }
  4316. else {
  4317. // All template param lists were matched against the scope specifier:
  4318. // this is NOT (an explicit specialization of) a template.
  4319. if (TemplateParamLists.size() > 0)
  4320. // For source fidelity, store all the template param lists.
  4321. NewFD->setTemplateParameterListsInfo(Context,
  4322. TemplateParamLists.size(),
  4323. TemplateParamLists.release());
  4324. }
  4325. if (Invalid) {
  4326. NewFD->setInvalidDecl();
  4327. if (FunctionTemplate)
  4328. FunctionTemplate->setInvalidDecl();
  4329. }
  4330. // If we see "T var();" at block scope, where T is a class type, it is
  4331. // probably an attempt to initialize a variable, not a function declaration.
  4332. // We don't catch this case earlier, since there is no ambiguity here.
  4333. if (!FunctionTemplate && D.getFunctionDefinitionKind() == FDK_Declaration &&
  4334. CurContext->isFunctionOrMethod() &&
  4335. D.getNumTypeObjects() == 1 && D.isFunctionDeclarator() &&
  4336. D.getDeclSpec().getStorageClassSpecAsWritten()
  4337. == DeclSpec::SCS_unspecified) {
  4338. QualType T = R->getAs<FunctionType>()->getResultType();
  4339. DeclaratorChunk &C = D.getTypeObject(0);
  4340. if (!T->isVoidType() && C.Fun.NumArgs == 0 && !C.Fun.isVariadic &&
  4341. !C.Fun.TrailingReturnType &&
  4342. C.Fun.getExceptionSpecType() == EST_None) {
  4343. SourceRange ParenRange(C.Loc, C.EndLoc);
  4344. Diag(C.Loc, diag::warn_empty_parens_are_function_decl) << ParenRange;
  4345. // If the declaration looks like:
  4346. // T var1,
  4347. // f();
  4348. // and name lookup finds a function named 'f', then the ',' was
  4349. // probably intended to be a ';'.
  4350. if (!D.isFirstDeclarator() && D.getIdentifier()) {
  4351. FullSourceLoc Comma(D.getCommaLoc(), SourceMgr);
  4352. FullSourceLoc Name(D.getIdentifierLoc(), SourceMgr);
  4353. if (Comma.getFileID() != Name.getFileID() ||
  4354. Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
  4355. LookupResult Result(*this, D.getIdentifier(), SourceLocation(),
  4356. LookupOrdinaryName);
  4357. if (LookupName(Result, S))
  4358. Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
  4359. << FixItHint::CreateReplacement(D.getCommaLoc(), ";") << NewFD;
  4360. }
  4361. }
  4362. const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  4363. // Empty parens mean value-initialization, and no parens mean default
  4364. // initialization. These are equivalent if the default constructor is
  4365. // user-provided, or if zero-initialization is a no-op.
  4366. if (RD && RD->hasDefinition() &&
  4367. (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
  4368. Diag(C.Loc, diag::note_empty_parens_default_ctor)
  4369. << FixItHint::CreateRemoval(ParenRange);
  4370. else if (const char *Init = getFixItZeroInitializerForType(T))
  4371. Diag(C.Loc, diag::note_empty_parens_zero_initialize)
  4372. << FixItHint::CreateReplacement(ParenRange, Init);
  4373. else if (LangOpts.CPlusPlus0x)
  4374. Diag(C.Loc, diag::note_empty_parens_zero_initialize)
  4375. << FixItHint::CreateReplacement(ParenRange, "{}");
  4376. }
  4377. }
  4378. // C++ [dcl.fct.spec]p5:
  4379. // The virtual specifier shall only be used in declarations of
  4380. // nonstatic class member functions that appear within a
  4381. // member-specification of a class declaration; see 10.3.
  4382. //
  4383. if (isVirtual && !NewFD->isInvalidDecl()) {
  4384. if (!isVirtualOkay) {
  4385. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  4386. diag::err_virtual_non_function);
  4387. } else if (!CurContext->isRecord()) {
  4388. // 'virtual' was specified outside of the class.
  4389. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  4390. diag::err_virtual_out_of_class)
  4391. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  4392. } else if (NewFD->getDescribedFunctionTemplate()) {
  4393. // C++ [temp.mem]p3:
  4394. // A member function template shall not be virtual.
  4395. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  4396. diag::err_virtual_member_function_template)
  4397. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  4398. } else {
  4399. // Okay: Add virtual to the method.
  4400. NewFD->setVirtualAsWritten(true);
  4401. }
  4402. }
  4403. // C++ [dcl.fct.spec]p3:
  4404. // The inline specifier shall not appear on a block scope function
  4405. // declaration.
  4406. if (isInline && !NewFD->isInvalidDecl()) {
  4407. if (CurContext->isFunctionOrMethod()) {
  4408. // 'inline' is not allowed on block scope function declaration.
  4409. Diag(D.getDeclSpec().getInlineSpecLoc(),
  4410. diag::err_inline_declaration_block_scope) << Name
  4411. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  4412. }
  4413. }
  4414. // C++ [dcl.fct.spec]p6:
  4415. // The explicit specifier shall be used only in the declaration of a
  4416. // constructor or conversion function within its class definition;
  4417. // see 12.3.1 and 12.3.2.
  4418. if (isExplicit && !NewFD->isInvalidDecl()) {
  4419. if (!CurContext->isRecord()) {
  4420. // 'explicit' was specified outside of the class.
  4421. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  4422. diag::err_explicit_out_of_class)
  4423. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  4424. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  4425. !isa<CXXConversionDecl>(NewFD)) {
  4426. // 'explicit' was specified on a function that wasn't a constructor
  4427. // or conversion function.
  4428. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  4429. diag::err_explicit_non_ctor_or_conv_function)
  4430. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  4431. }
  4432. }
  4433. if (isConstexpr) {
  4434. // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
  4435. // are implicitly inline.
  4436. NewFD->setImplicitlyInline();
  4437. // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
  4438. // be either constructors or to return a literal type. Therefore,
  4439. // destructors cannot be declared constexpr.
  4440. if (isa<CXXDestructorDecl>(NewFD))
  4441. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  4442. }
  4443. // If __module_private__ was specified, mark the function accordingly.
  4444. if (D.getDeclSpec().isModulePrivateSpecified()) {
  4445. if (isFunctionTemplateSpecialization) {
  4446. SourceLocation ModulePrivateLoc
  4447. = D.getDeclSpec().getModulePrivateSpecLoc();
  4448. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  4449. << 0
  4450. << FixItHint::CreateRemoval(ModulePrivateLoc);
  4451. } else {
  4452. NewFD->setModulePrivate();
  4453. if (FunctionTemplate)
  4454. FunctionTemplate->setModulePrivate();
  4455. }
  4456. }
  4457. if (isFriend) {
  4458. // For now, claim that the objects have no previous declaration.
  4459. if (FunctionTemplate) {
  4460. FunctionTemplate->setObjectOfFriendDecl(false);
  4461. FunctionTemplate->setAccess(AS_public);
  4462. }
  4463. NewFD->setObjectOfFriendDecl(false);
  4464. NewFD->setAccess(AS_public);
  4465. }
  4466. // If a function is defined as defaulted or deleted, mark it as such now.
  4467. switch (D.getFunctionDefinitionKind()) {
  4468. case FDK_Declaration:
  4469. case FDK_Definition:
  4470. break;
  4471. case FDK_Defaulted:
  4472. NewFD->setDefaulted();
  4473. break;
  4474. case FDK_Deleted:
  4475. NewFD->setDeletedAsWritten();
  4476. break;
  4477. }
  4478. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  4479. D.isFunctionDefinition()) {
  4480. // C++ [class.mfct]p2:
  4481. // A member function may be defined (8.4) in its class definition, in
  4482. // which case it is an inline member function (7.1.2)
  4483. NewFD->setImplicitlyInline();
  4484. }
  4485. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  4486. !CurContext->isRecord()) {
  4487. // C++ [class.static]p1:
  4488. // A data or function member of a class may be declared static
  4489. // in a class definition, in which case it is a static member of
  4490. // the class.
  4491. // Complain about the 'static' specifier if it's on an out-of-line
  4492. // member function definition.
  4493. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4494. diag::err_static_out_of_line)
  4495. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  4496. }
  4497. }
  4498. // Filter out previous declarations that don't match the scope.
  4499. FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
  4500. isExplicitSpecialization ||
  4501. isFunctionTemplateSpecialization);
  4502. // Handle GNU asm-label extension (encoded as an attribute).
  4503. if (Expr *E = (Expr*) D.getAsmLabel()) {
  4504. // The parser guarantees this is a string.
  4505. StringLiteral *SE = cast<StringLiteral>(E);
  4506. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  4507. SE->getString()));
  4508. }
  4509. // Copy the parameter declarations from the declarator D to the function
  4510. // declaration NewFD, if they are available. First scavenge them into Params.
  4511. SmallVector<ParmVarDecl*, 16> Params;
  4512. if (D.isFunctionDeclarator()) {
  4513. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  4514. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  4515. // function that takes no arguments, not a function that takes a
  4516. // single void argument.
  4517. // We let through "const void" here because Sema::GetTypeForDeclarator
  4518. // already checks for that case.
  4519. if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
  4520. FTI.ArgInfo[0].Param &&
  4521. cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
  4522. // Empty arg list, don't push any params.
  4523. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
  4524. // In C++, the empty parameter-type-list must be spelled "void"; a
  4525. // typedef of void is not permitted.
  4526. if (getLangOptions().CPlusPlus &&
  4527. Param->getType().getUnqualifiedType() != Context.VoidTy) {
  4528. bool IsTypeAlias = false;
  4529. if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
  4530. IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
  4531. else if (const TemplateSpecializationType *TST =
  4532. Param->getType()->getAs<TemplateSpecializationType>())
  4533. IsTypeAlias = TST->isTypeAlias();
  4534. Diag(Param->getLocation(), diag::err_param_typedef_of_void)
  4535. << IsTypeAlias;
  4536. }
  4537. } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
  4538. for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
  4539. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
  4540. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  4541. Param->setDeclContext(NewFD);
  4542. Params.push_back(Param);
  4543. if (Param->isInvalidDecl())
  4544. NewFD->setInvalidDecl();
  4545. }
  4546. }
  4547. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  4548. // When we're declaring a function with a typedef, typeof, etc as in the
  4549. // following example, we'll need to synthesize (unnamed)
  4550. // parameters for use in the declaration.
  4551. //
  4552. // @code
  4553. // typedef void fn(int);
  4554. // fn f;
  4555. // @endcode
  4556. // Synthesize a parameter for each argument type.
  4557. for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
  4558. AE = FT->arg_type_end(); AI != AE; ++AI) {
  4559. ParmVarDecl *Param =
  4560. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
  4561. Param->setScopeInfo(0, Params.size());
  4562. Params.push_back(Param);
  4563. }
  4564. } else {
  4565. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  4566. "Should not need args for typedef of non-prototype fn");
  4567. }
  4568. // Finally, we know we have the right number of parameters, install them.
  4569. NewFD->setParams(Params);
  4570. // Process the non-inheritable attributes on this declaration.
  4571. ProcessDeclAttributes(S, NewFD, D,
  4572. /*NonInheritable=*/true, /*Inheritable=*/false);
  4573. if (!getLangOptions().CPlusPlus) {
  4574. // Perform semantic checking on the function declaration.
  4575. bool isExplicitSpecialization=false;
  4576. if (!NewFD->isInvalidDecl()) {
  4577. if (NewFD->getResultType()->isVariablyModifiedType()) {
  4578. // Functions returning a variably modified type violate C99 6.7.5.2p2
  4579. // because all functions have linkage.
  4580. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  4581. NewFD->setInvalidDecl();
  4582. } else {
  4583. if (NewFD->isMain())
  4584. CheckMain(NewFD, D.getDeclSpec());
  4585. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  4586. isExplicitSpecialization));
  4587. }
  4588. }
  4589. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  4590. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  4591. "previous declaration set still overloaded");
  4592. } else {
  4593. // If the declarator is a template-id, translate the parser's template
  4594. // argument list into our AST format.
  4595. bool HasExplicitTemplateArgs = false;
  4596. TemplateArgumentListInfo TemplateArgs;
  4597. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  4598. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  4599. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  4600. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  4601. ASTTemplateArgsPtr TemplateArgsPtr(*this,
  4602. TemplateId->getTemplateArgs(),
  4603. TemplateId->NumArgs);
  4604. translateTemplateArguments(TemplateArgsPtr,
  4605. TemplateArgs);
  4606. TemplateArgsPtr.release();
  4607. HasExplicitTemplateArgs = true;
  4608. if (NewFD->isInvalidDecl()) {
  4609. HasExplicitTemplateArgs = false;
  4610. } else if (FunctionTemplate) {
  4611. // Function template with explicit template arguments.
  4612. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  4613. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  4614. HasExplicitTemplateArgs = false;
  4615. } else if (!isFunctionTemplateSpecialization &&
  4616. !D.getDeclSpec().isFriendSpecified()) {
  4617. // We have encountered something that the user meant to be a
  4618. // specialization (because it has explicitly-specified template
  4619. // arguments) but that was not introduced with a "template<>" (or had
  4620. // too few of them).
  4621. Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
  4622. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
  4623. << FixItHint::CreateInsertion(
  4624. D.getDeclSpec().getSourceRange().getBegin(),
  4625. "template<> ");
  4626. isFunctionTemplateSpecialization = true;
  4627. } else {
  4628. // "friend void foo<>(int);" is an implicit specialization decl.
  4629. isFunctionTemplateSpecialization = true;
  4630. }
  4631. } else if (isFriend && isFunctionTemplateSpecialization) {
  4632. // This combination is only possible in a recovery case; the user
  4633. // wrote something like:
  4634. // template <> friend void foo(int);
  4635. // which we're recovering from as if the user had written:
  4636. // friend void foo<>(int);
  4637. // Go ahead and fake up a template id.
  4638. HasExplicitTemplateArgs = true;
  4639. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  4640. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  4641. }
  4642. // If it's a friend (and only if it's a friend), it's possible
  4643. // that either the specialized function type or the specialized
  4644. // template is dependent, and therefore matching will fail. In
  4645. // this case, don't check the specialization yet.
  4646. bool InstantiationDependent = false;
  4647. if (isFunctionTemplateSpecialization && isFriend &&
  4648. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  4649. TemplateSpecializationType::anyDependentTemplateArguments(
  4650. TemplateArgs.getArgumentArray(), TemplateArgs.size(),
  4651. InstantiationDependent))) {
  4652. assert(HasExplicitTemplateArgs &&
  4653. "friend function specialization without template args");
  4654. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  4655. Previous))
  4656. NewFD->setInvalidDecl();
  4657. } else if (isFunctionTemplateSpecialization) {
  4658. if (CurContext->isDependentContext() && CurContext->isRecord()
  4659. && !isFriend) {
  4660. isDependentClassScopeExplicitSpecialization = true;
  4661. Diag(NewFD->getLocation(), getLangOptions().MicrosoftExt ?
  4662. diag::ext_function_specialization_in_class :
  4663. diag::err_function_specialization_in_class)
  4664. << NewFD->getDeclName();
  4665. } else if (CheckFunctionTemplateSpecialization(NewFD,
  4666. (HasExplicitTemplateArgs ? &TemplateArgs : 0),
  4667. Previous))
  4668. NewFD->setInvalidDecl();
  4669. // C++ [dcl.stc]p1:
  4670. // A storage-class-specifier shall not be specified in an explicit
  4671. // specialization (14.7.3)
  4672. if (SC != SC_None) {
  4673. if (SC != NewFD->getStorageClass())
  4674. Diag(NewFD->getLocation(),
  4675. diag::err_explicit_specialization_inconsistent_storage_class)
  4676. << SC
  4677. << FixItHint::CreateRemoval(
  4678. D.getDeclSpec().getStorageClassSpecLoc());
  4679. else
  4680. Diag(NewFD->getLocation(),
  4681. diag::ext_explicit_specialization_storage_class)
  4682. << FixItHint::CreateRemoval(
  4683. D.getDeclSpec().getStorageClassSpecLoc());
  4684. }
  4685. } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
  4686. if (CheckMemberSpecialization(NewFD, Previous))
  4687. NewFD->setInvalidDecl();
  4688. }
  4689. // Perform semantic checking on the function declaration.
  4690. if (!isDependentClassScopeExplicitSpecialization) {
  4691. if (NewFD->isInvalidDecl()) {
  4692. // If this is a class member, mark the class invalid immediately.
  4693. // This avoids some consistency errors later.
  4694. if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
  4695. methodDecl->getParent()->setInvalidDecl();
  4696. } else {
  4697. if (NewFD->isMain())
  4698. CheckMain(NewFD, D.getDeclSpec());
  4699. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  4700. isExplicitSpecialization));
  4701. }
  4702. }
  4703. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  4704. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  4705. "previous declaration set still overloaded");
  4706. NamedDecl *PrincipalDecl = (FunctionTemplate
  4707. ? cast<NamedDecl>(FunctionTemplate)
  4708. : NewFD);
  4709. if (isFriend && D.isRedeclaration()) {
  4710. AccessSpecifier Access = AS_public;
  4711. if (!NewFD->isInvalidDecl())
  4712. Access = NewFD->getPreviousDecl()->getAccess();
  4713. NewFD->setAccess(Access);
  4714. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  4715. PrincipalDecl->setObjectOfFriendDecl(true);
  4716. }
  4717. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  4718. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  4719. PrincipalDecl->setNonMemberOperator();
  4720. // If we have a function template, check the template parameter
  4721. // list. This will check and merge default template arguments.
  4722. if (FunctionTemplate) {
  4723. FunctionTemplateDecl *PrevTemplate =
  4724. FunctionTemplate->getPreviousDecl();
  4725. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  4726. PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
  4727. D.getDeclSpec().isFriendSpecified()
  4728. ? (D.isFunctionDefinition()
  4729. ? TPC_FriendFunctionTemplateDefinition
  4730. : TPC_FriendFunctionTemplate)
  4731. : (D.getCXXScopeSpec().isSet() &&
  4732. DC && DC->isRecord() &&
  4733. DC->isDependentContext())
  4734. ? TPC_ClassTemplateMember
  4735. : TPC_FunctionTemplate);
  4736. }
  4737. if (NewFD->isInvalidDecl()) {
  4738. // Ignore all the rest of this.
  4739. } else if (!D.isRedeclaration()) {
  4740. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  4741. AddToScope };
  4742. // Fake up an access specifier if it's supposed to be a class member.
  4743. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  4744. NewFD->setAccess(AS_public);
  4745. // Qualified decls generally require a previous declaration.
  4746. if (D.getCXXScopeSpec().isSet()) {
  4747. // ...with the major exception of templated-scope or
  4748. // dependent-scope friend declarations.
  4749. // TODO: we currently also suppress this check in dependent
  4750. // contexts because (1) the parameter depth will be off when
  4751. // matching friend templates and (2) we might actually be
  4752. // selecting a friend based on a dependent factor. But there
  4753. // are situations where these conditions don't apply and we
  4754. // can actually do this check immediately.
  4755. if (isFriend &&
  4756. (TemplateParamLists.size() ||
  4757. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  4758. CurContext->isDependentContext())) {
  4759. // ignore these
  4760. } else {
  4761. // The user tried to provide an out-of-line definition for a
  4762. // function that is a member of a class or namespace, but there
  4763. // was no such member function declared (C++ [class.mfct]p2,
  4764. // C++ [namespace.memdef]p2). For example:
  4765. //
  4766. // class X {
  4767. // void f() const;
  4768. // };
  4769. //
  4770. // void X::f() { } // ill-formed
  4771. //
  4772. // Complain about this problem, and attempt to suggest close
  4773. // matches (e.g., those that differ only in cv-qualifiers and
  4774. // whether the parameter types are references).
  4775. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
  4776. NewFD,
  4777. ExtraArgs)) {
  4778. AddToScope = ExtraArgs.AddToScope;
  4779. return Result;
  4780. }
  4781. }
  4782. // Unqualified local friend declarations are required to resolve
  4783. // to something.
  4784. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  4785. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
  4786. NewFD,
  4787. ExtraArgs)) {
  4788. AddToScope = ExtraArgs.AddToScope;
  4789. return Result;
  4790. }
  4791. }
  4792. } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
  4793. !isFriend && !isFunctionTemplateSpecialization &&
  4794. !isExplicitSpecialization) {
  4795. // An out-of-line member function declaration must also be a
  4796. // definition (C++ [dcl.meaning]p1).
  4797. // Note that this is not the case for explicit specializations of
  4798. // function templates or member functions of class templates, per
  4799. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  4800. // extension for compatibility with old SWIG code which likes to
  4801. // generate them.
  4802. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  4803. << D.getCXXScopeSpec().getRange();
  4804. }
  4805. }
  4806. // Handle attributes. We need to have merged decls when handling attributes
  4807. // (for example to check for conflicts, etc).
  4808. // FIXME: This needs to happen before we merge declarations. Then,
  4809. // let attribute merging cope with attribute conflicts.
  4810. ProcessDeclAttributes(S, NewFD, D,
  4811. /*NonInheritable=*/false, /*Inheritable=*/true);
  4812. // attributes declared post-definition are currently ignored
  4813. // FIXME: This should happen during attribute merging
  4814. if (D.isRedeclaration() && Previous.isSingleResult()) {
  4815. const FunctionDecl *Def;
  4816. FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
  4817. if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
  4818. Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
  4819. Diag(Def->getLocation(), diag::note_previous_definition);
  4820. }
  4821. }
  4822. AddKnownFunctionAttributes(NewFD);
  4823. if (NewFD->hasAttr<OverloadableAttr>() &&
  4824. !NewFD->getType()->getAs<FunctionProtoType>()) {
  4825. Diag(NewFD->getLocation(),
  4826. diag::err_attribute_overloadable_no_prototype)
  4827. << NewFD;
  4828. // Turn this into a variadic function with no parameters.
  4829. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  4830. FunctionProtoType::ExtProtoInfo EPI;
  4831. EPI.Variadic = true;
  4832. EPI.ExtInfo = FT->getExtInfo();
  4833. QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
  4834. NewFD->setType(R);
  4835. }
  4836. // If there's a #pragma GCC visibility in scope, and this isn't a class
  4837. // member, set the visibility of this function.
  4838. if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
  4839. AddPushedVisibilityAttribute(NewFD);
  4840. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  4841. // marking the function.
  4842. AddCFAuditedAttribute(NewFD);
  4843. // If this is a locally-scoped extern C function, update the
  4844. // map of such names.
  4845. if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
  4846. && !NewFD->isInvalidDecl())
  4847. RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
  4848. // Set this FunctionDecl's range up to the right paren.
  4849. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  4850. if (getLangOptions().CPlusPlus) {
  4851. if (FunctionTemplate) {
  4852. if (NewFD->isInvalidDecl())
  4853. FunctionTemplate->setInvalidDecl();
  4854. return FunctionTemplate;
  4855. }
  4856. }
  4857. MarkUnusedFileScopedDecl(NewFD);
  4858. if (getLangOptions().CUDA)
  4859. if (IdentifierInfo *II = NewFD->getIdentifier())
  4860. if (!NewFD->isInvalidDecl() &&
  4861. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  4862. if (II->isStr("cudaConfigureCall")) {
  4863. if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
  4864. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  4865. Context.setcudaConfigureCallDecl(NewFD);
  4866. }
  4867. }
  4868. // Here we have an function template explicit specialization at class scope.
  4869. // The actually specialization will be postponed to template instatiation
  4870. // time via the ClassScopeFunctionSpecializationDecl node.
  4871. if (isDependentClassScopeExplicitSpecialization) {
  4872. ClassScopeFunctionSpecializationDecl *NewSpec =
  4873. ClassScopeFunctionSpecializationDecl::Create(
  4874. Context, CurContext, SourceLocation(),
  4875. cast<CXXMethodDecl>(NewFD));
  4876. CurContext->addDecl(NewSpec);
  4877. AddToScope = false;
  4878. }
  4879. return NewFD;
  4880. }
  4881. /// \brief Perform semantic checking of a new function declaration.
  4882. ///
  4883. /// Performs semantic analysis of the new function declaration
  4884. /// NewFD. This routine performs all semantic checking that does not
  4885. /// require the actual declarator involved in the declaration, and is
  4886. /// used both for the declaration of functions as they are parsed
  4887. /// (called via ActOnDeclarator) and for the declaration of functions
  4888. /// that have been instantiated via C++ template instantiation (called
  4889. /// via InstantiateDecl).
  4890. ///
  4891. /// \param IsExplicitSpecialiation whether this new function declaration is
  4892. /// an explicit specialization of the previous declaration.
  4893. ///
  4894. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  4895. ///
  4896. /// Returns true if the function declaration is a redeclaration.
  4897. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  4898. LookupResult &Previous,
  4899. bool IsExplicitSpecialization) {
  4900. assert(!NewFD->getResultType()->isVariablyModifiedType()
  4901. && "Variably modified return types are not handled here");
  4902. // Check for a previous declaration of this name.
  4903. if (Previous.empty() && NewFD->isExternC()) {
  4904. // Since we did not find anything by this name and we're declaring
  4905. // an extern "C" function, look for a non-visible extern "C"
  4906. // declaration with the same name.
  4907. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  4908. = findLocallyScopedExternalDecl(NewFD->getDeclName());
  4909. if (Pos != LocallyScopedExternalDecls.end())
  4910. Previous.addDecl(Pos->second);
  4911. }
  4912. bool Redeclaration = false;
  4913. // Merge or overload the declaration with an existing declaration of
  4914. // the same name, if appropriate.
  4915. if (!Previous.empty()) {
  4916. // Determine whether NewFD is an overload of PrevDecl or
  4917. // a declaration that requires merging. If it's an overload,
  4918. // there's no more work to do here; we'll just add the new
  4919. // function to the scope.
  4920. NamedDecl *OldDecl = 0;
  4921. if (!AllowOverloadingOfFunction(Previous, Context)) {
  4922. Redeclaration = true;
  4923. OldDecl = Previous.getFoundDecl();
  4924. } else {
  4925. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  4926. /*NewIsUsingDecl*/ false)) {
  4927. case Ovl_Match:
  4928. Redeclaration = true;
  4929. break;
  4930. case Ovl_NonFunction:
  4931. Redeclaration = true;
  4932. break;
  4933. case Ovl_Overload:
  4934. Redeclaration = false;
  4935. break;
  4936. }
  4937. if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  4938. // If a function name is overloadable in C, then every function
  4939. // with that name must be marked "overloadable".
  4940. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  4941. << Redeclaration << NewFD;
  4942. NamedDecl *OverloadedDecl = 0;
  4943. if (Redeclaration)
  4944. OverloadedDecl = OldDecl;
  4945. else if (!Previous.empty())
  4946. OverloadedDecl = Previous.getRepresentativeDecl();
  4947. if (OverloadedDecl)
  4948. Diag(OverloadedDecl->getLocation(),
  4949. diag::note_attribute_overloadable_prev_overload);
  4950. NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
  4951. Context));
  4952. }
  4953. }
  4954. if (Redeclaration) {
  4955. // NewFD and OldDecl represent declarations that need to be
  4956. // merged.
  4957. if (MergeFunctionDecl(NewFD, OldDecl)) {
  4958. NewFD->setInvalidDecl();
  4959. return Redeclaration;
  4960. }
  4961. Previous.clear();
  4962. Previous.addDecl(OldDecl);
  4963. if (FunctionTemplateDecl *OldTemplateDecl
  4964. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  4965. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  4966. FunctionTemplateDecl *NewTemplateDecl
  4967. = NewFD->getDescribedFunctionTemplate();
  4968. assert(NewTemplateDecl && "Template/non-template mismatch");
  4969. if (CXXMethodDecl *Method
  4970. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  4971. Method->setAccess(OldTemplateDecl->getAccess());
  4972. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  4973. }
  4974. // If this is an explicit specialization of a member that is a function
  4975. // template, mark it as a member specialization.
  4976. if (IsExplicitSpecialization &&
  4977. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  4978. NewTemplateDecl->setMemberSpecialization();
  4979. assert(OldTemplateDecl->isMemberSpecialization());
  4980. }
  4981. } else {
  4982. if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
  4983. NewFD->setAccess(OldDecl->getAccess());
  4984. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  4985. }
  4986. }
  4987. }
  4988. // Semantic checking for this function declaration (in isolation).
  4989. if (getLangOptions().CPlusPlus) {
  4990. // C++-specific checks.
  4991. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  4992. CheckConstructor(Constructor);
  4993. } else if (CXXDestructorDecl *Destructor =
  4994. dyn_cast<CXXDestructorDecl>(NewFD)) {
  4995. CXXRecordDecl *Record = Destructor->getParent();
  4996. QualType ClassType = Context.getTypeDeclType(Record);
  4997. // FIXME: Shouldn't we be able to perform this check even when the class
  4998. // type is dependent? Both gcc and edg can handle that.
  4999. if (!ClassType->isDependentType()) {
  5000. DeclarationName Name
  5001. = Context.DeclarationNames.getCXXDestructorName(
  5002. Context.getCanonicalType(ClassType));
  5003. if (NewFD->getDeclName() != Name) {
  5004. Diag(NewFD->getLocation(), diag::err_destructor_name);
  5005. NewFD->setInvalidDecl();
  5006. return Redeclaration;
  5007. }
  5008. }
  5009. } else if (CXXConversionDecl *Conversion
  5010. = dyn_cast<CXXConversionDecl>(NewFD)) {
  5011. ActOnConversionDeclarator(Conversion);
  5012. }
  5013. // Find any virtual functions that this function overrides.
  5014. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  5015. if (!Method->isFunctionTemplateSpecialization() &&
  5016. !Method->getDescribedFunctionTemplate()) {
  5017. if (AddOverriddenMethods(Method->getParent(), Method)) {
  5018. // If the function was marked as "static", we have a problem.
  5019. if (NewFD->getStorageClass() == SC_Static) {
  5020. Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
  5021. << NewFD->getDeclName();
  5022. for (CXXMethodDecl::method_iterator
  5023. Overridden = Method->begin_overridden_methods(),
  5024. OverriddenEnd = Method->end_overridden_methods();
  5025. Overridden != OverriddenEnd;
  5026. ++Overridden) {
  5027. Diag((*Overridden)->getLocation(),
  5028. diag::note_overridden_virtual_function);
  5029. }
  5030. }
  5031. }
  5032. }
  5033. }
  5034. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  5035. if (NewFD->isOverloadedOperator() &&
  5036. CheckOverloadedOperatorDeclaration(NewFD)) {
  5037. NewFD->setInvalidDecl();
  5038. return Redeclaration;
  5039. }
  5040. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  5041. if (NewFD->getLiteralIdentifier() &&
  5042. CheckLiteralOperatorDeclaration(NewFD)) {
  5043. NewFD->setInvalidDecl();
  5044. return Redeclaration;
  5045. }
  5046. // In C++, check default arguments now that we have merged decls. Unless
  5047. // the lexical context is the class, because in this case this is done
  5048. // during delayed parsing anyway.
  5049. if (!CurContext->isRecord())
  5050. CheckCXXDefaultArguments(NewFD);
  5051. // If this function declares a builtin function, check the type of this
  5052. // declaration against the expected type for the builtin.
  5053. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  5054. ASTContext::GetBuiltinTypeError Error;
  5055. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  5056. if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
  5057. // The type of this function differs from the type of the builtin,
  5058. // so forget about the builtin entirely.
  5059. Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
  5060. }
  5061. }
  5062. // If this function is declared as being extern "C", then check to see if
  5063. // the function returns a UDT (class, struct, or union type) that is not C
  5064. // compatible, and if it does, warn the user.
  5065. if (NewFD->isExternC()) {
  5066. QualType R = NewFD->getResultType();
  5067. if (!R.isPODType(Context) &&
  5068. !R->isVoidType())
  5069. Diag( NewFD->getLocation(), diag::warn_return_value_udt )
  5070. << NewFD << R;
  5071. }
  5072. }
  5073. return Redeclaration;
  5074. }
  5075. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  5076. // C++11 [basic.start.main]p3: A program that declares main to be inline,
  5077. // static or constexpr is ill-formed.
  5078. // C99 6.7.4p4: In a hosted environment, the inline function specifier
  5079. // shall not appear in a declaration of main.
  5080. // static main is not an error under C99, but we should warn about it.
  5081. if (FD->getStorageClass() == SC_Static)
  5082. Diag(DS.getStorageClassSpecLoc(), getLangOptions().CPlusPlus
  5083. ? diag::err_static_main : diag::warn_static_main)
  5084. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  5085. if (FD->isInlineSpecified())
  5086. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  5087. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  5088. if (FD->isConstexpr()) {
  5089. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  5090. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  5091. FD->setConstexpr(false);
  5092. }
  5093. QualType T = FD->getType();
  5094. assert(T->isFunctionType() && "function decl is not of function type");
  5095. const FunctionType* FT = T->getAs<FunctionType>();
  5096. if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
  5097. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
  5098. FD->setInvalidDecl(true);
  5099. }
  5100. // Treat protoless main() as nullary.
  5101. if (isa<FunctionNoProtoType>(FT)) return;
  5102. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  5103. unsigned nparams = FTP->getNumArgs();
  5104. assert(FD->getNumParams() == nparams);
  5105. bool HasExtraParameters = (nparams > 3);
  5106. // Darwin passes an undocumented fourth argument of type char**. If
  5107. // other platforms start sprouting these, the logic below will start
  5108. // getting shifty.
  5109. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  5110. HasExtraParameters = false;
  5111. if (HasExtraParameters) {
  5112. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  5113. FD->setInvalidDecl(true);
  5114. nparams = 3;
  5115. }
  5116. // FIXME: a lot of the following diagnostics would be improved
  5117. // if we had some location information about types.
  5118. QualType CharPP =
  5119. Context.getPointerType(Context.getPointerType(Context.CharTy));
  5120. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  5121. for (unsigned i = 0; i < nparams; ++i) {
  5122. QualType AT = FTP->getArgType(i);
  5123. bool mismatch = true;
  5124. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  5125. mismatch = false;
  5126. else if (Expected[i] == CharPP) {
  5127. // As an extension, the following forms are okay:
  5128. // char const **
  5129. // char const * const *
  5130. // char * const *
  5131. QualifierCollector qs;
  5132. const PointerType* PT;
  5133. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  5134. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  5135. (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
  5136. qs.removeConst();
  5137. mismatch = !qs.empty();
  5138. }
  5139. }
  5140. if (mismatch) {
  5141. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  5142. // TODO: suggest replacing given type with expected type
  5143. FD->setInvalidDecl(true);
  5144. }
  5145. }
  5146. if (nparams == 1 && !FD->isInvalidDecl()) {
  5147. Diag(FD->getLocation(), diag::warn_main_one_arg);
  5148. }
  5149. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  5150. Diag(FD->getLocation(), diag::err_main_template_decl);
  5151. FD->setInvalidDecl();
  5152. }
  5153. }
  5154. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  5155. // FIXME: Need strict checking. In C89, we need to check for
  5156. // any assignment, increment, decrement, function-calls, or
  5157. // commas outside of a sizeof. In C99, it's the same list,
  5158. // except that the aforementioned are allowed in unevaluated
  5159. // expressions. Everything else falls under the
  5160. // "may accept other forms of constant expressions" exception.
  5161. // (We never end up here for C++, so the constant expression
  5162. // rules there don't matter.)
  5163. if (Init->isConstantInitializer(Context, false))
  5164. return false;
  5165. Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
  5166. << Init->getSourceRange();
  5167. return true;
  5168. }
  5169. namespace {
  5170. // Visits an initialization expression to see if OrigDecl is evaluated in
  5171. // its own initialization and throws a warning if it does.
  5172. class SelfReferenceChecker
  5173. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  5174. Sema &S;
  5175. Decl *OrigDecl;
  5176. bool isRecordType;
  5177. bool isPODType;
  5178. public:
  5179. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  5180. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  5181. S(S), OrigDecl(OrigDecl) {
  5182. isPODType = false;
  5183. isRecordType = false;
  5184. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  5185. isPODType = VD->getType().isPODType(S.Context);
  5186. isRecordType = VD->getType()->isRecordType();
  5187. }
  5188. }
  5189. void VisitExpr(Expr *E) {
  5190. if (isa<ObjCMessageExpr>(*E)) return;
  5191. if (isRecordType) {
  5192. Expr *expr = E;
  5193. if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  5194. ValueDecl *VD = ME->getMemberDecl();
  5195. if (isa<EnumConstantDecl>(VD) || isa<VarDecl>(VD)) return;
  5196. expr = ME->getBase();
  5197. }
  5198. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(expr)) {
  5199. HandleDeclRefExpr(DRE);
  5200. return;
  5201. }
  5202. }
  5203. Inherited::VisitExpr(E);
  5204. }
  5205. void VisitMemberExpr(MemberExpr *E) {
  5206. if (E->getType()->canDecayToPointerType()) return;
  5207. if (isa<FieldDecl>(E->getMemberDecl()))
  5208. if (DeclRefExpr *DRE
  5209. = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
  5210. HandleDeclRefExpr(DRE);
  5211. return;
  5212. }
  5213. Inherited::VisitMemberExpr(E);
  5214. }
  5215. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  5216. if ((!isRecordType &&E->getCastKind() == CK_LValueToRValue) ||
  5217. (isRecordType && E->getCastKind() == CK_NoOp)) {
  5218. Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
  5219. if (MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr))
  5220. SubExpr = ME->getBase()->IgnoreParenImpCasts();
  5221. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
  5222. HandleDeclRefExpr(DRE);
  5223. return;
  5224. }
  5225. }
  5226. Inherited::VisitImplicitCastExpr(E);
  5227. }
  5228. void VisitUnaryOperator(UnaryOperator *E) {
  5229. // For POD record types, addresses of its own members are well-defined.
  5230. if (isRecordType && isPODType) return;
  5231. Inherited::VisitUnaryOperator(E);
  5232. }
  5233. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  5234. Decl* ReferenceDecl = DRE->getDecl();
  5235. if (OrigDecl != ReferenceDecl) return;
  5236. LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
  5237. Sema::NotForRedeclaration);
  5238. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  5239. S.PDiag(diag::warn_uninit_self_reference_in_init)
  5240. << Result.getLookupName()
  5241. << OrigDecl->getLocation()
  5242. << DRE->getSourceRange());
  5243. }
  5244. };
  5245. }
  5246. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  5247. void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
  5248. SelfReferenceChecker(*this, OrigDecl).VisitExpr(E);
  5249. }
  5250. /// AddInitializerToDecl - Adds the initializer Init to the
  5251. /// declaration dcl. If DirectInit is true, this is C++ direct
  5252. /// initialization rather than copy initialization.
  5253. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
  5254. bool DirectInit, bool TypeMayContainAuto) {
  5255. // If there is no declaration, there was an error parsing it. Just ignore
  5256. // the initializer.
  5257. if (RealDecl == 0 || RealDecl->isInvalidDecl())
  5258. return;
  5259. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  5260. // With declarators parsed the way they are, the parser cannot
  5261. // distinguish between a normal initializer and a pure-specifier.
  5262. // Thus this grotesque test.
  5263. IntegerLiteral *IL;
  5264. if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
  5265. Context.getCanonicalType(IL->getType()) == Context.IntTy)
  5266. CheckPureMethod(Method, Init->getSourceRange());
  5267. else {
  5268. Diag(Method->getLocation(), diag::err_member_function_initialization)
  5269. << Method->getDeclName() << Init->getSourceRange();
  5270. Method->setInvalidDecl();
  5271. }
  5272. return;
  5273. }
  5274. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  5275. if (!VDecl) {
  5276. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  5277. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  5278. RealDecl->setInvalidDecl();
  5279. return;
  5280. }
  5281. // Check for self-references within variable initializers.
  5282. // Variables declared within a function/method body are handled
  5283. // by a dataflow analysis.
  5284. if (!VDecl->hasLocalStorage() && !VDecl->isStaticLocal())
  5285. CheckSelfReference(RealDecl, Init);
  5286. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  5287. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  5288. if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
  5289. Expr *DeduceInit = Init;
  5290. // Initializer could be a C++ direct-initializer. Deduction only works if it
  5291. // contains exactly one expression.
  5292. if (CXXDirectInit) {
  5293. if (CXXDirectInit->getNumExprs() == 0) {
  5294. // It isn't possible to write this directly, but it is possible to
  5295. // end up in this situation with "auto x(some_pack...);"
  5296. Diag(CXXDirectInit->getSourceRange().getBegin(),
  5297. diag::err_auto_var_init_no_expression)
  5298. << VDecl->getDeclName() << VDecl->getType()
  5299. << VDecl->getSourceRange();
  5300. RealDecl->setInvalidDecl();
  5301. return;
  5302. } else if (CXXDirectInit->getNumExprs() > 1) {
  5303. Diag(CXXDirectInit->getExpr(1)->getSourceRange().getBegin(),
  5304. diag::err_auto_var_init_multiple_expressions)
  5305. << VDecl->getDeclName() << VDecl->getType()
  5306. << VDecl->getSourceRange();
  5307. RealDecl->setInvalidDecl();
  5308. return;
  5309. } else {
  5310. DeduceInit = CXXDirectInit->getExpr(0);
  5311. }
  5312. }
  5313. TypeSourceInfo *DeducedType = 0;
  5314. if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
  5315. DAR_Failed)
  5316. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  5317. if (!DeducedType) {
  5318. RealDecl->setInvalidDecl();
  5319. return;
  5320. }
  5321. VDecl->setTypeSourceInfo(DeducedType);
  5322. VDecl->setType(DeducedType->getType());
  5323. // In ARC, infer lifetime.
  5324. if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  5325. VDecl->setInvalidDecl();
  5326. // If this is a redeclaration, check that the type we just deduced matches
  5327. // the previously declared type.
  5328. if (VarDecl *Old = VDecl->getPreviousDecl())
  5329. MergeVarDeclTypes(VDecl, Old);
  5330. }
  5331. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  5332. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  5333. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  5334. VDecl->setInvalidDecl();
  5335. return;
  5336. }
  5337. if (!VDecl->getType()->isDependentType()) {
  5338. // A definition must end up with a complete type, which means it must be
  5339. // complete with the restriction that an array type might be completed by
  5340. // the initializer; note that later code assumes this restriction.
  5341. QualType BaseDeclType = VDecl->getType();
  5342. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  5343. BaseDeclType = Array->getElementType();
  5344. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  5345. diag::err_typecheck_decl_incomplete_type)) {
  5346. RealDecl->setInvalidDecl();
  5347. return;
  5348. }
  5349. // The variable can not have an abstract class type.
  5350. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  5351. diag::err_abstract_type_in_decl,
  5352. AbstractVariableType))
  5353. VDecl->setInvalidDecl();
  5354. }
  5355. const VarDecl *Def;
  5356. if ((Def = VDecl->getDefinition()) && Def != VDecl) {
  5357. Diag(VDecl->getLocation(), diag::err_redefinition)
  5358. << VDecl->getDeclName();
  5359. Diag(Def->getLocation(), diag::note_previous_definition);
  5360. VDecl->setInvalidDecl();
  5361. return;
  5362. }
  5363. const VarDecl* PrevInit = 0;
  5364. if (getLangOptions().CPlusPlus) {
  5365. // C++ [class.static.data]p4
  5366. // If a static data member is of const integral or const
  5367. // enumeration type, its declaration in the class definition can
  5368. // specify a constant-initializer which shall be an integral
  5369. // constant expression (5.19). In that case, the member can appear
  5370. // in integral constant expressions. The member shall still be
  5371. // defined in a namespace scope if it is used in the program and the
  5372. // namespace scope definition shall not contain an initializer.
  5373. //
  5374. // We already performed a redefinition check above, but for static
  5375. // data members we also need to check whether there was an in-class
  5376. // declaration with an initializer.
  5377. if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
  5378. Diag(VDecl->getLocation(), diag::err_redefinition)
  5379. << VDecl->getDeclName();
  5380. Diag(PrevInit->getLocation(), diag::note_previous_definition);
  5381. return;
  5382. }
  5383. if (VDecl->hasLocalStorage())
  5384. getCurFunction()->setHasBranchProtectedScope();
  5385. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  5386. VDecl->setInvalidDecl();
  5387. return;
  5388. }
  5389. }
  5390. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  5391. // a kernel function cannot be initialized."
  5392. if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
  5393. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  5394. VDecl->setInvalidDecl();
  5395. return;
  5396. }
  5397. // Get the decls type and save a reference for later, since
  5398. // CheckInitializerTypes may change it.
  5399. QualType DclT = VDecl->getType(), SavT = DclT;
  5400. // Perform the initialization.
  5401. if (!VDecl->isInvalidDecl()) {
  5402. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  5403. InitializationKind Kind
  5404. = DirectInit ?
  5405. CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
  5406. Init->getLocStart(),
  5407. Init->getLocEnd())
  5408. : InitializationKind::CreateDirectList(
  5409. VDecl->getLocation())
  5410. : InitializationKind::CreateCopy(VDecl->getLocation(),
  5411. Init->getLocStart());
  5412. Expr **Args = &Init;
  5413. unsigned NumArgs = 1;
  5414. if (CXXDirectInit) {
  5415. Args = CXXDirectInit->getExprs();
  5416. NumArgs = CXXDirectInit->getNumExprs();
  5417. }
  5418. InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
  5419. ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
  5420. MultiExprArg(*this, Args,NumArgs),
  5421. &DclT);
  5422. if (Result.isInvalid()) {
  5423. VDecl->setInvalidDecl();
  5424. return;
  5425. }
  5426. Init = Result.takeAs<Expr>();
  5427. }
  5428. // If the type changed, it means we had an incomplete type that was
  5429. // completed by the initializer. For example:
  5430. // int ary[] = { 1, 3, 5 };
  5431. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  5432. if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
  5433. VDecl->setType(DclT);
  5434. Init->setType(DclT.getNonReferenceType());
  5435. }
  5436. // Check any implicit conversions within the expression.
  5437. CheckImplicitConversions(Init, VDecl->getLocation());
  5438. if (!VDecl->isInvalidDecl())
  5439. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  5440. Init = MaybeCreateExprWithCleanups(Init);
  5441. // Attach the initializer to the decl.
  5442. VDecl->setInit(Init);
  5443. if (VDecl->isLocalVarDecl()) {
  5444. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  5445. // static storage duration shall be constant expressions or string literals.
  5446. // C++ does not have this restriction.
  5447. if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl() &&
  5448. VDecl->getStorageClass() == SC_Static)
  5449. CheckForConstantInitializer(Init, DclT);
  5450. } else if (VDecl->isStaticDataMember() &&
  5451. VDecl->getLexicalDeclContext()->isRecord()) {
  5452. // This is an in-class initialization for a static data member, e.g.,
  5453. //
  5454. // struct S {
  5455. // static const int value = 17;
  5456. // };
  5457. // C++ [class.mem]p4:
  5458. // A member-declarator can contain a constant-initializer only
  5459. // if it declares a static member (9.4) of const integral or
  5460. // const enumeration type, see 9.4.2.
  5461. //
  5462. // C++11 [class.static.data]p3:
  5463. // If a non-volatile const static data member is of integral or
  5464. // enumeration type, its declaration in the class definition can
  5465. // specify a brace-or-equal-initializer in which every initalizer-clause
  5466. // that is an assignment-expression is a constant expression. A static
  5467. // data member of literal type can be declared in the class definition
  5468. // with the constexpr specifier; if so, its declaration shall specify a
  5469. // brace-or-equal-initializer in which every initializer-clause that is
  5470. // an assignment-expression is a constant expression.
  5471. // Do nothing on dependent types.
  5472. if (DclT->isDependentType()) {
  5473. // Allow any 'static constexpr' members, whether or not they are of literal
  5474. // type. We separately check that every constexpr variable is of literal
  5475. // type.
  5476. } else if (VDecl->isConstexpr()) {
  5477. // Require constness.
  5478. } else if (!DclT.isConstQualified()) {
  5479. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  5480. << Init->getSourceRange();
  5481. VDecl->setInvalidDecl();
  5482. // We allow integer constant expressions in all cases.
  5483. } else if (DclT->isIntegralOrEnumerationType()) {
  5484. // Check whether the expression is a constant expression.
  5485. SourceLocation Loc;
  5486. if (getLangOptions().CPlusPlus0x && DclT.isVolatileQualified())
  5487. // In C++11, a non-constexpr const static data member with an
  5488. // in-class initializer cannot be volatile.
  5489. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  5490. else if (Init->isValueDependent())
  5491. ; // Nothing to check.
  5492. else if (Init->isIntegerConstantExpr(Context, &Loc))
  5493. ; // Ok, it's an ICE!
  5494. else if (Init->isEvaluatable(Context)) {
  5495. // If we can constant fold the initializer through heroics, accept it,
  5496. // but report this as a use of an extension for -pedantic.
  5497. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  5498. << Init->getSourceRange();
  5499. } else {
  5500. // Otherwise, this is some crazy unknown case. Report the issue at the
  5501. // location provided by the isIntegerConstantExpr failed check.
  5502. Diag(Loc, diag::err_in_class_initializer_non_constant)
  5503. << Init->getSourceRange();
  5504. VDecl->setInvalidDecl();
  5505. }
  5506. // We allow foldable floating-point constants as an extension.
  5507. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  5508. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  5509. << DclT << Init->getSourceRange();
  5510. if (getLangOptions().CPlusPlus0x)
  5511. Diag(VDecl->getLocation(),
  5512. diag::note_in_class_initializer_float_type_constexpr)
  5513. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  5514. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  5515. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  5516. << Init->getSourceRange();
  5517. VDecl->setInvalidDecl();
  5518. }
  5519. // Suggest adding 'constexpr' in C++11 for literal types.
  5520. } else if (getLangOptions().CPlusPlus0x && DclT->isLiteralType()) {
  5521. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  5522. << DclT << Init->getSourceRange()
  5523. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  5524. VDecl->setConstexpr(true);
  5525. } else {
  5526. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  5527. << DclT << Init->getSourceRange();
  5528. VDecl->setInvalidDecl();
  5529. }
  5530. } else if (VDecl->isFileVarDecl()) {
  5531. if (VDecl->getStorageClassAsWritten() == SC_Extern &&
  5532. (!getLangOptions().CPlusPlus ||
  5533. !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
  5534. Diag(VDecl->getLocation(), diag::warn_extern_init);
  5535. // C99 6.7.8p4. All file scoped initializers need to be constant.
  5536. if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl())
  5537. CheckForConstantInitializer(Init, DclT);
  5538. }
  5539. // We will represent direct-initialization similarly to copy-initialization:
  5540. // int x(1); -as-> int x = 1;
  5541. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  5542. //
  5543. // Clients that want to distinguish between the two forms, can check for
  5544. // direct initializer using VarDecl::getInitStyle().
  5545. // A major benefit is that clients that don't particularly care about which
  5546. // exactly form was it (like the CodeGen) can handle both cases without
  5547. // special case code.
  5548. // C++ 8.5p11:
  5549. // The form of initialization (using parentheses or '=') is generally
  5550. // insignificant, but does matter when the entity being initialized has a
  5551. // class type.
  5552. if (CXXDirectInit) {
  5553. assert(DirectInit && "Call-style initializer must be direct init.");
  5554. VDecl->setInitStyle(VarDecl::CallInit);
  5555. } else if (DirectInit) {
  5556. // This must be list-initialization. No other way is direct-initialization.
  5557. VDecl->setInitStyle(VarDecl::ListInit);
  5558. }
  5559. CheckCompleteVariableDeclaration(VDecl);
  5560. }
  5561. /// ActOnInitializerError - Given that there was an error parsing an
  5562. /// initializer for the given declaration, try to return to some form
  5563. /// of sanity.
  5564. void Sema::ActOnInitializerError(Decl *D) {
  5565. // Our main concern here is re-establishing invariants like "a
  5566. // variable's type is either dependent or complete".
  5567. if (!D || D->isInvalidDecl()) return;
  5568. VarDecl *VD = dyn_cast<VarDecl>(D);
  5569. if (!VD) return;
  5570. // Auto types are meaningless if we can't make sense of the initializer.
  5571. if (ParsingInitForAutoVars.count(D)) {
  5572. D->setInvalidDecl();
  5573. return;
  5574. }
  5575. QualType Ty = VD->getType();
  5576. if (Ty->isDependentType()) return;
  5577. // Require a complete type.
  5578. if (RequireCompleteType(VD->getLocation(),
  5579. Context.getBaseElementType(Ty),
  5580. diag::err_typecheck_decl_incomplete_type)) {
  5581. VD->setInvalidDecl();
  5582. return;
  5583. }
  5584. // Require an abstract type.
  5585. if (RequireNonAbstractType(VD->getLocation(), Ty,
  5586. diag::err_abstract_type_in_decl,
  5587. AbstractVariableType)) {
  5588. VD->setInvalidDecl();
  5589. return;
  5590. }
  5591. // Don't bother complaining about constructors or destructors,
  5592. // though.
  5593. }
  5594. void Sema::ActOnUninitializedDecl(Decl *RealDecl,
  5595. bool TypeMayContainAuto) {
  5596. // If there is no declaration, there was an error parsing it. Just ignore it.
  5597. if (RealDecl == 0)
  5598. return;
  5599. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  5600. QualType Type = Var->getType();
  5601. // C++11 [dcl.spec.auto]p3
  5602. if (TypeMayContainAuto && Type->getContainedAutoType()) {
  5603. Diag(Var->getLocation(), diag::err_auto_var_requires_init)
  5604. << Var->getDeclName() << Type;
  5605. Var->setInvalidDecl();
  5606. return;
  5607. }
  5608. // C++11 [class.static.data]p3: A static data member can be declared with
  5609. // the constexpr specifier; if so, its declaration shall specify
  5610. // a brace-or-equal-initializer.
  5611. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  5612. // the definition of a variable [...] or the declaration of a static data
  5613. // member.
  5614. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
  5615. if (Var->isStaticDataMember())
  5616. Diag(Var->getLocation(),
  5617. diag::err_constexpr_static_mem_var_requires_init)
  5618. << Var->getDeclName();
  5619. else
  5620. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  5621. Var->setInvalidDecl();
  5622. return;
  5623. }
  5624. switch (Var->isThisDeclarationADefinition()) {
  5625. case VarDecl::Definition:
  5626. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  5627. break;
  5628. // We have an out-of-line definition of a static data member
  5629. // that has an in-class initializer, so we type-check this like
  5630. // a declaration.
  5631. //
  5632. // Fall through
  5633. case VarDecl::DeclarationOnly:
  5634. // It's only a declaration.
  5635. // Block scope. C99 6.7p7: If an identifier for an object is
  5636. // declared with no linkage (C99 6.2.2p6), the type for the
  5637. // object shall be complete.
  5638. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  5639. !Var->getLinkage() && !Var->isInvalidDecl() &&
  5640. RequireCompleteType(Var->getLocation(), Type,
  5641. diag::err_typecheck_decl_incomplete_type))
  5642. Var->setInvalidDecl();
  5643. // Make sure that the type is not abstract.
  5644. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  5645. RequireNonAbstractType(Var->getLocation(), Type,
  5646. diag::err_abstract_type_in_decl,
  5647. AbstractVariableType))
  5648. Var->setInvalidDecl();
  5649. return;
  5650. case VarDecl::TentativeDefinition:
  5651. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  5652. // object that has file scope without an initializer, and without a
  5653. // storage-class specifier or with the storage-class specifier "static",
  5654. // constitutes a tentative definition. Note: A tentative definition with
  5655. // external linkage is valid (C99 6.2.2p5).
  5656. if (!Var->isInvalidDecl()) {
  5657. if (const IncompleteArrayType *ArrayT
  5658. = Context.getAsIncompleteArrayType(Type)) {
  5659. if (RequireCompleteType(Var->getLocation(),
  5660. ArrayT->getElementType(),
  5661. diag::err_illegal_decl_array_incomplete_type))
  5662. Var->setInvalidDecl();
  5663. } else if (Var->getStorageClass() == SC_Static) {
  5664. // C99 6.9.2p3: If the declaration of an identifier for an object is
  5665. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  5666. // declared type shall not be an incomplete type.
  5667. // NOTE: code such as the following
  5668. // static struct s;
  5669. // struct s { int a; };
  5670. // is accepted by gcc. Hence here we issue a warning instead of
  5671. // an error and we do not invalidate the static declaration.
  5672. // NOTE: to avoid multiple warnings, only check the first declaration.
  5673. if (Var->getPreviousDecl() == 0)
  5674. RequireCompleteType(Var->getLocation(), Type,
  5675. diag::ext_typecheck_decl_incomplete_type);
  5676. }
  5677. }
  5678. // Record the tentative definition; we're done.
  5679. if (!Var->isInvalidDecl())
  5680. TentativeDefinitions.push_back(Var);
  5681. return;
  5682. }
  5683. // Provide a specific diagnostic for uninitialized variable
  5684. // definitions with incomplete array type.
  5685. if (Type->isIncompleteArrayType()) {
  5686. Diag(Var->getLocation(),
  5687. diag::err_typecheck_incomplete_array_needs_initializer);
  5688. Var->setInvalidDecl();
  5689. return;
  5690. }
  5691. // Provide a specific diagnostic for uninitialized variable
  5692. // definitions with reference type.
  5693. if (Type->isReferenceType()) {
  5694. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  5695. << Var->getDeclName()
  5696. << SourceRange(Var->getLocation(), Var->getLocation());
  5697. Var->setInvalidDecl();
  5698. return;
  5699. }
  5700. // Do not attempt to type-check the default initializer for a
  5701. // variable with dependent type.
  5702. if (Type->isDependentType())
  5703. return;
  5704. if (Var->isInvalidDecl())
  5705. return;
  5706. if (RequireCompleteType(Var->getLocation(),
  5707. Context.getBaseElementType(Type),
  5708. diag::err_typecheck_decl_incomplete_type)) {
  5709. Var->setInvalidDecl();
  5710. return;
  5711. }
  5712. // The variable can not have an abstract class type.
  5713. if (RequireNonAbstractType(Var->getLocation(), Type,
  5714. diag::err_abstract_type_in_decl,
  5715. AbstractVariableType)) {
  5716. Var->setInvalidDecl();
  5717. return;
  5718. }
  5719. // Check for jumps past the implicit initializer. C++0x
  5720. // clarifies that this applies to a "variable with automatic
  5721. // storage duration", not a "local variable".
  5722. // C++11 [stmt.dcl]p3
  5723. // A program that jumps from a point where a variable with automatic
  5724. // storage duration is not in scope to a point where it is in scope is
  5725. // ill-formed unless the variable has scalar type, class type with a
  5726. // trivial default constructor and a trivial destructor, a cv-qualified
  5727. // version of one of these types, or an array of one of the preceding
  5728. // types and is declared without an initializer.
  5729. if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) {
  5730. if (const RecordType *Record
  5731. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  5732. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  5733. // Mark the function for further checking even if the looser rules of
  5734. // C++11 do not require such checks, so that we can diagnose
  5735. // incompatibilities with C++98.
  5736. if (!CXXRecord->isPOD())
  5737. getCurFunction()->setHasBranchProtectedScope();
  5738. }
  5739. }
  5740. // C++03 [dcl.init]p9:
  5741. // If no initializer is specified for an object, and the
  5742. // object is of (possibly cv-qualified) non-POD class type (or
  5743. // array thereof), the object shall be default-initialized; if
  5744. // the object is of const-qualified type, the underlying class
  5745. // type shall have a user-declared default
  5746. // constructor. Otherwise, if no initializer is specified for
  5747. // a non- static object, the object and its subobjects, if
  5748. // any, have an indeterminate initial value); if the object
  5749. // or any of its subobjects are of const-qualified type, the
  5750. // program is ill-formed.
  5751. // C++0x [dcl.init]p11:
  5752. // If no initializer is specified for an object, the object is
  5753. // default-initialized; [...].
  5754. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  5755. InitializationKind Kind
  5756. = InitializationKind::CreateDefault(Var->getLocation());
  5757. InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
  5758. ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
  5759. MultiExprArg(*this, 0, 0));
  5760. if (Init.isInvalid())
  5761. Var->setInvalidDecl();
  5762. else if (Init.get()) {
  5763. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  5764. // This is important for template substitution.
  5765. Var->setInitStyle(VarDecl::CallInit);
  5766. }
  5767. CheckCompleteVariableDeclaration(Var);
  5768. }
  5769. }
  5770. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  5771. VarDecl *VD = dyn_cast<VarDecl>(D);
  5772. if (!VD) {
  5773. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  5774. D->setInvalidDecl();
  5775. return;
  5776. }
  5777. VD->setCXXForRangeDecl(true);
  5778. // for-range-declaration cannot be given a storage class specifier.
  5779. int Error = -1;
  5780. switch (VD->getStorageClassAsWritten()) {
  5781. case SC_None:
  5782. break;
  5783. case SC_Extern:
  5784. Error = 0;
  5785. break;
  5786. case SC_Static:
  5787. Error = 1;
  5788. break;
  5789. case SC_PrivateExtern:
  5790. Error = 2;
  5791. break;
  5792. case SC_Auto:
  5793. Error = 3;
  5794. break;
  5795. case SC_Register:
  5796. Error = 4;
  5797. break;
  5798. case SC_OpenCLWorkGroupLocal:
  5799. llvm_unreachable("Unexpected storage class");
  5800. }
  5801. if (VD->isConstexpr())
  5802. Error = 5;
  5803. if (Error != -1) {
  5804. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  5805. << VD->getDeclName() << Error;
  5806. D->setInvalidDecl();
  5807. }
  5808. }
  5809. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  5810. if (var->isInvalidDecl()) return;
  5811. // In ARC, don't allow jumps past the implicit initialization of a
  5812. // local retaining variable.
  5813. if (getLangOptions().ObjCAutoRefCount &&
  5814. var->hasLocalStorage()) {
  5815. switch (var->getType().getObjCLifetime()) {
  5816. case Qualifiers::OCL_None:
  5817. case Qualifiers::OCL_ExplicitNone:
  5818. case Qualifiers::OCL_Autoreleasing:
  5819. break;
  5820. case Qualifiers::OCL_Weak:
  5821. case Qualifiers::OCL_Strong:
  5822. getCurFunction()->setHasBranchProtectedScope();
  5823. break;
  5824. }
  5825. }
  5826. // All the following checks are C++ only.
  5827. if (!getLangOptions().CPlusPlus) return;
  5828. QualType baseType = Context.getBaseElementType(var->getType());
  5829. if (baseType->isDependentType()) return;
  5830. // __block variables might require us to capture a copy-initializer.
  5831. if (var->hasAttr<BlocksAttr>()) {
  5832. // It's currently invalid to ever have a __block variable with an
  5833. // array type; should we diagnose that here?
  5834. // Regardless, we don't want to ignore array nesting when
  5835. // constructing this copy.
  5836. QualType type = var->getType();
  5837. if (type->isStructureOrClassType()) {
  5838. SourceLocation poi = var->getLocation();
  5839. Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi);
  5840. ExprResult result =
  5841. PerformCopyInitialization(
  5842. InitializedEntity::InitializeBlock(poi, type, false),
  5843. poi, Owned(varRef));
  5844. if (!result.isInvalid()) {
  5845. result = MaybeCreateExprWithCleanups(result);
  5846. Expr *init = result.takeAs<Expr>();
  5847. Context.setBlockVarCopyInits(var, init);
  5848. }
  5849. }
  5850. }
  5851. Expr *Init = var->getInit();
  5852. bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
  5853. if (!var->getDeclContext()->isDependentContext() && Init) {
  5854. if (IsGlobal && !var->isConstexpr() &&
  5855. getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
  5856. var->getLocation())
  5857. != DiagnosticsEngine::Ignored &&
  5858. !Init->isConstantInitializer(Context, baseType->isReferenceType()))
  5859. Diag(var->getLocation(), diag::warn_global_constructor)
  5860. << Init->getSourceRange();
  5861. if (var->isConstexpr()) {
  5862. llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
  5863. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  5864. SourceLocation DiagLoc = var->getLocation();
  5865. // If the note doesn't add any useful information other than a source
  5866. // location, fold it into the primary diagnostic.
  5867. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  5868. diag::note_invalid_subexpr_in_const_expr) {
  5869. DiagLoc = Notes[0].first;
  5870. Notes.clear();
  5871. }
  5872. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  5873. << var << Init->getSourceRange();
  5874. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  5875. Diag(Notes[I].first, Notes[I].second);
  5876. }
  5877. } else if (var->isUsableInConstantExpressions()) {
  5878. // Check whether the initializer of a const variable of integral or
  5879. // enumeration type is an ICE now, since we can't tell whether it was
  5880. // initialized by a constant expression if we check later.
  5881. var->checkInitIsICE();
  5882. }
  5883. }
  5884. // Require the destructor.
  5885. if (const RecordType *recordType = baseType->getAs<RecordType>())
  5886. FinalizeVarWithDestructor(var, recordType);
  5887. }
  5888. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  5889. /// any semantic actions necessary after any initializer has been attached.
  5890. void
  5891. Sema::FinalizeDeclaration(Decl *ThisDecl) {
  5892. // Note that we are no longer parsing the initializer for this declaration.
  5893. ParsingInitForAutoVars.erase(ThisDecl);
  5894. }
  5895. Sema::DeclGroupPtrTy
  5896. Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  5897. Decl **Group, unsigned NumDecls) {
  5898. SmallVector<Decl*, 8> Decls;
  5899. if (DS.isTypeSpecOwned())
  5900. Decls.push_back(DS.getRepAsDecl());
  5901. for (unsigned i = 0; i != NumDecls; ++i)
  5902. if (Decl *D = Group[i])
  5903. Decls.push_back(D);
  5904. return BuildDeclaratorGroup(Decls.data(), Decls.size(),
  5905. DS.getTypeSpecType() == DeclSpec::TST_auto);
  5906. }
  5907. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  5908. /// group, performing any necessary semantic checking.
  5909. Sema::DeclGroupPtrTy
  5910. Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
  5911. bool TypeMayContainAuto) {
  5912. // C++0x [dcl.spec.auto]p7:
  5913. // If the type deduced for the template parameter U is not the same in each
  5914. // deduction, the program is ill-formed.
  5915. // FIXME: When initializer-list support is added, a distinction is needed
  5916. // between the deduced type U and the deduced type which 'auto' stands for.
  5917. // auto a = 0, b = { 1, 2, 3 };
  5918. // is legal because the deduced type U is 'int' in both cases.
  5919. if (TypeMayContainAuto && NumDecls > 1) {
  5920. QualType Deduced;
  5921. CanQualType DeducedCanon;
  5922. VarDecl *DeducedDecl = 0;
  5923. for (unsigned i = 0; i != NumDecls; ++i) {
  5924. if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
  5925. AutoType *AT = D->getType()->getContainedAutoType();
  5926. // Don't reissue diagnostics when instantiating a template.
  5927. if (AT && D->isInvalidDecl())
  5928. break;
  5929. if (AT && AT->isDeduced()) {
  5930. QualType U = AT->getDeducedType();
  5931. CanQualType UCanon = Context.getCanonicalType(U);
  5932. if (Deduced.isNull()) {
  5933. Deduced = U;
  5934. DeducedCanon = UCanon;
  5935. DeducedDecl = D;
  5936. } else if (DeducedCanon != UCanon) {
  5937. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  5938. diag::err_auto_different_deductions)
  5939. << Deduced << DeducedDecl->getDeclName()
  5940. << U << D->getDeclName()
  5941. << DeducedDecl->getInit()->getSourceRange()
  5942. << D->getInit()->getSourceRange();
  5943. D->setInvalidDecl();
  5944. break;
  5945. }
  5946. }
  5947. }
  5948. }
  5949. }
  5950. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
  5951. }
  5952. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  5953. /// to introduce parameters into function prototype scope.
  5954. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  5955. const DeclSpec &DS = D.getDeclSpec();
  5956. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  5957. // C++03 [dcl.stc]p2 also permits 'auto'.
  5958. VarDecl::StorageClass StorageClass = SC_None;
  5959. VarDecl::StorageClass StorageClassAsWritten = SC_None;
  5960. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  5961. StorageClass = SC_Register;
  5962. StorageClassAsWritten = SC_Register;
  5963. } else if (getLangOptions().CPlusPlus &&
  5964. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  5965. StorageClass = SC_Auto;
  5966. StorageClassAsWritten = SC_Auto;
  5967. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  5968. Diag(DS.getStorageClassSpecLoc(),
  5969. diag::err_invalid_storage_class_in_func_decl);
  5970. D.getMutableDeclSpec().ClearStorageClassSpecs();
  5971. }
  5972. if (D.getDeclSpec().isThreadSpecified())
  5973. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  5974. if (D.getDeclSpec().isConstexprSpecified())
  5975. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5976. << 0;
  5977. DiagnoseFunctionSpecifiers(D);
  5978. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  5979. QualType parmDeclType = TInfo->getType();
  5980. if (getLangOptions().CPlusPlus) {
  5981. // Check that there are no default arguments inside the type of this
  5982. // parameter.
  5983. CheckExtraCXXDefaultArguments(D);
  5984. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  5985. if (D.getCXXScopeSpec().isSet()) {
  5986. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  5987. << D.getCXXScopeSpec().getRange();
  5988. D.getCXXScopeSpec().clear();
  5989. }
  5990. }
  5991. // Ensure we have a valid name
  5992. IdentifierInfo *II = 0;
  5993. if (D.hasName()) {
  5994. II = D.getIdentifier();
  5995. if (!II) {
  5996. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  5997. << GetNameForDeclarator(D).getName().getAsString();
  5998. D.setInvalidType(true);
  5999. }
  6000. }
  6001. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  6002. if (II) {
  6003. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  6004. ForRedeclaration);
  6005. LookupName(R, S);
  6006. if (R.isSingleResult()) {
  6007. NamedDecl *PrevDecl = R.getFoundDecl();
  6008. if (PrevDecl->isTemplateParameter()) {
  6009. // Maybe we will complain about the shadowed template parameter.
  6010. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  6011. // Just pretend that we didn't see the previous declaration.
  6012. PrevDecl = 0;
  6013. } else if (S->isDeclScope(PrevDecl)) {
  6014. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  6015. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  6016. // Recover by removing the name
  6017. II = 0;
  6018. D.SetIdentifier(0, D.getIdentifierLoc());
  6019. D.setInvalidType(true);
  6020. }
  6021. }
  6022. }
  6023. // Temporarily put parameter variables in the translation unit, not
  6024. // the enclosing context. This prevents them from accidentally
  6025. // looking like class members in C++.
  6026. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  6027. D.getSourceRange().getBegin(),
  6028. D.getIdentifierLoc(), II,
  6029. parmDeclType, TInfo,
  6030. StorageClass, StorageClassAsWritten);
  6031. if (D.isInvalidType())
  6032. New->setInvalidDecl();
  6033. assert(S->isFunctionPrototypeScope());
  6034. assert(S->getFunctionPrototypeDepth() >= 1);
  6035. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  6036. S->getNextFunctionPrototypeIndex());
  6037. // Add the parameter declaration into this scope.
  6038. S->AddDecl(New);
  6039. if (II)
  6040. IdResolver.AddDecl(New);
  6041. ProcessDeclAttributes(S, New, D);
  6042. if (D.getDeclSpec().isModulePrivateSpecified())
  6043. Diag(New->getLocation(), diag::err_module_private_local)
  6044. << 1 << New->getDeclName()
  6045. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  6046. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6047. if (New->hasAttr<BlocksAttr>()) {
  6048. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  6049. }
  6050. return New;
  6051. }
  6052. /// \brief Synthesizes a variable for a parameter arising from a
  6053. /// typedef.
  6054. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  6055. SourceLocation Loc,
  6056. QualType T) {
  6057. /* FIXME: setting StartLoc == Loc.
  6058. Would it be worth to modify callers so as to provide proper source
  6059. location for the unnamed parameters, embedding the parameter's type? */
  6060. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
  6061. T, Context.getTrivialTypeSourceInfo(T, Loc),
  6062. SC_None, SC_None, 0);
  6063. Param->setImplicit();
  6064. return Param;
  6065. }
  6066. void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
  6067. ParmVarDecl * const *ParamEnd) {
  6068. // Don't diagnose unused-parameter errors in template instantiations; we
  6069. // will already have done so in the template itself.
  6070. if (!ActiveTemplateInstantiations.empty())
  6071. return;
  6072. for (; Param != ParamEnd; ++Param) {
  6073. if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
  6074. !(*Param)->hasAttr<UnusedAttr>()) {
  6075. Diag((*Param)->getLocation(), diag::warn_unused_parameter)
  6076. << (*Param)->getDeclName();
  6077. }
  6078. }
  6079. }
  6080. void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
  6081. ParmVarDecl * const *ParamEnd,
  6082. QualType ReturnTy,
  6083. NamedDecl *D) {
  6084. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  6085. return;
  6086. // Warn if the return value is pass-by-value and larger than the specified
  6087. // threshold.
  6088. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  6089. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  6090. if (Size > LangOpts.NumLargeByValueCopy)
  6091. Diag(D->getLocation(), diag::warn_return_value_size)
  6092. << D->getDeclName() << Size;
  6093. }
  6094. // Warn if any parameter is pass-by-value and larger than the specified
  6095. // threshold.
  6096. for (; Param != ParamEnd; ++Param) {
  6097. QualType T = (*Param)->getType();
  6098. if (T->isDependentType() || !T.isPODType(Context))
  6099. continue;
  6100. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  6101. if (Size > LangOpts.NumLargeByValueCopy)
  6102. Diag((*Param)->getLocation(), diag::warn_parameter_size)
  6103. << (*Param)->getDeclName() << Size;
  6104. }
  6105. }
  6106. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  6107. SourceLocation NameLoc, IdentifierInfo *Name,
  6108. QualType T, TypeSourceInfo *TSInfo,
  6109. VarDecl::StorageClass StorageClass,
  6110. VarDecl::StorageClass StorageClassAsWritten) {
  6111. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  6112. if (getLangOptions().ObjCAutoRefCount &&
  6113. T.getObjCLifetime() == Qualifiers::OCL_None &&
  6114. T->isObjCLifetimeType()) {
  6115. Qualifiers::ObjCLifetime lifetime;
  6116. // Special cases for arrays:
  6117. // - if it's const, use __unsafe_unretained
  6118. // - otherwise, it's an error
  6119. if (T->isArrayType()) {
  6120. if (!T.isConstQualified()) {
  6121. DelayedDiagnostics.add(
  6122. sema::DelayedDiagnostic::makeForbiddenType(
  6123. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  6124. }
  6125. lifetime = Qualifiers::OCL_ExplicitNone;
  6126. } else {
  6127. lifetime = T->getObjCARCImplicitLifetime();
  6128. }
  6129. T = Context.getLifetimeQualifiedType(T, lifetime);
  6130. }
  6131. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  6132. Context.getAdjustedParameterType(T),
  6133. TSInfo,
  6134. StorageClass, StorageClassAsWritten,
  6135. 0);
  6136. // Parameters can not be abstract class types.
  6137. // For record types, this is done by the AbstractClassUsageDiagnoser once
  6138. // the class has been completely parsed.
  6139. if (!CurContext->isRecord() &&
  6140. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  6141. AbstractParamType))
  6142. New->setInvalidDecl();
  6143. // Parameter declarators cannot be interface types. All ObjC objects are
  6144. // passed by reference.
  6145. if (T->isObjCObjectType()) {
  6146. Diag(NameLoc,
  6147. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  6148. << FixItHint::CreateInsertion(NameLoc, "*");
  6149. T = Context.getObjCObjectPointerType(T);
  6150. New->setType(T);
  6151. }
  6152. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  6153. // duration shall not be qualified by an address-space qualifier."
  6154. // Since all parameters have automatic store duration, they can not have
  6155. // an address space.
  6156. if (T.getAddressSpace() != 0) {
  6157. Diag(NameLoc, diag::err_arg_with_address_space);
  6158. New->setInvalidDecl();
  6159. }
  6160. return New;
  6161. }
  6162. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  6163. SourceLocation LocAfterDecls) {
  6164. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  6165. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  6166. // for a K&R function.
  6167. if (!FTI.hasPrototype) {
  6168. for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
  6169. --i;
  6170. if (FTI.ArgInfo[i].Param == 0) {
  6171. SmallString<256> Code;
  6172. llvm::raw_svector_ostream(Code) << " int "
  6173. << FTI.ArgInfo[i].Ident->getName()
  6174. << ";\n";
  6175. Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
  6176. << FTI.ArgInfo[i].Ident
  6177. << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
  6178. // Implicitly declare the argument as type 'int' for lack of a better
  6179. // type.
  6180. AttributeFactory attrs;
  6181. DeclSpec DS(attrs);
  6182. const char* PrevSpec; // unused
  6183. unsigned DiagID; // unused
  6184. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
  6185. PrevSpec, DiagID);
  6186. Declarator ParamD(DS, Declarator::KNRTypeListContext);
  6187. ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
  6188. FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
  6189. }
  6190. }
  6191. }
  6192. }
  6193. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
  6194. Declarator &D) {
  6195. assert(getCurFunctionDecl() == 0 && "Function parsing confused");
  6196. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  6197. Scope *ParentScope = FnBodyScope->getParent();
  6198. D.setFunctionDefinitionKind(FDK_Definition);
  6199. Decl *DP = HandleDeclarator(ParentScope, D,
  6200. MultiTemplateParamsArg(*this));
  6201. return ActOnStartOfFunctionDef(FnBodyScope, DP);
  6202. }
  6203. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
  6204. // Don't warn about invalid declarations.
  6205. if (FD->isInvalidDecl())
  6206. return false;
  6207. // Or declarations that aren't global.
  6208. if (!FD->isGlobal())
  6209. return false;
  6210. // Don't warn about C++ member functions.
  6211. if (isa<CXXMethodDecl>(FD))
  6212. return false;
  6213. // Don't warn about 'main'.
  6214. if (FD->isMain())
  6215. return false;
  6216. // Don't warn about inline functions.
  6217. if (FD->isInlined())
  6218. return false;
  6219. // Don't warn about function templates.
  6220. if (FD->getDescribedFunctionTemplate())
  6221. return false;
  6222. // Don't warn about function template specializations.
  6223. if (FD->isFunctionTemplateSpecialization())
  6224. return false;
  6225. bool MissingPrototype = true;
  6226. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  6227. Prev; Prev = Prev->getPreviousDecl()) {
  6228. // Ignore any declarations that occur in function or method
  6229. // scope, because they aren't visible from the header.
  6230. if (Prev->getDeclContext()->isFunctionOrMethod())
  6231. continue;
  6232. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  6233. break;
  6234. }
  6235. return MissingPrototype;
  6236. }
  6237. void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
  6238. // Don't complain if we're in GNU89 mode and the previous definition
  6239. // was an extern inline function.
  6240. const FunctionDecl *Definition;
  6241. if (FD->isDefined(Definition) &&
  6242. !canRedefineFunction(Definition, getLangOptions())) {
  6243. if (getLangOptions().GNUMode && Definition->isInlineSpecified() &&
  6244. Definition->getStorageClass() == SC_Extern)
  6245. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  6246. << FD->getDeclName() << getLangOptions().CPlusPlus;
  6247. else
  6248. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  6249. Diag(Definition->getLocation(), diag::note_previous_definition);
  6250. }
  6251. }
  6252. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
  6253. // Clear the last template instantiation error context.
  6254. LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
  6255. if (!D)
  6256. return D;
  6257. FunctionDecl *FD = 0;
  6258. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  6259. FD = FunTmpl->getTemplatedDecl();
  6260. else
  6261. FD = cast<FunctionDecl>(D);
  6262. // Enter a new function scope
  6263. PushFunctionScope();
  6264. // See if this is a redefinition.
  6265. if (!FD->isLateTemplateParsed())
  6266. CheckForFunctionRedefinition(FD);
  6267. // Builtin functions cannot be defined.
  6268. if (unsigned BuiltinID = FD->getBuiltinID()) {
  6269. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  6270. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  6271. FD->setInvalidDecl();
  6272. }
  6273. }
  6274. // The return type of a function definition must be complete
  6275. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  6276. QualType ResultType = FD->getResultType();
  6277. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  6278. !FD->isInvalidDecl() &&
  6279. RequireCompleteType(FD->getLocation(), ResultType,
  6280. diag::err_func_def_incomplete_result))
  6281. FD->setInvalidDecl();
  6282. // GNU warning -Wmissing-prototypes:
  6283. // Warn if a global function is defined without a previous
  6284. // prototype declaration. This warning is issued even if the
  6285. // definition itself provides a prototype. The aim is to detect
  6286. // global functions that fail to be declared in header files.
  6287. if (ShouldWarnAboutMissingPrototype(FD))
  6288. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  6289. if (FnBodyScope)
  6290. PushDeclContext(FnBodyScope, FD);
  6291. // Check the validity of our function parameters
  6292. CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
  6293. /*CheckParameterNames=*/true);
  6294. // Introduce our parameters into the function scope
  6295. for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
  6296. ParmVarDecl *Param = FD->getParamDecl(p);
  6297. Param->setOwningFunction(FD);
  6298. // If this has an identifier, add it to the scope stack.
  6299. if (Param->getIdentifier() && FnBodyScope) {
  6300. CheckShadow(FnBodyScope, Param);
  6301. PushOnScopeChains(Param, FnBodyScope);
  6302. }
  6303. }
  6304. // Checking attributes of current function definition
  6305. // dllimport attribute.
  6306. DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
  6307. if (DA && (!FD->getAttr<DLLExportAttr>())) {
  6308. // dllimport attribute cannot be directly applied to definition.
  6309. // Microsoft accepts dllimport for functions defined within class scope.
  6310. if (!DA->isInherited() &&
  6311. !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
  6312. Diag(FD->getLocation(),
  6313. diag::err_attribute_can_be_applied_only_to_symbol_declaration)
  6314. << "dllimport";
  6315. FD->setInvalidDecl();
  6316. return FD;
  6317. }
  6318. // Visual C++ appears to not think this is an issue, so only issue
  6319. // a warning when Microsoft extensions are disabled.
  6320. if (!LangOpts.MicrosoftExt) {
  6321. // If a symbol previously declared dllimport is later defined, the
  6322. // attribute is ignored in subsequent references, and a warning is
  6323. // emitted.
  6324. Diag(FD->getLocation(),
  6325. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  6326. << FD->getName() << "dllimport";
  6327. }
  6328. }
  6329. return FD;
  6330. }
  6331. /// \brief Given the set of return statements within a function body,
  6332. /// compute the variables that are subject to the named return value
  6333. /// optimization.
  6334. ///
  6335. /// Each of the variables that is subject to the named return value
  6336. /// optimization will be marked as NRVO variables in the AST, and any
  6337. /// return statement that has a marked NRVO variable as its NRVO candidate can
  6338. /// use the named return value optimization.
  6339. ///
  6340. /// This function applies a very simplistic algorithm for NRVO: if every return
  6341. /// statement in the function has the same NRVO candidate, that candidate is
  6342. /// the NRVO variable.
  6343. ///
  6344. /// FIXME: Employ a smarter algorithm that accounts for multiple return
  6345. /// statements and the lifetimes of the NRVO candidates. We should be able to
  6346. /// find a maximal set of NRVO variables.
  6347. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  6348. ReturnStmt **Returns = Scope->Returns.data();
  6349. const VarDecl *NRVOCandidate = 0;
  6350. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  6351. if (!Returns[I]->getNRVOCandidate())
  6352. return;
  6353. if (!NRVOCandidate)
  6354. NRVOCandidate = Returns[I]->getNRVOCandidate();
  6355. else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
  6356. return;
  6357. }
  6358. if (NRVOCandidate)
  6359. const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
  6360. }
  6361. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  6362. return ActOnFinishFunctionBody(D, move(BodyArg), false);
  6363. }
  6364. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  6365. bool IsInstantiation) {
  6366. FunctionDecl *FD = 0;
  6367. FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
  6368. if (FunTmpl)
  6369. FD = FunTmpl->getTemplatedDecl();
  6370. else
  6371. FD = dyn_cast_or_null<FunctionDecl>(dcl);
  6372. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  6373. sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
  6374. if (FD) {
  6375. FD->setBody(Body);
  6376. if (FD->isMain()) {
  6377. // C and C++ allow for main to automagically return 0.
  6378. // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  6379. FD->setHasImplicitReturnZero(true);
  6380. WP.disableCheckFallThrough();
  6381. } else if (FD->hasAttr<NakedAttr>()) {
  6382. // If the function is marked 'naked', don't complain about missing return
  6383. // statements.
  6384. WP.disableCheckFallThrough();
  6385. }
  6386. // MSVC permits the use of pure specifier (=0) on function definition,
  6387. // defined at class scope, warn about this non standard construct.
  6388. if (getLangOptions().MicrosoftExt && FD->isPure())
  6389. Diag(FD->getLocation(), diag::warn_pure_function_definition);
  6390. if (!FD->isInvalidDecl()) {
  6391. DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
  6392. DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
  6393. FD->getResultType(), FD);
  6394. // If this is a constructor, we need a vtable.
  6395. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  6396. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  6397. computeNRVO(Body, getCurFunction());
  6398. }
  6399. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  6400. "Function parsing confused");
  6401. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  6402. assert(MD == getCurMethodDecl() && "Method parsing confused");
  6403. MD->setBody(Body);
  6404. if (Body)
  6405. MD->setEndLoc(Body->getLocEnd());
  6406. if (!MD->isInvalidDecl()) {
  6407. DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
  6408. DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
  6409. MD->getResultType(), MD);
  6410. if (Body)
  6411. computeNRVO(Body, getCurFunction());
  6412. }
  6413. if (ObjCShouldCallSuperDealloc) {
  6414. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc);
  6415. ObjCShouldCallSuperDealloc = false;
  6416. }
  6417. if (ObjCShouldCallSuperFinalize) {
  6418. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
  6419. ObjCShouldCallSuperFinalize = false;
  6420. }
  6421. } else {
  6422. return 0;
  6423. }
  6424. assert(!ObjCShouldCallSuperDealloc && "This should only be set for "
  6425. "ObjC methods, which should have been handled in the block above.");
  6426. assert(!ObjCShouldCallSuperFinalize && "This should only be set for "
  6427. "ObjC methods, which should have been handled in the block above.");
  6428. // Verify and clean out per-function state.
  6429. if (Body) {
  6430. // C++ constructors that have function-try-blocks can't have return
  6431. // statements in the handlers of that block. (C++ [except.handle]p14)
  6432. // Verify this.
  6433. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  6434. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  6435. // Verify that gotos and switch cases don't jump into scopes illegally.
  6436. if (getCurFunction()->NeedsScopeChecking() &&
  6437. !dcl->isInvalidDecl() &&
  6438. !hasAnyUnrecoverableErrorsInThisFunction())
  6439. DiagnoseInvalidJumps(Body);
  6440. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  6441. if (!Destructor->getParent()->isDependentType())
  6442. CheckDestructor(Destructor);
  6443. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  6444. Destructor->getParent());
  6445. }
  6446. // If any errors have occurred, clear out any temporaries that may have
  6447. // been leftover. This ensures that these temporaries won't be picked up for
  6448. // deletion in some later function.
  6449. if (PP.getDiagnostics().hasErrorOccurred() ||
  6450. PP.getDiagnostics().getSuppressAllDiagnostics()) {
  6451. DiscardCleanupsInEvaluationContext();
  6452. } else if (!isa<FunctionTemplateDecl>(dcl)) {
  6453. // Since the body is valid, issue any analysis-based warnings that are
  6454. // enabled.
  6455. ActivePolicy = &WP;
  6456. }
  6457. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  6458. (!CheckConstexprFunctionDecl(FD) ||
  6459. !CheckConstexprFunctionBody(FD, Body)))
  6460. FD->setInvalidDecl();
  6461. assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
  6462. assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
  6463. assert(MaybeODRUseExprs.empty() &&
  6464. "Leftover expressions for odr-use checking");
  6465. }
  6466. if (!IsInstantiation)
  6467. PopDeclContext();
  6468. PopFunctionScopeInfo(ActivePolicy, dcl);
  6469. // If any errors have occurred, clear out any temporaries that may have
  6470. // been leftover. This ensures that these temporaries won't be picked up for
  6471. // deletion in some later function.
  6472. if (getDiagnostics().hasErrorOccurred()) {
  6473. DiscardCleanupsInEvaluationContext();
  6474. }
  6475. return dcl;
  6476. }
  6477. /// When we finish delayed parsing of an attribute, we must attach it to the
  6478. /// relevant Decl.
  6479. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  6480. ParsedAttributes &Attrs) {
  6481. // Always attach attributes to the underlying decl.
  6482. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  6483. D = TD->getTemplatedDecl();
  6484. ProcessDeclAttributeList(S, D, Attrs.getList());
  6485. }
  6486. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  6487. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  6488. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  6489. IdentifierInfo &II, Scope *S) {
  6490. // Before we produce a declaration for an implicitly defined
  6491. // function, see whether there was a locally-scoped declaration of
  6492. // this name as a function or variable. If so, use that
  6493. // (non-visible) declaration, and complain about it.
  6494. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  6495. = findLocallyScopedExternalDecl(&II);
  6496. if (Pos != LocallyScopedExternalDecls.end()) {
  6497. Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
  6498. Diag(Pos->second->getLocation(), diag::note_previous_declaration);
  6499. return Pos->second;
  6500. }
  6501. // Extension in C99. Legal in C90, but warn about it.
  6502. unsigned diag_id;
  6503. if (II.getName().startswith("__builtin_"))
  6504. diag_id = diag::warn_builtin_unknown;
  6505. else if (getLangOptions().C99)
  6506. diag_id = diag::ext_implicit_function_decl;
  6507. else
  6508. diag_id = diag::warn_implicit_function_decl;
  6509. Diag(Loc, diag_id) << &II;
  6510. // Because typo correction is expensive, only do it if the implicit
  6511. // function declaration is going to be treated as an error.
  6512. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  6513. TypoCorrection Corrected;
  6514. DeclFilterCCC<FunctionDecl> Validator;
  6515. if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
  6516. LookupOrdinaryName, S, 0, Validator))) {
  6517. std::string CorrectedStr = Corrected.getAsString(getLangOptions());
  6518. std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOptions());
  6519. FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
  6520. Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
  6521. << FixItHint::CreateReplacement(Loc, CorrectedStr);
  6522. if (Func->getLocation().isValid()
  6523. && !II.getName().startswith("__builtin_"))
  6524. Diag(Func->getLocation(), diag::note_previous_decl)
  6525. << CorrectedQuotedStr;
  6526. }
  6527. }
  6528. // Set a Declarator for the implicit definition: int foo();
  6529. const char *Dummy;
  6530. AttributeFactory attrFactory;
  6531. DeclSpec DS(attrFactory);
  6532. unsigned DiagID;
  6533. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
  6534. (void)Error; // Silence warning.
  6535. assert(!Error && "Error setting up implicit decl!");
  6536. Declarator D(DS, Declarator::BlockContext);
  6537. D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
  6538. 0, 0, true, SourceLocation(),
  6539. SourceLocation(), SourceLocation(),
  6540. SourceLocation(),
  6541. EST_None, SourceLocation(),
  6542. 0, 0, 0, 0, Loc, Loc, D),
  6543. DS.getAttributes(),
  6544. SourceLocation());
  6545. D.SetIdentifier(&II, Loc);
  6546. // Insert this function into translation-unit scope.
  6547. DeclContext *PrevDC = CurContext;
  6548. CurContext = Context.getTranslationUnitDecl();
  6549. FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
  6550. FD->setImplicit();
  6551. CurContext = PrevDC;
  6552. AddKnownFunctionAttributes(FD);
  6553. return FD;
  6554. }
  6555. /// \brief Adds any function attributes that we know a priori based on
  6556. /// the declaration of this function.
  6557. ///
  6558. /// These attributes can apply both to implicitly-declared builtins
  6559. /// (like __builtin___printf_chk) or to library-declared functions
  6560. /// like NSLog or printf.
  6561. ///
  6562. /// We need to check for duplicate attributes both here and where user-written
  6563. /// attributes are applied to declarations.
  6564. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  6565. if (FD->isInvalidDecl())
  6566. return;
  6567. // If this is a built-in function, map its builtin attributes to
  6568. // actual attributes.
  6569. if (unsigned BuiltinID = FD->getBuiltinID()) {
  6570. // Handle printf-formatting attributes.
  6571. unsigned FormatIdx;
  6572. bool HasVAListArg;
  6573. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  6574. if (!FD->getAttr<FormatAttr>()) {
  6575. const char *fmt = "printf";
  6576. unsigned int NumParams = FD->getNumParams();
  6577. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  6578. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  6579. fmt = "NSString";
  6580. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  6581. fmt, FormatIdx+1,
  6582. HasVAListArg ? 0 : FormatIdx+2));
  6583. }
  6584. }
  6585. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  6586. HasVAListArg)) {
  6587. if (!FD->getAttr<FormatAttr>())
  6588. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  6589. "scanf", FormatIdx+1,
  6590. HasVAListArg ? 0 : FormatIdx+2));
  6591. }
  6592. // Mark const if we don't care about errno and that is the only
  6593. // thing preventing the function from being const. This allows
  6594. // IRgen to use LLVM intrinsics for such functions.
  6595. if (!getLangOptions().MathErrno &&
  6596. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
  6597. if (!FD->getAttr<ConstAttr>())
  6598. FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
  6599. }
  6600. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  6601. !FD->getAttr<ReturnsTwiceAttr>())
  6602. FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
  6603. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
  6604. FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
  6605. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
  6606. FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
  6607. }
  6608. IdentifierInfo *Name = FD->getIdentifier();
  6609. if (!Name)
  6610. return;
  6611. if ((!getLangOptions().CPlusPlus &&
  6612. FD->getDeclContext()->isTranslationUnit()) ||
  6613. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  6614. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  6615. LinkageSpecDecl::lang_c)) {
  6616. // Okay: this could be a libc/libm/Objective-C function we know
  6617. // about.
  6618. } else
  6619. return;
  6620. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  6621. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  6622. // target-specific builtins, perhaps?
  6623. if (!FD->getAttr<FormatAttr>())
  6624. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  6625. "printf", 2,
  6626. Name->isStr("vasprintf") ? 0 : 3));
  6627. }
  6628. }
  6629. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  6630. TypeSourceInfo *TInfo) {
  6631. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  6632. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  6633. if (!TInfo) {
  6634. assert(D.isInvalidType() && "no declarator info for valid type");
  6635. TInfo = Context.getTrivialTypeSourceInfo(T);
  6636. }
  6637. // Scope manipulation handled by caller.
  6638. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  6639. D.getSourceRange().getBegin(),
  6640. D.getIdentifierLoc(),
  6641. D.getIdentifier(),
  6642. TInfo);
  6643. // Bail out immediately if we have an invalid declaration.
  6644. if (D.isInvalidType()) {
  6645. NewTD->setInvalidDecl();
  6646. return NewTD;
  6647. }
  6648. if (D.getDeclSpec().isModulePrivateSpecified()) {
  6649. if (CurContext->isFunctionOrMethod())
  6650. Diag(NewTD->getLocation(), diag::err_module_private_local)
  6651. << 2 << NewTD->getDeclName()
  6652. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  6653. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6654. else
  6655. NewTD->setModulePrivate();
  6656. }
  6657. // C++ [dcl.typedef]p8:
  6658. // If the typedef declaration defines an unnamed class (or
  6659. // enum), the first typedef-name declared by the declaration
  6660. // to be that class type (or enum type) is used to denote the
  6661. // class type (or enum type) for linkage purposes only.
  6662. // We need to check whether the type was declared in the declaration.
  6663. switch (D.getDeclSpec().getTypeSpecType()) {
  6664. case TST_enum:
  6665. case TST_struct:
  6666. case TST_union:
  6667. case TST_class: {
  6668. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  6669. // Do nothing if the tag is not anonymous or already has an
  6670. // associated typedef (from an earlier typedef in this decl group).
  6671. if (tagFromDeclSpec->getIdentifier()) break;
  6672. if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
  6673. // A well-formed anonymous tag must always be a TUK_Definition.
  6674. assert(tagFromDeclSpec->isThisDeclarationADefinition());
  6675. // The type must match the tag exactly; no qualifiers allowed.
  6676. if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
  6677. break;
  6678. // Otherwise, set this is the anon-decl typedef for the tag.
  6679. tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  6680. break;
  6681. }
  6682. default:
  6683. break;
  6684. }
  6685. return NewTD;
  6686. }
  6687. /// \brief Determine whether a tag with a given kind is acceptable
  6688. /// as a redeclaration of the given tag declaration.
  6689. ///
  6690. /// \returns true if the new tag kind is acceptable, false otherwise.
  6691. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  6692. TagTypeKind NewTag, bool isDefinition,
  6693. SourceLocation NewTagLoc,
  6694. const IdentifierInfo &Name) {
  6695. // C++ [dcl.type.elab]p3:
  6696. // The class-key or enum keyword present in the
  6697. // elaborated-type-specifier shall agree in kind with the
  6698. // declaration to which the name in the elaborated-type-specifier
  6699. // refers. This rule also applies to the form of
  6700. // elaborated-type-specifier that declares a class-name or
  6701. // friend class since it can be construed as referring to the
  6702. // definition of the class. Thus, in any
  6703. // elaborated-type-specifier, the enum keyword shall be used to
  6704. // refer to an enumeration (7.2), the union class-key shall be
  6705. // used to refer to a union (clause 9), and either the class or
  6706. // struct class-key shall be used to refer to a class (clause 9)
  6707. // declared using the class or struct class-key.
  6708. TagTypeKind OldTag = Previous->getTagKind();
  6709. if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
  6710. if (OldTag == NewTag)
  6711. return true;
  6712. if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
  6713. (NewTag == TTK_Struct || NewTag == TTK_Class)) {
  6714. // Warn about the struct/class tag mismatch.
  6715. bool isTemplate = false;
  6716. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  6717. isTemplate = Record->getDescribedClassTemplate();
  6718. if (!ActiveTemplateInstantiations.empty()) {
  6719. // In a template instantiation, do not offer fix-its for tag mismatches
  6720. // since they usually mess up the template instead of fixing the problem.
  6721. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  6722. << (NewTag == TTK_Class) << isTemplate << &Name;
  6723. return true;
  6724. }
  6725. if (isDefinition) {
  6726. // On definitions, check previous tags and issue a fix-it for each
  6727. // one that doesn't match the current tag.
  6728. if (Previous->getDefinition()) {
  6729. // Don't suggest fix-its for redefinitions.
  6730. return true;
  6731. }
  6732. bool previousMismatch = false;
  6733. for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
  6734. E(Previous->redecls_end()); I != E; ++I) {
  6735. if (I->getTagKind() != NewTag) {
  6736. if (!previousMismatch) {
  6737. previousMismatch = true;
  6738. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  6739. << (NewTag == TTK_Class) << isTemplate << &Name;
  6740. }
  6741. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  6742. << (NewTag == TTK_Class)
  6743. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  6744. NewTag == TTK_Class?
  6745. "class" : "struct");
  6746. }
  6747. }
  6748. return true;
  6749. }
  6750. // Check for a previous definition. If current tag and definition
  6751. // are same type, do nothing. If no definition, but disagree with
  6752. // with previous tag type, give a warning, but no fix-it.
  6753. const TagDecl *Redecl = Previous->getDefinition() ?
  6754. Previous->getDefinition() : Previous;
  6755. if (Redecl->getTagKind() == NewTag) {
  6756. return true;
  6757. }
  6758. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  6759. << (NewTag == TTK_Class)
  6760. << isTemplate << &Name;
  6761. Diag(Redecl->getLocation(), diag::note_previous_use);
  6762. // If there is a previous defintion, suggest a fix-it.
  6763. if (Previous->getDefinition()) {
  6764. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  6765. << (Redecl->getTagKind() == TTK_Class)
  6766. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  6767. Redecl->getTagKind() == TTK_Class? "class" : "struct");
  6768. }
  6769. return true;
  6770. }
  6771. return false;
  6772. }
  6773. /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
  6774. /// former case, Name will be non-null. In the later case, Name will be null.
  6775. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  6776. /// reference/declaration/definition of a tag.
  6777. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  6778. SourceLocation KWLoc, CXXScopeSpec &SS,
  6779. IdentifierInfo *Name, SourceLocation NameLoc,
  6780. AttributeList *Attr, AccessSpecifier AS,
  6781. SourceLocation ModulePrivateLoc,
  6782. MultiTemplateParamsArg TemplateParameterLists,
  6783. bool &OwnedDecl, bool &IsDependent,
  6784. SourceLocation ScopedEnumKWLoc,
  6785. bool ScopedEnumUsesClassTag,
  6786. TypeResult UnderlyingType) {
  6787. // If this is not a definition, it must have a name.
  6788. assert((Name != 0 || TUK == TUK_Definition) &&
  6789. "Nameless record must be a definition!");
  6790. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  6791. OwnedDecl = false;
  6792. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  6793. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  6794. // FIXME: Check explicit specializations more carefully.
  6795. bool isExplicitSpecialization = false;
  6796. bool Invalid = false;
  6797. // We only need to do this matching if we have template parameters
  6798. // or a scope specifier, which also conveniently avoids this work
  6799. // for non-C++ cases.
  6800. if (TemplateParameterLists.size() > 0 ||
  6801. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  6802. if (TemplateParameterList *TemplateParams
  6803. = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
  6804. TemplateParameterLists.get(),
  6805. TemplateParameterLists.size(),
  6806. TUK == TUK_Friend,
  6807. isExplicitSpecialization,
  6808. Invalid)) {
  6809. if (TemplateParams->size() > 0) {
  6810. // This is a declaration or definition of a class template (which may
  6811. // be a member of another template).
  6812. if (Invalid)
  6813. return 0;
  6814. OwnedDecl = false;
  6815. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  6816. SS, Name, NameLoc, Attr,
  6817. TemplateParams, AS,
  6818. ModulePrivateLoc,
  6819. TemplateParameterLists.size() - 1,
  6820. (TemplateParameterList**) TemplateParameterLists.release());
  6821. return Result.get();
  6822. } else {
  6823. // The "template<>" header is extraneous.
  6824. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  6825. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  6826. isExplicitSpecialization = true;
  6827. }
  6828. }
  6829. }
  6830. // Figure out the underlying type if this a enum declaration. We need to do
  6831. // this early, because it's needed to detect if this is an incompatible
  6832. // redeclaration.
  6833. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  6834. if (Kind == TTK_Enum) {
  6835. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
  6836. // No underlying type explicitly specified, or we failed to parse the
  6837. // type, default to int.
  6838. EnumUnderlying = Context.IntTy.getTypePtr();
  6839. else if (UnderlyingType.get()) {
  6840. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  6841. // integral type; any cv-qualification is ignored.
  6842. TypeSourceInfo *TI = 0;
  6843. QualType T = GetTypeFromParser(UnderlyingType.get(), &TI);
  6844. EnumUnderlying = TI;
  6845. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  6846. if (!T->isDependentType() && !T->isIntegralType(Context)) {
  6847. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
  6848. << T;
  6849. // Recover by falling back to int.
  6850. EnumUnderlying = Context.IntTy.getTypePtr();
  6851. }
  6852. if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,
  6853. UPPC_FixedUnderlyingType))
  6854. EnumUnderlying = Context.IntTy.getTypePtr();
  6855. } else if (getLangOptions().MicrosoftExt)
  6856. // Microsoft enums are always of int type.
  6857. EnumUnderlying = Context.IntTy.getTypePtr();
  6858. }
  6859. DeclContext *SearchDC = CurContext;
  6860. DeclContext *DC = CurContext;
  6861. bool isStdBadAlloc = false;
  6862. RedeclarationKind Redecl = ForRedeclaration;
  6863. if (TUK == TUK_Friend || TUK == TUK_Reference)
  6864. Redecl = NotForRedeclaration;
  6865. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  6866. if (Name && SS.isNotEmpty()) {
  6867. // We have a nested-name tag ('struct foo::bar').
  6868. // Check for invalid 'foo::'.
  6869. if (SS.isInvalid()) {
  6870. Name = 0;
  6871. goto CreateNewDecl;
  6872. }
  6873. // If this is a friend or a reference to a class in a dependent
  6874. // context, don't try to make a decl for it.
  6875. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  6876. DC = computeDeclContext(SS, false);
  6877. if (!DC) {
  6878. IsDependent = true;
  6879. return 0;
  6880. }
  6881. } else {
  6882. DC = computeDeclContext(SS, true);
  6883. if (!DC) {
  6884. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  6885. << SS.getRange();
  6886. return 0;
  6887. }
  6888. }
  6889. if (RequireCompleteDeclContext(SS, DC))
  6890. return 0;
  6891. SearchDC = DC;
  6892. // Look-up name inside 'foo::'.
  6893. LookupQualifiedName(Previous, DC);
  6894. if (Previous.isAmbiguous())
  6895. return 0;
  6896. if (Previous.empty()) {
  6897. // Name lookup did not find anything. However, if the
  6898. // nested-name-specifier refers to the current instantiation,
  6899. // and that current instantiation has any dependent base
  6900. // classes, we might find something at instantiation time: treat
  6901. // this as a dependent elaborated-type-specifier.
  6902. // But this only makes any sense for reference-like lookups.
  6903. if (Previous.wasNotFoundInCurrentInstantiation() &&
  6904. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  6905. IsDependent = true;
  6906. return 0;
  6907. }
  6908. // A tag 'foo::bar' must already exist.
  6909. Diag(NameLoc, diag::err_not_tag_in_scope)
  6910. << Kind << Name << DC << SS.getRange();
  6911. Name = 0;
  6912. Invalid = true;
  6913. goto CreateNewDecl;
  6914. }
  6915. } else if (Name) {
  6916. // If this is a named struct, check to see if there was a previous forward
  6917. // declaration or definition.
  6918. // FIXME: We're looking into outer scopes here, even when we
  6919. // shouldn't be. Doing so can result in ambiguities that we
  6920. // shouldn't be diagnosing.
  6921. LookupName(Previous, S);
  6922. if (Previous.isAmbiguous() &&
  6923. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  6924. LookupResult::Filter F = Previous.makeFilter();
  6925. while (F.hasNext()) {
  6926. NamedDecl *ND = F.next();
  6927. if (ND->getDeclContext()->getRedeclContext() != SearchDC)
  6928. F.erase();
  6929. }
  6930. F.done();
  6931. }
  6932. // Note: there used to be some attempt at recovery here.
  6933. if (Previous.isAmbiguous())
  6934. return 0;
  6935. if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
  6936. // FIXME: This makes sure that we ignore the contexts associated
  6937. // with C structs, unions, and enums when looking for a matching
  6938. // tag declaration or definition. See the similar lookup tweak
  6939. // in Sema::LookupName; is there a better way to deal with this?
  6940. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  6941. SearchDC = SearchDC->getParent();
  6942. }
  6943. } else if (S->isFunctionPrototypeScope()) {
  6944. // If this is an enum declaration in function prototype scope, set its
  6945. // initial context to the translation unit.
  6946. SearchDC = Context.getTranslationUnitDecl();
  6947. }
  6948. if (Previous.isSingleResult() &&
  6949. Previous.getFoundDecl()->isTemplateParameter()) {
  6950. // Maybe we will complain about the shadowed template parameter.
  6951. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  6952. // Just pretend that we didn't see the previous declaration.
  6953. Previous.clear();
  6954. }
  6955. if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
  6956. DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
  6957. // This is a declaration of or a reference to "std::bad_alloc".
  6958. isStdBadAlloc = true;
  6959. if (Previous.empty() && StdBadAlloc) {
  6960. // std::bad_alloc has been implicitly declared (but made invisible to
  6961. // name lookup). Fill in this implicit declaration as the previous
  6962. // declaration, so that the declarations get chained appropriately.
  6963. Previous.addDecl(getStdBadAlloc());
  6964. }
  6965. }
  6966. // If we didn't find a previous declaration, and this is a reference
  6967. // (or friend reference), move to the correct scope. In C++, we
  6968. // also need to do a redeclaration lookup there, just in case
  6969. // there's a shadow friend decl.
  6970. if (Name && Previous.empty() &&
  6971. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  6972. if (Invalid) goto CreateNewDecl;
  6973. assert(SS.isEmpty());
  6974. if (TUK == TUK_Reference) {
  6975. // C++ [basic.scope.pdecl]p5:
  6976. // -- for an elaborated-type-specifier of the form
  6977. //
  6978. // class-key identifier
  6979. //
  6980. // if the elaborated-type-specifier is used in the
  6981. // decl-specifier-seq or parameter-declaration-clause of a
  6982. // function defined in namespace scope, the identifier is
  6983. // declared as a class-name in the namespace that contains
  6984. // the declaration; otherwise, except as a friend
  6985. // declaration, the identifier is declared in the smallest
  6986. // non-class, non-function-prototype scope that contains the
  6987. // declaration.
  6988. //
  6989. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  6990. // C structs and unions.
  6991. //
  6992. // It is an error in C++ to declare (rather than define) an enum
  6993. // type, including via an elaborated type specifier. We'll
  6994. // diagnose that later; for now, declare the enum in the same
  6995. // scope as we would have picked for any other tag type.
  6996. //
  6997. // GNU C also supports this behavior as part of its incomplete
  6998. // enum types extension, while GNU C++ does not.
  6999. //
  7000. // Find the context where we'll be declaring the tag.
  7001. // FIXME: We would like to maintain the current DeclContext as the
  7002. // lexical context,
  7003. while (SearchDC->isRecord() || SearchDC->isTransparentContext() ||
  7004. SearchDC->isObjCContainer())
  7005. SearchDC = SearchDC->getParent();
  7006. // Find the scope where we'll be declaring the tag.
  7007. while (S->isClassScope() ||
  7008. (getLangOptions().CPlusPlus &&
  7009. S->isFunctionPrototypeScope()) ||
  7010. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7011. (S->getEntity() &&
  7012. ((DeclContext *)S->getEntity())->isTransparentContext()))
  7013. S = S->getParent();
  7014. } else {
  7015. assert(TUK == TUK_Friend);
  7016. // C++ [namespace.memdef]p3:
  7017. // If a friend declaration in a non-local class first declares a
  7018. // class or function, the friend class or function is a member of
  7019. // the innermost enclosing namespace.
  7020. SearchDC = SearchDC->getEnclosingNamespaceContext();
  7021. }
  7022. // In C++, we need to do a redeclaration lookup to properly
  7023. // diagnose some problems.
  7024. if (getLangOptions().CPlusPlus) {
  7025. Previous.setRedeclarationKind(ForRedeclaration);
  7026. LookupQualifiedName(Previous, SearchDC);
  7027. }
  7028. }
  7029. if (!Previous.empty()) {
  7030. NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
  7031. // It's okay to have a tag decl in the same scope as a typedef
  7032. // which hides a tag decl in the same scope. Finding this
  7033. // insanity with a redeclaration lookup can only actually happen
  7034. // in C++.
  7035. //
  7036. // This is also okay for elaborated-type-specifiers, which is
  7037. // technically forbidden by the current standard but which is
  7038. // okay according to the likely resolution of an open issue;
  7039. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  7040. if (getLangOptions().CPlusPlus) {
  7041. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  7042. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  7043. TagDecl *Tag = TT->getDecl();
  7044. if (Tag->getDeclName() == Name &&
  7045. Tag->getDeclContext()->getRedeclContext()
  7046. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  7047. PrevDecl = Tag;
  7048. Previous.clear();
  7049. Previous.addDecl(Tag);
  7050. Previous.resolveKind();
  7051. }
  7052. }
  7053. }
  7054. }
  7055. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  7056. // If this is a use of a previous tag, or if the tag is already declared
  7057. // in the same scope (so that the definition/declaration completes or
  7058. // rementions the tag), reuse the decl.
  7059. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  7060. isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
  7061. // Make sure that this wasn't declared as an enum and now used as a
  7062. // struct or something similar.
  7063. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  7064. TUK == TUK_Definition, KWLoc,
  7065. *Name)) {
  7066. bool SafeToContinue
  7067. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  7068. Kind != TTK_Enum);
  7069. if (SafeToContinue)
  7070. Diag(KWLoc, diag::err_use_with_wrong_tag)
  7071. << Name
  7072. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  7073. PrevTagDecl->getKindName());
  7074. else
  7075. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  7076. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  7077. if (SafeToContinue)
  7078. Kind = PrevTagDecl->getTagKind();
  7079. else {
  7080. // Recover by making this an anonymous redefinition.
  7081. Name = 0;
  7082. Previous.clear();
  7083. Invalid = true;
  7084. }
  7085. }
  7086. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  7087. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  7088. // If this is an elaborated-type-specifier for a scoped enumeration,
  7089. // the 'class' keyword is not necessary and not permitted.
  7090. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  7091. if (ScopedEnum)
  7092. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  7093. << PrevEnum->isScoped()
  7094. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  7095. return PrevTagDecl;
  7096. }
  7097. // All conflicts with previous declarations are recovered by
  7098. // returning the previous declaration.
  7099. if (ScopedEnum != PrevEnum->isScoped()) {
  7100. Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
  7101. << PrevEnum->isScoped();
  7102. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  7103. return PrevTagDecl;
  7104. }
  7105. else if (EnumUnderlying && PrevEnum->isFixed()) {
  7106. QualType T;
  7107. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  7108. T = TI->getType();
  7109. else
  7110. T = QualType(EnumUnderlying.get<const Type*>(), 0);
  7111. if (!Context.hasSameUnqualifiedType(T,
  7112. PrevEnum->getIntegerType())) {
  7113. Diag(NameLoc.isValid() ? NameLoc : KWLoc,
  7114. diag::err_enum_redeclare_type_mismatch)
  7115. << T
  7116. << PrevEnum->getIntegerType();
  7117. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  7118. return PrevTagDecl;
  7119. }
  7120. }
  7121. else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) {
  7122. Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
  7123. << PrevEnum->isFixed();
  7124. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  7125. return PrevTagDecl;
  7126. }
  7127. }
  7128. if (!Invalid) {
  7129. // If this is a use, just return the declaration we found.
  7130. // FIXME: In the future, return a variant or some other clue
  7131. // for the consumer of this Decl to know it doesn't own it.
  7132. // For our current ASTs this shouldn't be a problem, but will
  7133. // need to be changed with DeclGroups.
  7134. if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
  7135. getLangOptions().MicrosoftExt)) || TUK == TUK_Friend)
  7136. return PrevTagDecl;
  7137. // Diagnose attempts to redefine a tag.
  7138. if (TUK == TUK_Definition) {
  7139. if (TagDecl *Def = PrevTagDecl->getDefinition()) {
  7140. // If we're defining a specialization and the previous definition
  7141. // is from an implicit instantiation, don't emit an error
  7142. // here; we'll catch this in the general case below.
  7143. if (!isExplicitSpecialization ||
  7144. !isa<CXXRecordDecl>(Def) ||
  7145. cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
  7146. == TSK_ExplicitSpecialization) {
  7147. Diag(NameLoc, diag::err_redefinition) << Name;
  7148. Diag(Def->getLocation(), diag::note_previous_definition);
  7149. // If this is a redefinition, recover by making this
  7150. // struct be anonymous, which will make any later
  7151. // references get the previous definition.
  7152. Name = 0;
  7153. Previous.clear();
  7154. Invalid = true;
  7155. }
  7156. } else {
  7157. // If the type is currently being defined, complain
  7158. // about a nested redefinition.
  7159. const TagType *Tag
  7160. = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
  7161. if (Tag->isBeingDefined()) {
  7162. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  7163. Diag(PrevTagDecl->getLocation(),
  7164. diag::note_previous_definition);
  7165. Name = 0;
  7166. Previous.clear();
  7167. Invalid = true;
  7168. }
  7169. }
  7170. // Okay, this is definition of a previously declared or referenced
  7171. // tag PrevDecl. We're going to create a new Decl for it.
  7172. }
  7173. }
  7174. // If we get here we have (another) forward declaration or we
  7175. // have a definition. Just create a new decl.
  7176. } else {
  7177. // If we get here, this is a definition of a new tag type in a nested
  7178. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  7179. // new decl/type. We set PrevDecl to NULL so that the entities
  7180. // have distinct types.
  7181. Previous.clear();
  7182. }
  7183. // If we get here, we're going to create a new Decl. If PrevDecl
  7184. // is non-NULL, it's a definition of the tag declared by
  7185. // PrevDecl. If it's NULL, we have a new definition.
  7186. // Otherwise, PrevDecl is not a tag, but was found with tag
  7187. // lookup. This is only actually possible in C++, where a few
  7188. // things like templates still live in the tag namespace.
  7189. } else {
  7190. // Use a better diagnostic if an elaborated-type-specifier
  7191. // found the wrong kind of type on the first
  7192. // (non-redeclaration) lookup.
  7193. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  7194. !Previous.isForRedeclaration()) {
  7195. unsigned Kind = 0;
  7196. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  7197. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  7198. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  7199. Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
  7200. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  7201. Invalid = true;
  7202. // Otherwise, only diagnose if the declaration is in scope.
  7203. } else if (!isDeclInScope(PrevDecl, SearchDC, S,
  7204. isExplicitSpecialization)) {
  7205. // do nothing
  7206. // Diagnose implicit declarations introduced by elaborated types.
  7207. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  7208. unsigned Kind = 0;
  7209. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  7210. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  7211. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  7212. Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
  7213. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  7214. Invalid = true;
  7215. // Otherwise it's a declaration. Call out a particularly common
  7216. // case here.
  7217. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  7218. unsigned Kind = 0;
  7219. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  7220. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  7221. << Name << Kind << TND->getUnderlyingType();
  7222. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  7223. Invalid = true;
  7224. // Otherwise, diagnose.
  7225. } else {
  7226. // The tag name clashes with something else in the target scope,
  7227. // issue an error and recover by making this tag be anonymous.
  7228. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  7229. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  7230. Name = 0;
  7231. Invalid = true;
  7232. }
  7233. // The existing declaration isn't relevant to us; we're in a
  7234. // new scope, so clear out the previous declaration.
  7235. Previous.clear();
  7236. }
  7237. }
  7238. CreateNewDecl:
  7239. TagDecl *PrevDecl = 0;
  7240. if (Previous.isSingleResult())
  7241. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  7242. // If there is an identifier, use the location of the identifier as the
  7243. // location of the decl, otherwise use the location of the struct/union
  7244. // keyword.
  7245. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  7246. // Otherwise, create a new declaration. If there is a previous
  7247. // declaration of the same entity, the two will be linked via
  7248. // PrevDecl.
  7249. TagDecl *New;
  7250. bool IsForwardReference = false;
  7251. if (Kind == TTK_Enum) {
  7252. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  7253. // enum X { A, B, C } D; D should chain to X.
  7254. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  7255. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  7256. ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
  7257. // If this is an undefined enum, warn.
  7258. if (TUK != TUK_Definition && !Invalid) {
  7259. TagDecl *Def;
  7260. if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
  7261. // C++0x: 7.2p2: opaque-enum-declaration.
  7262. // Conflicts are diagnosed above. Do nothing.
  7263. }
  7264. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  7265. Diag(Loc, diag::ext_forward_ref_enum_def)
  7266. << New;
  7267. Diag(Def->getLocation(), diag::note_previous_definition);
  7268. } else {
  7269. unsigned DiagID = diag::ext_forward_ref_enum;
  7270. if (getLangOptions().MicrosoftExt)
  7271. DiagID = diag::ext_ms_forward_ref_enum;
  7272. else if (getLangOptions().CPlusPlus)
  7273. DiagID = diag::err_forward_ref_enum;
  7274. Diag(Loc, DiagID);
  7275. // If this is a forward-declared reference to an enumeration, make a
  7276. // note of it; we won't actually be introducing the declaration into
  7277. // the declaration context.
  7278. if (TUK == TUK_Reference)
  7279. IsForwardReference = true;
  7280. }
  7281. }
  7282. if (EnumUnderlying) {
  7283. EnumDecl *ED = cast<EnumDecl>(New);
  7284. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  7285. ED->setIntegerTypeSourceInfo(TI);
  7286. else
  7287. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  7288. ED->setPromotionType(ED->getIntegerType());
  7289. }
  7290. } else {
  7291. // struct/union/class
  7292. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  7293. // struct X { int A; } D; D should chain to X.
  7294. if (getLangOptions().CPlusPlus) {
  7295. // FIXME: Look for a way to use RecordDecl for simple structs.
  7296. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  7297. cast_or_null<CXXRecordDecl>(PrevDecl));
  7298. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  7299. StdBadAlloc = cast<CXXRecordDecl>(New);
  7300. } else
  7301. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  7302. cast_or_null<RecordDecl>(PrevDecl));
  7303. }
  7304. // Maybe add qualifier info.
  7305. if (SS.isNotEmpty()) {
  7306. if (SS.isSet()) {
  7307. New->setQualifierInfo(SS.getWithLocInContext(Context));
  7308. if (TemplateParameterLists.size() > 0) {
  7309. New->setTemplateParameterListsInfo(Context,
  7310. TemplateParameterLists.size(),
  7311. (TemplateParameterList**) TemplateParameterLists.release());
  7312. }
  7313. }
  7314. else
  7315. Invalid = true;
  7316. }
  7317. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  7318. // Add alignment attributes if necessary; these attributes are checked when
  7319. // the ASTContext lays out the structure.
  7320. //
  7321. // It is important for implementing the correct semantics that this
  7322. // happen here (in act on tag decl). The #pragma pack stack is
  7323. // maintained as a result of parser callbacks which can occur at
  7324. // many points during the parsing of a struct declaration (because
  7325. // the #pragma tokens are effectively skipped over during the
  7326. // parsing of the struct).
  7327. AddAlignmentAttributesForRecord(RD);
  7328. AddMsStructLayoutForRecord(RD);
  7329. }
  7330. if (ModulePrivateLoc.isValid()) {
  7331. if (isExplicitSpecialization)
  7332. Diag(New->getLocation(), diag::err_module_private_specialization)
  7333. << 2
  7334. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7335. // __module_private__ does not apply to local classes. However, we only
  7336. // diagnose this as an error when the declaration specifiers are
  7337. // freestanding. Here, we just ignore the __module_private__.
  7338. else if (!SearchDC->isFunctionOrMethod())
  7339. New->setModulePrivate();
  7340. }
  7341. // If this is a specialization of a member class (of a class template),
  7342. // check the specialization.
  7343. if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
  7344. Invalid = true;
  7345. if (Invalid)
  7346. New->setInvalidDecl();
  7347. if (Attr)
  7348. ProcessDeclAttributeList(S, New, Attr);
  7349. // If we're declaring or defining a tag in function prototype scope
  7350. // in C, note that this type can only be used within the function.
  7351. if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
  7352. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  7353. // Set the lexical context. If the tag has a C++ scope specifier, the
  7354. // lexical context will be different from the semantic context.
  7355. New->setLexicalDeclContext(CurContext);
  7356. // Mark this as a friend decl if applicable.
  7357. // In Microsoft mode, a friend declaration also acts as a forward
  7358. // declaration so we always pass true to setObjectOfFriendDecl to make
  7359. // the tag name visible.
  7360. if (TUK == TUK_Friend)
  7361. New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
  7362. getLangOptions().MicrosoftExt);
  7363. // Set the access specifier.
  7364. if (!Invalid && SearchDC->isRecord())
  7365. SetMemberAccessSpecifier(New, PrevDecl, AS);
  7366. if (TUK == TUK_Definition)
  7367. New->startDefinition();
  7368. // If this has an identifier, add it to the scope stack.
  7369. if (TUK == TUK_Friend) {
  7370. // We might be replacing an existing declaration in the lookup tables;
  7371. // if so, borrow its access specifier.
  7372. if (PrevDecl)
  7373. New->setAccess(PrevDecl->getAccess());
  7374. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  7375. DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
  7376. if (Name) // can be null along some error paths
  7377. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  7378. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  7379. } else if (Name) {
  7380. S = getNonFieldDeclScope(S);
  7381. PushOnScopeChains(New, S, !IsForwardReference);
  7382. if (IsForwardReference)
  7383. SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
  7384. } else {
  7385. CurContext->addDecl(New);
  7386. }
  7387. // If this is the C FILE type, notify the AST context.
  7388. if (IdentifierInfo *II = New->getIdentifier())
  7389. if (!New->isInvalidDecl() &&
  7390. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  7391. II->isStr("FILE"))
  7392. Context.setFILEDecl(New);
  7393. OwnedDecl = true;
  7394. return New;
  7395. }
  7396. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  7397. AdjustDeclIfTemplate(TagD);
  7398. TagDecl *Tag = cast<TagDecl>(TagD);
  7399. // Enter the tag context.
  7400. PushDeclContext(S, Tag);
  7401. }
  7402. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  7403. assert(isa<ObjCContainerDecl>(IDecl) &&
  7404. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  7405. DeclContext *OCD = cast<DeclContext>(IDecl);
  7406. assert(getContainingDC(OCD) == CurContext &&
  7407. "The next DeclContext should be lexically contained in the current one.");
  7408. CurContext = OCD;
  7409. return IDecl;
  7410. }
  7411. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  7412. SourceLocation FinalLoc,
  7413. SourceLocation LBraceLoc) {
  7414. AdjustDeclIfTemplate(TagD);
  7415. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  7416. FieldCollector->StartClass();
  7417. if (!Record->getIdentifier())
  7418. return;
  7419. if (FinalLoc.isValid())
  7420. Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
  7421. // C++ [class]p2:
  7422. // [...] The class-name is also inserted into the scope of the
  7423. // class itself; this is known as the injected-class-name. For
  7424. // purposes of access checking, the injected-class-name is treated
  7425. // as if it were a public member name.
  7426. CXXRecordDecl *InjectedClassName
  7427. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  7428. Record->getLocStart(), Record->getLocation(),
  7429. Record->getIdentifier(),
  7430. /*PrevDecl=*/0,
  7431. /*DelayTypeCreation=*/true);
  7432. Context.getTypeDeclType(InjectedClassName, Record);
  7433. InjectedClassName->setImplicit();
  7434. InjectedClassName->setAccess(AS_public);
  7435. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  7436. InjectedClassName->setDescribedClassTemplate(Template);
  7437. PushOnScopeChains(InjectedClassName, S);
  7438. assert(InjectedClassName->isInjectedClassName() &&
  7439. "Broken injected-class-name");
  7440. }
  7441. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  7442. SourceLocation RBraceLoc) {
  7443. AdjustDeclIfTemplate(TagD);
  7444. TagDecl *Tag = cast<TagDecl>(TagD);
  7445. Tag->setRBraceLoc(RBraceLoc);
  7446. if (isa<CXXRecordDecl>(Tag))
  7447. FieldCollector->FinishClass();
  7448. // Exit this scope of this tag's definition.
  7449. PopDeclContext();
  7450. // Notify the consumer that we've defined a tag.
  7451. Consumer.HandleTagDeclDefinition(Tag);
  7452. }
  7453. void Sema::ActOnObjCContainerFinishDefinition() {
  7454. // Exit this scope of this interface definition.
  7455. PopDeclContext();
  7456. }
  7457. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  7458. assert(DC == CurContext && "Mismatch of container contexts");
  7459. OriginalLexicalContext = DC;
  7460. ActOnObjCContainerFinishDefinition();
  7461. }
  7462. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  7463. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  7464. OriginalLexicalContext = 0;
  7465. }
  7466. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  7467. AdjustDeclIfTemplate(TagD);
  7468. TagDecl *Tag = cast<TagDecl>(TagD);
  7469. Tag->setInvalidDecl();
  7470. // We're undoing ActOnTagStartDefinition here, not
  7471. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  7472. // the FieldCollector.
  7473. PopDeclContext();
  7474. }
  7475. // Note that FieldName may be null for anonymous bitfields.
  7476. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  7477. IdentifierInfo *FieldName,
  7478. QualType FieldTy, Expr *BitWidth,
  7479. bool *ZeroWidth) {
  7480. // Default to true; that shouldn't confuse checks for emptiness
  7481. if (ZeroWidth)
  7482. *ZeroWidth = true;
  7483. // C99 6.7.2.1p4 - verify the field type.
  7484. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  7485. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  7486. // Handle incomplete types with specific error.
  7487. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  7488. return ExprError();
  7489. if (FieldName)
  7490. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  7491. << FieldName << FieldTy << BitWidth->getSourceRange();
  7492. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  7493. << FieldTy << BitWidth->getSourceRange();
  7494. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  7495. UPPC_BitFieldWidth))
  7496. return ExprError();
  7497. // If the bit-width is type- or value-dependent, don't try to check
  7498. // it now.
  7499. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  7500. return Owned(BitWidth);
  7501. llvm::APSInt Value;
  7502. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  7503. if (ICE.isInvalid())
  7504. return ICE;
  7505. BitWidth = ICE.take();
  7506. if (Value != 0 && ZeroWidth)
  7507. *ZeroWidth = false;
  7508. // Zero-width bitfield is ok for anonymous field.
  7509. if (Value == 0 && FieldName)
  7510. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  7511. if (Value.isSigned() && Value.isNegative()) {
  7512. if (FieldName)
  7513. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  7514. << FieldName << Value.toString(10);
  7515. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  7516. << Value.toString(10);
  7517. }
  7518. if (!FieldTy->isDependentType()) {
  7519. uint64_t TypeSize = Context.getTypeSize(FieldTy);
  7520. if (Value.getZExtValue() > TypeSize) {
  7521. if (!getLangOptions().CPlusPlus) {
  7522. if (FieldName)
  7523. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
  7524. << FieldName << (unsigned)Value.getZExtValue()
  7525. << (unsigned)TypeSize;
  7526. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
  7527. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  7528. }
  7529. if (FieldName)
  7530. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
  7531. << FieldName << (unsigned)Value.getZExtValue()
  7532. << (unsigned)TypeSize;
  7533. else
  7534. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
  7535. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  7536. }
  7537. }
  7538. return Owned(BitWidth);
  7539. }
  7540. /// ActOnField - Each field of a C struct/union is passed into this in order
  7541. /// to create a FieldDecl object for it.
  7542. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  7543. Declarator &D, Expr *BitfieldWidth) {
  7544. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  7545. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  7546. /*HasInit=*/false, AS_public);
  7547. return Res;
  7548. }
  7549. /// HandleField - Analyze a field of a C struct or a C++ data member.
  7550. ///
  7551. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  7552. SourceLocation DeclStart,
  7553. Declarator &D, Expr *BitWidth, bool HasInit,
  7554. AccessSpecifier AS) {
  7555. IdentifierInfo *II = D.getIdentifier();
  7556. SourceLocation Loc = DeclStart;
  7557. if (II) Loc = D.getIdentifierLoc();
  7558. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  7559. QualType T = TInfo->getType();
  7560. if (getLangOptions().CPlusPlus) {
  7561. CheckExtraCXXDefaultArguments(D);
  7562. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  7563. UPPC_DataMemberType)) {
  7564. D.setInvalidType();
  7565. T = Context.IntTy;
  7566. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  7567. }
  7568. }
  7569. DiagnoseFunctionSpecifiers(D);
  7570. if (D.getDeclSpec().isThreadSpecified())
  7571. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  7572. if (D.getDeclSpec().isConstexprSpecified())
  7573. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  7574. << 2;
  7575. // Check to see if this name was declared as a member previously
  7576. NamedDecl *PrevDecl = 0;
  7577. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  7578. LookupName(Previous, S);
  7579. switch (Previous.getResultKind()) {
  7580. case LookupResult::Found:
  7581. case LookupResult::FoundUnresolvedValue:
  7582. PrevDecl = Previous.getAsSingle<NamedDecl>();
  7583. break;
  7584. case LookupResult::FoundOverloaded:
  7585. PrevDecl = Previous.getRepresentativeDecl();
  7586. break;
  7587. case LookupResult::NotFound:
  7588. case LookupResult::NotFoundInCurrentInstantiation:
  7589. case LookupResult::Ambiguous:
  7590. break;
  7591. }
  7592. Previous.suppressDiagnostics();
  7593. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  7594. // Maybe we will complain about the shadowed template parameter.
  7595. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  7596. // Just pretend that we didn't see the previous declaration.
  7597. PrevDecl = 0;
  7598. }
  7599. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  7600. PrevDecl = 0;
  7601. bool Mutable
  7602. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  7603. SourceLocation TSSL = D.getSourceRange().getBegin();
  7604. FieldDecl *NewFD
  7605. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
  7606. TSSL, AS, PrevDecl, &D);
  7607. if (NewFD->isInvalidDecl())
  7608. Record->setInvalidDecl();
  7609. if (D.getDeclSpec().isModulePrivateSpecified())
  7610. NewFD->setModulePrivate();
  7611. if (NewFD->isInvalidDecl() && PrevDecl) {
  7612. // Don't introduce NewFD into scope; there's already something
  7613. // with the same name in the same scope.
  7614. } else if (II) {
  7615. PushOnScopeChains(NewFD, S);
  7616. } else
  7617. Record->addDecl(NewFD);
  7618. return NewFD;
  7619. }
  7620. /// \brief Build a new FieldDecl and check its well-formedness.
  7621. ///
  7622. /// This routine builds a new FieldDecl given the fields name, type,
  7623. /// record, etc. \p PrevDecl should refer to any previous declaration
  7624. /// with the same name and in the same scope as the field to be
  7625. /// created.
  7626. ///
  7627. /// \returns a new FieldDecl.
  7628. ///
  7629. /// \todo The Declarator argument is a hack. It will be removed once
  7630. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  7631. TypeSourceInfo *TInfo,
  7632. RecordDecl *Record, SourceLocation Loc,
  7633. bool Mutable, Expr *BitWidth, bool HasInit,
  7634. SourceLocation TSSL,
  7635. AccessSpecifier AS, NamedDecl *PrevDecl,
  7636. Declarator *D) {
  7637. IdentifierInfo *II = Name.getAsIdentifierInfo();
  7638. bool InvalidDecl = false;
  7639. if (D) InvalidDecl = D->isInvalidType();
  7640. // If we receive a broken type, recover by assuming 'int' and
  7641. // marking this declaration as invalid.
  7642. if (T.isNull()) {
  7643. InvalidDecl = true;
  7644. T = Context.IntTy;
  7645. }
  7646. QualType EltTy = Context.getBaseElementType(T);
  7647. if (!EltTy->isDependentType() &&
  7648. RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  7649. // Fields of incomplete type force their record to be invalid.
  7650. Record->setInvalidDecl();
  7651. InvalidDecl = true;
  7652. }
  7653. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  7654. // than a variably modified type.
  7655. if (!InvalidDecl && T->isVariablyModifiedType()) {
  7656. bool SizeIsNegative;
  7657. llvm::APSInt Oversized;
  7658. QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
  7659. SizeIsNegative,
  7660. Oversized);
  7661. if (!FixedTy.isNull()) {
  7662. Diag(Loc, diag::warn_illegal_constant_array_size);
  7663. T = FixedTy;
  7664. } else {
  7665. if (SizeIsNegative)
  7666. Diag(Loc, diag::err_typecheck_negative_array_size);
  7667. else if (Oversized.getBoolValue())
  7668. Diag(Loc, diag::err_array_too_large)
  7669. << Oversized.toString(10);
  7670. else
  7671. Diag(Loc, diag::err_typecheck_field_variable_size);
  7672. InvalidDecl = true;
  7673. }
  7674. }
  7675. // Fields can not have abstract class types
  7676. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  7677. diag::err_abstract_type_in_decl,
  7678. AbstractFieldType))
  7679. InvalidDecl = true;
  7680. bool ZeroWidth = false;
  7681. // If this is declared as a bit-field, check the bit-field.
  7682. if (!InvalidDecl && BitWidth) {
  7683. BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
  7684. if (!BitWidth) {
  7685. InvalidDecl = true;
  7686. BitWidth = 0;
  7687. ZeroWidth = false;
  7688. }
  7689. }
  7690. // Check that 'mutable' is consistent with the type of the declaration.
  7691. if (!InvalidDecl && Mutable) {
  7692. unsigned DiagID = 0;
  7693. if (T->isReferenceType())
  7694. DiagID = diag::err_mutable_reference;
  7695. else if (T.isConstQualified())
  7696. DiagID = diag::err_mutable_const;
  7697. if (DiagID) {
  7698. SourceLocation ErrLoc = Loc;
  7699. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  7700. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  7701. Diag(ErrLoc, DiagID);
  7702. Mutable = false;
  7703. InvalidDecl = true;
  7704. }
  7705. }
  7706. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  7707. BitWidth, Mutable, HasInit);
  7708. if (InvalidDecl)
  7709. NewFD->setInvalidDecl();
  7710. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  7711. Diag(Loc, diag::err_duplicate_member) << II;
  7712. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  7713. NewFD->setInvalidDecl();
  7714. }
  7715. if (!InvalidDecl && getLangOptions().CPlusPlus) {
  7716. if (Record->isUnion()) {
  7717. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  7718. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  7719. if (RDecl->getDefinition()) {
  7720. // C++ [class.union]p1: An object of a class with a non-trivial
  7721. // constructor, a non-trivial copy constructor, a non-trivial
  7722. // destructor, or a non-trivial copy assignment operator
  7723. // cannot be a member of a union, nor can an array of such
  7724. // objects.
  7725. if (CheckNontrivialField(NewFD))
  7726. NewFD->setInvalidDecl();
  7727. }
  7728. }
  7729. // C++ [class.union]p1: If a union contains a member of reference type,
  7730. // the program is ill-formed.
  7731. if (EltTy->isReferenceType()) {
  7732. Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
  7733. << NewFD->getDeclName() << EltTy;
  7734. NewFD->setInvalidDecl();
  7735. }
  7736. }
  7737. }
  7738. // FIXME: We need to pass in the attributes given an AST
  7739. // representation, not a parser representation.
  7740. if (D)
  7741. // FIXME: What to pass instead of TUScope?
  7742. ProcessDeclAttributes(TUScope, NewFD, *D);
  7743. // In auto-retain/release, infer strong retension for fields of
  7744. // retainable type.
  7745. if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  7746. NewFD->setInvalidDecl();
  7747. if (T.isObjCGCWeak())
  7748. Diag(Loc, diag::warn_attribute_weak_on_field);
  7749. NewFD->setAccess(AS);
  7750. return NewFD;
  7751. }
  7752. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  7753. assert(FD);
  7754. assert(getLangOptions().CPlusPlus && "valid check only for C++");
  7755. if (FD->isInvalidDecl())
  7756. return true;
  7757. QualType EltTy = Context.getBaseElementType(FD->getType());
  7758. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  7759. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  7760. if (RDecl->getDefinition()) {
  7761. // We check for copy constructors before constructors
  7762. // because otherwise we'll never get complaints about
  7763. // copy constructors.
  7764. CXXSpecialMember member = CXXInvalid;
  7765. if (!RDecl->hasTrivialCopyConstructor())
  7766. member = CXXCopyConstructor;
  7767. else if (!RDecl->hasTrivialDefaultConstructor())
  7768. member = CXXDefaultConstructor;
  7769. else if (!RDecl->hasTrivialCopyAssignment())
  7770. member = CXXCopyAssignment;
  7771. else if (!RDecl->hasTrivialDestructor())
  7772. member = CXXDestructor;
  7773. if (member != CXXInvalid) {
  7774. if (!getLangOptions().CPlusPlus0x &&
  7775. getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  7776. // Objective-C++ ARC: it is an error to have a non-trivial field of
  7777. // a union. However, system headers in Objective-C programs
  7778. // occasionally have Objective-C lifetime objects within unions,
  7779. // and rather than cause the program to fail, we make those
  7780. // members unavailable.
  7781. SourceLocation Loc = FD->getLocation();
  7782. if (getSourceManager().isInSystemHeader(Loc)) {
  7783. if (!FD->hasAttr<UnavailableAttr>())
  7784. FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
  7785. "this system field has retaining ownership"));
  7786. return false;
  7787. }
  7788. }
  7789. Diag(FD->getLocation(), getLangOptions().CPlusPlus0x ?
  7790. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  7791. diag::err_illegal_union_or_anon_struct_member)
  7792. << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
  7793. DiagnoseNontrivial(RT, member);
  7794. return !getLangOptions().CPlusPlus0x;
  7795. }
  7796. }
  7797. }
  7798. return false;
  7799. }
  7800. /// DiagnoseNontrivial - Given that a class has a non-trivial
  7801. /// special member, figure out why.
  7802. void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
  7803. QualType QT(T, 0U);
  7804. CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
  7805. // Check whether the member was user-declared.
  7806. switch (member) {
  7807. case CXXInvalid:
  7808. break;
  7809. case CXXDefaultConstructor:
  7810. if (RD->hasUserDeclaredConstructor()) {
  7811. typedef CXXRecordDecl::ctor_iterator ctor_iter;
  7812. for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
  7813. const FunctionDecl *body = 0;
  7814. ci->hasBody(body);
  7815. if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
  7816. SourceLocation CtorLoc = ci->getLocation();
  7817. Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  7818. return;
  7819. }
  7820. }
  7821. llvm_unreachable("found no user-declared constructors");
  7822. }
  7823. break;
  7824. case CXXCopyConstructor:
  7825. if (RD->hasUserDeclaredCopyConstructor()) {
  7826. SourceLocation CtorLoc =
  7827. RD->getCopyConstructor(0)->getLocation();
  7828. Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  7829. return;
  7830. }
  7831. break;
  7832. case CXXMoveConstructor:
  7833. if (RD->hasUserDeclaredMoveConstructor()) {
  7834. SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
  7835. Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  7836. return;
  7837. }
  7838. break;
  7839. case CXXCopyAssignment:
  7840. if (RD->hasUserDeclaredCopyAssignment()) {
  7841. // FIXME: this should use the location of the copy
  7842. // assignment, not the type.
  7843. SourceLocation TyLoc = RD->getSourceRange().getBegin();
  7844. Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
  7845. return;
  7846. }
  7847. break;
  7848. case CXXMoveAssignment:
  7849. if (RD->hasUserDeclaredMoveAssignment()) {
  7850. SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
  7851. Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
  7852. return;
  7853. }
  7854. break;
  7855. case CXXDestructor:
  7856. if (RD->hasUserDeclaredDestructor()) {
  7857. SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
  7858. Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  7859. return;
  7860. }
  7861. break;
  7862. }
  7863. typedef CXXRecordDecl::base_class_iterator base_iter;
  7864. // Virtual bases and members inhibit trivial copying/construction,
  7865. // but not trivial destruction.
  7866. if (member != CXXDestructor) {
  7867. // Check for virtual bases. vbases includes indirect virtual bases,
  7868. // so we just iterate through the direct bases.
  7869. for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
  7870. if (bi->isVirtual()) {
  7871. SourceLocation BaseLoc = bi->getSourceRange().getBegin();
  7872. Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
  7873. return;
  7874. }
  7875. // Check for virtual methods.
  7876. typedef CXXRecordDecl::method_iterator meth_iter;
  7877. for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
  7878. ++mi) {
  7879. if (mi->isVirtual()) {
  7880. SourceLocation MLoc = mi->getSourceRange().getBegin();
  7881. Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
  7882. return;
  7883. }
  7884. }
  7885. }
  7886. bool (CXXRecordDecl::*hasTrivial)() const;
  7887. switch (member) {
  7888. case CXXDefaultConstructor:
  7889. hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
  7890. case CXXCopyConstructor:
  7891. hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
  7892. case CXXCopyAssignment:
  7893. hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
  7894. case CXXDestructor:
  7895. hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
  7896. default:
  7897. llvm_unreachable("unexpected special member");
  7898. }
  7899. // Check for nontrivial bases (and recurse).
  7900. for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
  7901. const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
  7902. assert(BaseRT && "Don't know how to handle dependent bases");
  7903. CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
  7904. if (!(BaseRecTy->*hasTrivial)()) {
  7905. SourceLocation BaseLoc = bi->getSourceRange().getBegin();
  7906. Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
  7907. DiagnoseNontrivial(BaseRT, member);
  7908. return;
  7909. }
  7910. }
  7911. // Check for nontrivial members (and recurse).
  7912. typedef RecordDecl::field_iterator field_iter;
  7913. for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
  7914. ++fi) {
  7915. QualType EltTy = Context.getBaseElementType((*fi)->getType());
  7916. if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
  7917. CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
  7918. if (!(EltRD->*hasTrivial)()) {
  7919. SourceLocation FLoc = (*fi)->getLocation();
  7920. Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
  7921. DiagnoseNontrivial(EltRT, member);
  7922. return;
  7923. }
  7924. }
  7925. if (EltTy->isObjCLifetimeType()) {
  7926. switch (EltTy.getObjCLifetime()) {
  7927. case Qualifiers::OCL_None:
  7928. case Qualifiers::OCL_ExplicitNone:
  7929. break;
  7930. case Qualifiers::OCL_Autoreleasing:
  7931. case Qualifiers::OCL_Weak:
  7932. case Qualifiers::OCL_Strong:
  7933. Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership)
  7934. << QT << EltTy.getObjCLifetime();
  7935. return;
  7936. }
  7937. }
  7938. }
  7939. llvm_unreachable("found no explanation for non-trivial member");
  7940. }
  7941. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  7942. /// AST enum value.
  7943. static ObjCIvarDecl::AccessControl
  7944. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  7945. switch (ivarVisibility) {
  7946. default: llvm_unreachable("Unknown visitibility kind");
  7947. case tok::objc_private: return ObjCIvarDecl::Private;
  7948. case tok::objc_public: return ObjCIvarDecl::Public;
  7949. case tok::objc_protected: return ObjCIvarDecl::Protected;
  7950. case tok::objc_package: return ObjCIvarDecl::Package;
  7951. }
  7952. }
  7953. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  7954. /// in order to create an IvarDecl object for it.
  7955. Decl *Sema::ActOnIvar(Scope *S,
  7956. SourceLocation DeclStart,
  7957. Declarator &D, Expr *BitfieldWidth,
  7958. tok::ObjCKeywordKind Visibility) {
  7959. IdentifierInfo *II = D.getIdentifier();
  7960. Expr *BitWidth = (Expr*)BitfieldWidth;
  7961. SourceLocation Loc = DeclStart;
  7962. if (II) Loc = D.getIdentifierLoc();
  7963. // FIXME: Unnamed fields can be handled in various different ways, for
  7964. // example, unnamed unions inject all members into the struct namespace!
  7965. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  7966. QualType T = TInfo->getType();
  7967. if (BitWidth) {
  7968. // 6.7.2.1p3, 6.7.2.1p4
  7969. BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
  7970. if (!BitWidth)
  7971. D.setInvalidType();
  7972. } else {
  7973. // Not a bitfield.
  7974. // validate II.
  7975. }
  7976. if (T->isReferenceType()) {
  7977. Diag(Loc, diag::err_ivar_reference_type);
  7978. D.setInvalidType();
  7979. }
  7980. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  7981. // than a variably modified type.
  7982. else if (T->isVariablyModifiedType()) {
  7983. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  7984. D.setInvalidType();
  7985. }
  7986. // Get the visibility (access control) for this ivar.
  7987. ObjCIvarDecl::AccessControl ac =
  7988. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  7989. : ObjCIvarDecl::None;
  7990. // Must set ivar's DeclContext to its enclosing interface.
  7991. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  7992. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  7993. return 0;
  7994. ObjCContainerDecl *EnclosingContext;
  7995. if (ObjCImplementationDecl *IMPDecl =
  7996. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  7997. if (!LangOpts.ObjCNonFragileABI2) {
  7998. // Case of ivar declared in an implementation. Context is that of its class.
  7999. EnclosingContext = IMPDecl->getClassInterface();
  8000. assert(EnclosingContext && "Implementation has no class interface!");
  8001. }
  8002. else
  8003. EnclosingContext = EnclosingDecl;
  8004. } else {
  8005. if (ObjCCategoryDecl *CDecl =
  8006. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  8007. if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
  8008. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  8009. return 0;
  8010. }
  8011. }
  8012. EnclosingContext = EnclosingDecl;
  8013. }
  8014. // Construct the decl.
  8015. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  8016. DeclStart, Loc, II, T,
  8017. TInfo, ac, (Expr *)BitfieldWidth);
  8018. if (II) {
  8019. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  8020. ForRedeclaration);
  8021. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  8022. && !isa<TagDecl>(PrevDecl)) {
  8023. Diag(Loc, diag::err_duplicate_member) << II;
  8024. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  8025. NewID->setInvalidDecl();
  8026. }
  8027. }
  8028. // Process attributes attached to the ivar.
  8029. ProcessDeclAttributes(S, NewID, D);
  8030. if (D.isInvalidType())
  8031. NewID->setInvalidDecl();
  8032. // In ARC, infer 'retaining' for ivars of retainable type.
  8033. if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  8034. NewID->setInvalidDecl();
  8035. if (D.getDeclSpec().isModulePrivateSpecified())
  8036. NewID->setModulePrivate();
  8037. if (II) {
  8038. // FIXME: When interfaces are DeclContexts, we'll need to add
  8039. // these to the interface.
  8040. S->AddDecl(NewID);
  8041. IdResolver.AddDecl(NewID);
  8042. }
  8043. return NewID;
  8044. }
  8045. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  8046. /// class and class extensions. For every class @interface and class
  8047. /// extension @interface, if the last ivar is a bitfield of any type,
  8048. /// then add an implicit `char :0` ivar to the end of that interface.
  8049. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  8050. SmallVectorImpl<Decl *> &AllIvarDecls) {
  8051. if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
  8052. return;
  8053. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  8054. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  8055. if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
  8056. return;
  8057. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  8058. if (!ID) {
  8059. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  8060. if (!CD->IsClassExtension())
  8061. return;
  8062. }
  8063. // No need to add this to end of @implementation.
  8064. else
  8065. return;
  8066. }
  8067. // All conditions are met. Add a new bitfield to the tail end of ivars.
  8068. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  8069. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  8070. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  8071. DeclLoc, DeclLoc, 0,
  8072. Context.CharTy,
  8073. Context.getTrivialTypeSourceInfo(Context.CharTy,
  8074. DeclLoc),
  8075. ObjCIvarDecl::Private, BW,
  8076. true);
  8077. AllIvarDecls.push_back(Ivar);
  8078. }
  8079. void Sema::ActOnFields(Scope* S,
  8080. SourceLocation RecLoc, Decl *EnclosingDecl,
  8081. llvm::ArrayRef<Decl *> Fields,
  8082. SourceLocation LBrac, SourceLocation RBrac,
  8083. AttributeList *Attr) {
  8084. assert(EnclosingDecl && "missing record or interface decl");
  8085. // If the decl this is being inserted into is invalid, then it may be a
  8086. // redeclaration or some other bogus case. Don't try to add fields to it.
  8087. if (EnclosingDecl->isInvalidDecl())
  8088. return;
  8089. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  8090. // Start counting up the number of named members; make sure to include
  8091. // members of anonymous structs and unions in the total.
  8092. unsigned NumNamedMembers = 0;
  8093. if (Record) {
  8094. for (RecordDecl::decl_iterator i = Record->decls_begin(),
  8095. e = Record->decls_end(); i != e; i++) {
  8096. if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
  8097. if (IFD->getDeclName())
  8098. ++NumNamedMembers;
  8099. }
  8100. }
  8101. // Verify that all the fields are okay.
  8102. SmallVector<FieldDecl*, 32> RecFields;
  8103. bool ARCErrReported = false;
  8104. for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  8105. i != end; ++i) {
  8106. FieldDecl *FD = cast<FieldDecl>(*i);
  8107. // Get the type for the field.
  8108. const Type *FDTy = FD->getType().getTypePtr();
  8109. if (!FD->isAnonymousStructOrUnion()) {
  8110. // Remember all fields written by the user.
  8111. RecFields.push_back(FD);
  8112. }
  8113. // If the field is already invalid for some reason, don't emit more
  8114. // diagnostics about it.
  8115. if (FD->isInvalidDecl()) {
  8116. EnclosingDecl->setInvalidDecl();
  8117. continue;
  8118. }
  8119. // C99 6.7.2.1p2:
  8120. // A structure or union shall not contain a member with
  8121. // incomplete or function type (hence, a structure shall not
  8122. // contain an instance of itself, but may contain a pointer to
  8123. // an instance of itself), except that the last member of a
  8124. // structure with more than one named member may have incomplete
  8125. // array type; such a structure (and any union containing,
  8126. // possibly recursively, a member that is such a structure)
  8127. // shall not be a member of a structure or an element of an
  8128. // array.
  8129. if (FDTy->isFunctionType()) {
  8130. // Field declared as a function.
  8131. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  8132. << FD->getDeclName();
  8133. FD->setInvalidDecl();
  8134. EnclosingDecl->setInvalidDecl();
  8135. continue;
  8136. } else if (FDTy->isIncompleteArrayType() && Record &&
  8137. ((i + 1 == Fields.end() && !Record->isUnion()) ||
  8138. ((getLangOptions().MicrosoftExt ||
  8139. getLangOptions().CPlusPlus) &&
  8140. (i + 1 == Fields.end() || Record->isUnion())))) {
  8141. // Flexible array member.
  8142. // Microsoft and g++ is more permissive regarding flexible array.
  8143. // It will accept flexible array in union and also
  8144. // as the sole element of a struct/class.
  8145. if (getLangOptions().MicrosoftExt) {
  8146. if (Record->isUnion())
  8147. Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
  8148. << FD->getDeclName();
  8149. else if (Fields.size() == 1)
  8150. Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
  8151. << FD->getDeclName() << Record->getTagKind();
  8152. } else if (getLangOptions().CPlusPlus) {
  8153. if (Record->isUnion())
  8154. Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
  8155. << FD->getDeclName();
  8156. else if (Fields.size() == 1)
  8157. Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
  8158. << FD->getDeclName() << Record->getTagKind();
  8159. } else if (NumNamedMembers < 1) {
  8160. Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
  8161. << FD->getDeclName();
  8162. FD->setInvalidDecl();
  8163. EnclosingDecl->setInvalidDecl();
  8164. continue;
  8165. }
  8166. if (!FD->getType()->isDependentType() &&
  8167. !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
  8168. Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
  8169. << FD->getDeclName() << FD->getType();
  8170. FD->setInvalidDecl();
  8171. EnclosingDecl->setInvalidDecl();
  8172. continue;
  8173. }
  8174. // Okay, we have a legal flexible array member at the end of the struct.
  8175. if (Record)
  8176. Record->setHasFlexibleArrayMember(true);
  8177. } else if (!FDTy->isDependentType() &&
  8178. RequireCompleteType(FD->getLocation(), FD->getType(),
  8179. diag::err_field_incomplete)) {
  8180. // Incomplete type
  8181. FD->setInvalidDecl();
  8182. EnclosingDecl->setInvalidDecl();
  8183. continue;
  8184. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  8185. if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
  8186. // If this is a member of a union, then entire union becomes "flexible".
  8187. if (Record && Record->isUnion()) {
  8188. Record->setHasFlexibleArrayMember(true);
  8189. } else {
  8190. // If this is a struct/class and this is not the last element, reject
  8191. // it. Note that GCC supports variable sized arrays in the middle of
  8192. // structures.
  8193. if (i + 1 != Fields.end())
  8194. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  8195. << FD->getDeclName() << FD->getType();
  8196. else {
  8197. // We support flexible arrays at the end of structs in
  8198. // other structs as an extension.
  8199. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  8200. << FD->getDeclName();
  8201. if (Record)
  8202. Record->setHasFlexibleArrayMember(true);
  8203. }
  8204. }
  8205. }
  8206. if (Record && FDTTy->getDecl()->hasObjectMember())
  8207. Record->setHasObjectMember(true);
  8208. } else if (FDTy->isObjCObjectType()) {
  8209. /// A field cannot be an Objective-c object
  8210. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  8211. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  8212. QualType T = Context.getObjCObjectPointerType(FD->getType());
  8213. FD->setType(T);
  8214. }
  8215. else if (!getLangOptions().CPlusPlus) {
  8216. if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) {
  8217. // It's an error in ARC if a field has lifetime.
  8218. // We don't want to report this in a system header, though,
  8219. // so we just make the field unavailable.
  8220. // FIXME: that's really not sufficient; we need to make the type
  8221. // itself invalid to, say, initialize or copy.
  8222. QualType T = FD->getType();
  8223. Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
  8224. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
  8225. SourceLocation loc = FD->getLocation();
  8226. if (getSourceManager().isInSystemHeader(loc)) {
  8227. if (!FD->hasAttr<UnavailableAttr>()) {
  8228. FD->addAttr(new (Context) UnavailableAttr(loc, Context,
  8229. "this system field has retaining ownership"));
  8230. }
  8231. } else {
  8232. Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
  8233. << T->isBlockPointerType();
  8234. }
  8235. ARCErrReported = true;
  8236. }
  8237. }
  8238. else if (getLangOptions().ObjC1 &&
  8239. getLangOptions().getGC() != LangOptions::NonGC &&
  8240. Record && !Record->hasObjectMember()) {
  8241. if (FD->getType()->isObjCObjectPointerType() ||
  8242. FD->getType().isObjCGCStrong())
  8243. Record->setHasObjectMember(true);
  8244. else if (Context.getAsArrayType(FD->getType())) {
  8245. QualType BaseType = Context.getBaseElementType(FD->getType());
  8246. if (BaseType->isRecordType() &&
  8247. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  8248. Record->setHasObjectMember(true);
  8249. else if (BaseType->isObjCObjectPointerType() ||
  8250. BaseType.isObjCGCStrong())
  8251. Record->setHasObjectMember(true);
  8252. }
  8253. }
  8254. }
  8255. // Keep track of the number of named members.
  8256. if (FD->getIdentifier())
  8257. ++NumNamedMembers;
  8258. }
  8259. // Okay, we successfully defined 'Record'.
  8260. if (Record) {
  8261. bool Completed = false;
  8262. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  8263. if (!CXXRecord->isInvalidDecl()) {
  8264. // Set access bits correctly on the directly-declared conversions.
  8265. UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
  8266. for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
  8267. I != E; ++I)
  8268. Convs->setAccess(I, (*I)->getAccess());
  8269. if (!CXXRecord->isDependentType()) {
  8270. // Objective-C Automatic Reference Counting:
  8271. // If a class has a non-static data member of Objective-C pointer
  8272. // type (or array thereof), it is a non-POD type and its
  8273. // default constructor (if any), copy constructor, copy assignment
  8274. // operator, and destructor are non-trivial.
  8275. //
  8276. // This rule is also handled by CXXRecordDecl::completeDefinition().
  8277. // However, here we check whether this particular class is only
  8278. // non-POD because of the presence of an Objective-C pointer member.
  8279. // If so, objects of this type cannot be shared between code compiled
  8280. // with instant objects and code compiled with manual retain/release.
  8281. if (getLangOptions().ObjCAutoRefCount &&
  8282. CXXRecord->hasObjectMember() &&
  8283. CXXRecord->getLinkage() == ExternalLinkage) {
  8284. if (CXXRecord->isPOD()) {
  8285. Diag(CXXRecord->getLocation(),
  8286. diag::warn_arc_non_pod_class_with_object_member)
  8287. << CXXRecord;
  8288. } else {
  8289. // FIXME: Fix-Its would be nice here, but finding a good location
  8290. // for them is going to be tricky.
  8291. if (CXXRecord->hasTrivialCopyConstructor())
  8292. Diag(CXXRecord->getLocation(),
  8293. diag::warn_arc_trivial_member_function_with_object_member)
  8294. << CXXRecord << 0;
  8295. if (CXXRecord->hasTrivialCopyAssignment())
  8296. Diag(CXXRecord->getLocation(),
  8297. diag::warn_arc_trivial_member_function_with_object_member)
  8298. << CXXRecord << 1;
  8299. if (CXXRecord->hasTrivialDestructor())
  8300. Diag(CXXRecord->getLocation(),
  8301. diag::warn_arc_trivial_member_function_with_object_member)
  8302. << CXXRecord << 2;
  8303. }
  8304. }
  8305. // Adjust user-defined destructor exception spec.
  8306. if (getLangOptions().CPlusPlus0x &&
  8307. CXXRecord->hasUserDeclaredDestructor())
  8308. AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
  8309. // Add any implicitly-declared members to this class.
  8310. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  8311. // If we have virtual base classes, we may end up finding multiple
  8312. // final overriders for a given virtual function. Check for this
  8313. // problem now.
  8314. if (CXXRecord->getNumVBases()) {
  8315. CXXFinalOverriderMap FinalOverriders;
  8316. CXXRecord->getFinalOverriders(FinalOverriders);
  8317. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  8318. MEnd = FinalOverriders.end();
  8319. M != MEnd; ++M) {
  8320. for (OverridingMethods::iterator SO = M->second.begin(),
  8321. SOEnd = M->second.end();
  8322. SO != SOEnd; ++SO) {
  8323. assert(SO->second.size() > 0 &&
  8324. "Virtual function without overridding functions?");
  8325. if (SO->second.size() == 1)
  8326. continue;
  8327. // C++ [class.virtual]p2:
  8328. // In a derived class, if a virtual member function of a base
  8329. // class subobject has more than one final overrider the
  8330. // program is ill-formed.
  8331. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  8332. << (NamedDecl *)M->first << Record;
  8333. Diag(M->first->getLocation(),
  8334. diag::note_overridden_virtual_function);
  8335. for (OverridingMethods::overriding_iterator
  8336. OM = SO->second.begin(),
  8337. OMEnd = SO->second.end();
  8338. OM != OMEnd; ++OM)
  8339. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  8340. << (NamedDecl *)M->first << OM->Method->getParent();
  8341. Record->setInvalidDecl();
  8342. }
  8343. }
  8344. CXXRecord->completeDefinition(&FinalOverriders);
  8345. Completed = true;
  8346. }
  8347. }
  8348. }
  8349. }
  8350. if (!Completed)
  8351. Record->completeDefinition();
  8352. // Now that the record is complete, do any delayed exception spec checks
  8353. // we were missing.
  8354. while (!DelayedDestructorExceptionSpecChecks.empty()) {
  8355. const CXXDestructorDecl *Dtor =
  8356. DelayedDestructorExceptionSpecChecks.back().first;
  8357. if (Dtor->getParent() != Record)
  8358. break;
  8359. assert(!Dtor->getParent()->isDependentType() &&
  8360. "Should not ever add destructors of templates into the list.");
  8361. CheckOverridingFunctionExceptionSpec(Dtor,
  8362. DelayedDestructorExceptionSpecChecks.back().second);
  8363. DelayedDestructorExceptionSpecChecks.pop_back();
  8364. }
  8365. } else {
  8366. ObjCIvarDecl **ClsFields =
  8367. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  8368. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  8369. ID->setEndOfDefinitionLoc(RBrac);
  8370. // Add ivar's to class's DeclContext.
  8371. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  8372. ClsFields[i]->setLexicalDeclContext(ID);
  8373. ID->addDecl(ClsFields[i]);
  8374. }
  8375. // Must enforce the rule that ivars in the base classes may not be
  8376. // duplicates.
  8377. if (ID->getSuperClass())
  8378. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  8379. } else if (ObjCImplementationDecl *IMPDecl =
  8380. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  8381. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  8382. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  8383. // Ivar declared in @implementation never belongs to the implementation.
  8384. // Only it is in implementation's lexical context.
  8385. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  8386. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  8387. } else if (ObjCCategoryDecl *CDecl =
  8388. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  8389. // case of ivars in class extension; all other cases have been
  8390. // reported as errors elsewhere.
  8391. // FIXME. Class extension does not have a LocEnd field.
  8392. // CDecl->setLocEnd(RBrac);
  8393. // Add ivar's to class extension's DeclContext.
  8394. // Diagnose redeclaration of private ivars.
  8395. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  8396. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  8397. if (IDecl) {
  8398. if (const ObjCIvarDecl *ClsIvar =
  8399. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  8400. Diag(ClsFields[i]->getLocation(),
  8401. diag::err_duplicate_ivar_declaration);
  8402. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  8403. continue;
  8404. }
  8405. for (const ObjCCategoryDecl *ClsExtDecl =
  8406. IDecl->getFirstClassExtension();
  8407. ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
  8408. if (const ObjCIvarDecl *ClsExtIvar =
  8409. ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  8410. Diag(ClsFields[i]->getLocation(),
  8411. diag::err_duplicate_ivar_declaration);
  8412. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  8413. continue;
  8414. }
  8415. }
  8416. }
  8417. ClsFields[i]->setLexicalDeclContext(CDecl);
  8418. CDecl->addDecl(ClsFields[i]);
  8419. }
  8420. }
  8421. }
  8422. if (Attr)
  8423. ProcessDeclAttributeList(S, Record, Attr);
  8424. // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
  8425. // set the visibility of this record.
  8426. if (Record && !Record->getDeclContext()->isRecord())
  8427. AddPushedVisibilityAttribute(Record);
  8428. }
  8429. /// \brief Determine whether the given integral value is representable within
  8430. /// the given type T.
  8431. static bool isRepresentableIntegerValue(ASTContext &Context,
  8432. llvm::APSInt &Value,
  8433. QualType T) {
  8434. assert(T->isIntegralType(Context) && "Integral type required!");
  8435. unsigned BitWidth = Context.getIntWidth(T);
  8436. if (Value.isUnsigned() || Value.isNonNegative()) {
  8437. if (T->isSignedIntegerOrEnumerationType())
  8438. --BitWidth;
  8439. return Value.getActiveBits() <= BitWidth;
  8440. }
  8441. return Value.getMinSignedBits() <= BitWidth;
  8442. }
  8443. // \brief Given an integral type, return the next larger integral type
  8444. // (or a NULL type of no such type exists).
  8445. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  8446. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  8447. // enum checking below.
  8448. assert(T->isIntegralType(Context) && "Integral type required!");
  8449. const unsigned NumTypes = 4;
  8450. QualType SignedIntegralTypes[NumTypes] = {
  8451. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  8452. };
  8453. QualType UnsignedIntegralTypes[NumTypes] = {
  8454. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  8455. Context.UnsignedLongLongTy
  8456. };
  8457. unsigned BitWidth = Context.getTypeSize(T);
  8458. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  8459. : UnsignedIntegralTypes;
  8460. for (unsigned I = 0; I != NumTypes; ++I)
  8461. if (Context.getTypeSize(Types[I]) > BitWidth)
  8462. return Types[I];
  8463. return QualType();
  8464. }
  8465. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  8466. EnumConstantDecl *LastEnumConst,
  8467. SourceLocation IdLoc,
  8468. IdentifierInfo *Id,
  8469. Expr *Val) {
  8470. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  8471. llvm::APSInt EnumVal(IntWidth);
  8472. QualType EltTy;
  8473. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  8474. Val = 0;
  8475. if (Val)
  8476. Val = DefaultLvalueConversion(Val).take();
  8477. if (Val) {
  8478. if (Enum->isDependentType() || Val->isTypeDependent())
  8479. EltTy = Context.DependentTy;
  8480. else {
  8481. SourceLocation ExpLoc;
  8482. if (getLangOptions().CPlusPlus0x && Enum->isFixed() &&
  8483. !getLangOptions().MicrosoftMode) {
  8484. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  8485. // constant-expression in the enumerator-definition shall be a converted
  8486. // constant expression of the underlying type.
  8487. EltTy = Enum->getIntegerType();
  8488. ExprResult Converted =
  8489. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  8490. CCEK_Enumerator);
  8491. if (Converted.isInvalid())
  8492. Val = 0;
  8493. else
  8494. Val = Converted.take();
  8495. } else if (!Val->isValueDependent() &&
  8496. !(Val = VerifyIntegerConstantExpression(Val,
  8497. &EnumVal).take())) {
  8498. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  8499. } else {
  8500. if (Enum->isFixed()) {
  8501. EltTy = Enum->getIntegerType();
  8502. // In Obj-C and Microsoft mode, require the enumeration value to be
  8503. // representable in the underlying type of the enumeration. In C++11,
  8504. // we perform a non-narrowing conversion as part of converted constant
  8505. // expression checking.
  8506. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  8507. if (getLangOptions().MicrosoftExt) {
  8508. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  8509. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
  8510. } else
  8511. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  8512. } else
  8513. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
  8514. } else if (getLangOptions().CPlusPlus) {
  8515. // C++11 [dcl.enum]p5:
  8516. // If the underlying type is not fixed, the type of each enumerator
  8517. // is the type of its initializing value:
  8518. // - If an initializer is specified for an enumerator, the
  8519. // initializing value has the same type as the expression.
  8520. EltTy = Val->getType();
  8521. } else {
  8522. // C99 6.7.2.2p2:
  8523. // The expression that defines the value of an enumeration constant
  8524. // shall be an integer constant expression that has a value
  8525. // representable as an int.
  8526. // Complain if the value is not representable in an int.
  8527. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  8528. Diag(IdLoc, diag::ext_enum_value_not_int)
  8529. << EnumVal.toString(10) << Val->getSourceRange()
  8530. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  8531. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  8532. // Force the type of the expression to 'int'.
  8533. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
  8534. }
  8535. EltTy = Val->getType();
  8536. }
  8537. }
  8538. }
  8539. }
  8540. if (!Val) {
  8541. if (Enum->isDependentType())
  8542. EltTy = Context.DependentTy;
  8543. else if (!LastEnumConst) {
  8544. // C++0x [dcl.enum]p5:
  8545. // If the underlying type is not fixed, the type of each enumerator
  8546. // is the type of its initializing value:
  8547. // - If no initializer is specified for the first enumerator, the
  8548. // initializing value has an unspecified integral type.
  8549. //
  8550. // GCC uses 'int' for its unspecified integral type, as does
  8551. // C99 6.7.2.2p3.
  8552. if (Enum->isFixed()) {
  8553. EltTy = Enum->getIntegerType();
  8554. }
  8555. else {
  8556. EltTy = Context.IntTy;
  8557. }
  8558. } else {
  8559. // Assign the last value + 1.
  8560. EnumVal = LastEnumConst->getInitVal();
  8561. ++EnumVal;
  8562. EltTy = LastEnumConst->getType();
  8563. // Check for overflow on increment.
  8564. if (EnumVal < LastEnumConst->getInitVal()) {
  8565. // C++0x [dcl.enum]p5:
  8566. // If the underlying type is not fixed, the type of each enumerator
  8567. // is the type of its initializing value:
  8568. //
  8569. // - Otherwise the type of the initializing value is the same as
  8570. // the type of the initializing value of the preceding enumerator
  8571. // unless the incremented value is not representable in that type,
  8572. // in which case the type is an unspecified integral type
  8573. // sufficient to contain the incremented value. If no such type
  8574. // exists, the program is ill-formed.
  8575. QualType T = getNextLargerIntegralType(Context, EltTy);
  8576. if (T.isNull() || Enum->isFixed()) {
  8577. // There is no integral type larger enough to represent this
  8578. // value. Complain, then allow the value to wrap around.
  8579. EnumVal = LastEnumConst->getInitVal();
  8580. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  8581. ++EnumVal;
  8582. if (Enum->isFixed())
  8583. // When the underlying type is fixed, this is ill-formed.
  8584. Diag(IdLoc, diag::err_enumerator_wrapped)
  8585. << EnumVal.toString(10)
  8586. << EltTy;
  8587. else
  8588. Diag(IdLoc, diag::warn_enumerator_too_large)
  8589. << EnumVal.toString(10);
  8590. } else {
  8591. EltTy = T;
  8592. }
  8593. // Retrieve the last enumerator's value, extent that type to the
  8594. // type that is supposed to be large enough to represent the incremented
  8595. // value, then increment.
  8596. EnumVal = LastEnumConst->getInitVal();
  8597. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  8598. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  8599. ++EnumVal;
  8600. // If we're not in C++, diagnose the overflow of enumerator values,
  8601. // which in C99 means that the enumerator value is not representable in
  8602. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  8603. // permits enumerator values that are representable in some larger
  8604. // integral type.
  8605. if (!getLangOptions().CPlusPlus && !T.isNull())
  8606. Diag(IdLoc, diag::warn_enum_value_overflow);
  8607. } else if (!getLangOptions().CPlusPlus &&
  8608. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  8609. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  8610. Diag(IdLoc, diag::ext_enum_value_not_int)
  8611. << EnumVal.toString(10) << 1;
  8612. }
  8613. }
  8614. }
  8615. if (!EltTy->isDependentType()) {
  8616. // Make the enumerator value match the signedness and size of the
  8617. // enumerator's type.
  8618. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  8619. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  8620. }
  8621. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  8622. Val, EnumVal);
  8623. }
  8624. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  8625. SourceLocation IdLoc, IdentifierInfo *Id,
  8626. AttributeList *Attr,
  8627. SourceLocation EqualLoc, Expr *Val) {
  8628. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  8629. EnumConstantDecl *LastEnumConst =
  8630. cast_or_null<EnumConstantDecl>(lastEnumConst);
  8631. // The scope passed in may not be a decl scope. Zip up the scope tree until
  8632. // we find one that is.
  8633. S = getNonFieldDeclScope(S);
  8634. // Verify that there isn't already something declared with this name in this
  8635. // scope.
  8636. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  8637. ForRedeclaration);
  8638. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  8639. // Maybe we will complain about the shadowed template parameter.
  8640. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  8641. // Just pretend that we didn't see the previous declaration.
  8642. PrevDecl = 0;
  8643. }
  8644. if (PrevDecl) {
  8645. // When in C++, we may get a TagDecl with the same name; in this case the
  8646. // enum constant will 'hide' the tag.
  8647. assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  8648. "Received TagDecl when not in C++!");
  8649. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  8650. if (isa<EnumConstantDecl>(PrevDecl))
  8651. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  8652. else
  8653. Diag(IdLoc, diag::err_redefinition) << Id;
  8654. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  8655. return 0;
  8656. }
  8657. }
  8658. // C++ [class.mem]p13:
  8659. // If T is the name of a class, then each of the following shall have a
  8660. // name different from T:
  8661. // - every enumerator of every member of class T that is an enumerated
  8662. // type
  8663. if (CXXRecordDecl *Record
  8664. = dyn_cast<CXXRecordDecl>(
  8665. TheEnumDecl->getDeclContext()->getRedeclContext()))
  8666. if (Record->getIdentifier() && Record->getIdentifier() == Id)
  8667. Diag(IdLoc, diag::err_member_name_of_class) << Id;
  8668. EnumConstantDecl *New =
  8669. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  8670. if (New) {
  8671. // Process attributes.
  8672. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  8673. // Register this decl in the current scope stack.
  8674. New->setAccess(TheEnumDecl->getAccess());
  8675. PushOnScopeChains(New, S);
  8676. }
  8677. return New;
  8678. }
  8679. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
  8680. SourceLocation RBraceLoc, Decl *EnumDeclX,
  8681. Decl **Elements, unsigned NumElements,
  8682. Scope *S, AttributeList *Attr) {
  8683. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  8684. QualType EnumType = Context.getTypeDeclType(Enum);
  8685. if (Attr)
  8686. ProcessDeclAttributeList(S, Enum, Attr);
  8687. if (Enum->isDependentType()) {
  8688. for (unsigned i = 0; i != NumElements; ++i) {
  8689. EnumConstantDecl *ECD =
  8690. cast_or_null<EnumConstantDecl>(Elements[i]);
  8691. if (!ECD) continue;
  8692. ECD->setType(EnumType);
  8693. }
  8694. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  8695. return;
  8696. }
  8697. // TODO: If the result value doesn't fit in an int, it must be a long or long
  8698. // long value. ISO C does not support this, but GCC does as an extension,
  8699. // emit a warning.
  8700. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  8701. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  8702. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  8703. // Verify that all the values are okay, compute the size of the values, and
  8704. // reverse the list.
  8705. unsigned NumNegativeBits = 0;
  8706. unsigned NumPositiveBits = 0;
  8707. // Keep track of whether all elements have type int.
  8708. bool AllElementsInt = true;
  8709. for (unsigned i = 0; i != NumElements; ++i) {
  8710. EnumConstantDecl *ECD =
  8711. cast_or_null<EnumConstantDecl>(Elements[i]);
  8712. if (!ECD) continue; // Already issued a diagnostic.
  8713. const llvm::APSInt &InitVal = ECD->getInitVal();
  8714. // Keep track of the size of positive and negative values.
  8715. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  8716. NumPositiveBits = std::max(NumPositiveBits,
  8717. (unsigned)InitVal.getActiveBits());
  8718. else
  8719. NumNegativeBits = std::max(NumNegativeBits,
  8720. (unsigned)InitVal.getMinSignedBits());
  8721. // Keep track of whether every enum element has type int (very commmon).
  8722. if (AllElementsInt)
  8723. AllElementsInt = ECD->getType() == Context.IntTy;
  8724. }
  8725. // Figure out the type that should be used for this enum.
  8726. QualType BestType;
  8727. unsigned BestWidth;
  8728. // C++0x N3000 [conv.prom]p3:
  8729. // An rvalue of an unscoped enumeration type whose underlying
  8730. // type is not fixed can be converted to an rvalue of the first
  8731. // of the following types that can represent all the values of
  8732. // the enumeration: int, unsigned int, long int, unsigned long
  8733. // int, long long int, or unsigned long long int.
  8734. // C99 6.4.4.3p2:
  8735. // An identifier declared as an enumeration constant has type int.
  8736. // The C99 rule is modified by a gcc extension
  8737. QualType BestPromotionType;
  8738. bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
  8739. // -fshort-enums is the equivalent to specifying the packed attribute on all
  8740. // enum definitions.
  8741. if (LangOpts.ShortEnums)
  8742. Packed = true;
  8743. if (Enum->isFixed()) {
  8744. BestType = Enum->getIntegerType();
  8745. if (BestType->isPromotableIntegerType())
  8746. BestPromotionType = Context.getPromotedIntegerType(BestType);
  8747. else
  8748. BestPromotionType = BestType;
  8749. // We don't need to set BestWidth, because BestType is going to be the type
  8750. // of the enumerators, but we do anyway because otherwise some compilers
  8751. // warn that it might be used uninitialized.
  8752. BestWidth = CharWidth;
  8753. }
  8754. else if (NumNegativeBits) {
  8755. // If there is a negative value, figure out the smallest integer type (of
  8756. // int/long/longlong) that fits.
  8757. // If it's packed, check also if it fits a char or a short.
  8758. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  8759. BestType = Context.SignedCharTy;
  8760. BestWidth = CharWidth;
  8761. } else if (Packed && NumNegativeBits <= ShortWidth &&
  8762. NumPositiveBits < ShortWidth) {
  8763. BestType = Context.ShortTy;
  8764. BestWidth = ShortWidth;
  8765. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  8766. BestType = Context.IntTy;
  8767. BestWidth = IntWidth;
  8768. } else {
  8769. BestWidth = Context.getTargetInfo().getLongWidth();
  8770. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  8771. BestType = Context.LongTy;
  8772. } else {
  8773. BestWidth = Context.getTargetInfo().getLongLongWidth();
  8774. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  8775. Diag(Enum->getLocation(), diag::warn_enum_too_large);
  8776. BestType = Context.LongLongTy;
  8777. }
  8778. }
  8779. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  8780. } else {
  8781. // If there is no negative value, figure out the smallest type that fits
  8782. // all of the enumerator values.
  8783. // If it's packed, check also if it fits a char or a short.
  8784. if (Packed && NumPositiveBits <= CharWidth) {
  8785. BestType = Context.UnsignedCharTy;
  8786. BestPromotionType = Context.IntTy;
  8787. BestWidth = CharWidth;
  8788. } else if (Packed && NumPositiveBits <= ShortWidth) {
  8789. BestType = Context.UnsignedShortTy;
  8790. BestPromotionType = Context.IntTy;
  8791. BestWidth = ShortWidth;
  8792. } else if (NumPositiveBits <= IntWidth) {
  8793. BestType = Context.UnsignedIntTy;
  8794. BestWidth = IntWidth;
  8795. BestPromotionType
  8796. = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
  8797. ? Context.UnsignedIntTy : Context.IntTy;
  8798. } else if (NumPositiveBits <=
  8799. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  8800. BestType = Context.UnsignedLongTy;
  8801. BestPromotionType
  8802. = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
  8803. ? Context.UnsignedLongTy : Context.LongTy;
  8804. } else {
  8805. BestWidth = Context.getTargetInfo().getLongLongWidth();
  8806. assert(NumPositiveBits <= BestWidth &&
  8807. "How could an initializer get larger than ULL?");
  8808. BestType = Context.UnsignedLongLongTy;
  8809. BestPromotionType
  8810. = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
  8811. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  8812. }
  8813. }
  8814. // Loop over all of the enumerator constants, changing their types to match
  8815. // the type of the enum if needed.
  8816. for (unsigned i = 0; i != NumElements; ++i) {
  8817. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  8818. if (!ECD) continue; // Already issued a diagnostic.
  8819. // Standard C says the enumerators have int type, but we allow, as an
  8820. // extension, the enumerators to be larger than int size. If each
  8821. // enumerator value fits in an int, type it as an int, otherwise type it the
  8822. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  8823. // that X has type 'int', not 'unsigned'.
  8824. // Determine whether the value fits into an int.
  8825. llvm::APSInt InitVal = ECD->getInitVal();
  8826. // If it fits into an integer type, force it. Otherwise force it to match
  8827. // the enum decl type.
  8828. QualType NewTy;
  8829. unsigned NewWidth;
  8830. bool NewSign;
  8831. if (!getLangOptions().CPlusPlus &&
  8832. !Enum->isFixed() &&
  8833. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  8834. NewTy = Context.IntTy;
  8835. NewWidth = IntWidth;
  8836. NewSign = true;
  8837. } else if (ECD->getType() == BestType) {
  8838. // Already the right type!
  8839. if (getLangOptions().CPlusPlus)
  8840. // C++ [dcl.enum]p4: Following the closing brace of an
  8841. // enum-specifier, each enumerator has the type of its
  8842. // enumeration.
  8843. ECD->setType(EnumType);
  8844. continue;
  8845. } else {
  8846. NewTy = BestType;
  8847. NewWidth = BestWidth;
  8848. NewSign = BestType->isSignedIntegerOrEnumerationType();
  8849. }
  8850. // Adjust the APSInt value.
  8851. InitVal = InitVal.extOrTrunc(NewWidth);
  8852. InitVal.setIsSigned(NewSign);
  8853. ECD->setInitVal(InitVal);
  8854. // Adjust the Expr initializer and type.
  8855. if (ECD->getInitExpr() &&
  8856. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  8857. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  8858. CK_IntegralCast,
  8859. ECD->getInitExpr(),
  8860. /*base paths*/ 0,
  8861. VK_RValue));
  8862. if (getLangOptions().CPlusPlus)
  8863. // C++ [dcl.enum]p4: Following the closing brace of an
  8864. // enum-specifier, each enumerator has the type of its
  8865. // enumeration.
  8866. ECD->setType(EnumType);
  8867. else
  8868. ECD->setType(NewTy);
  8869. }
  8870. Enum->completeDefinition(BestType, BestPromotionType,
  8871. NumPositiveBits, NumNegativeBits);
  8872. }
  8873. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  8874. SourceLocation StartLoc,
  8875. SourceLocation EndLoc) {
  8876. StringLiteral *AsmString = cast<StringLiteral>(expr);
  8877. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  8878. AsmString, StartLoc,
  8879. EndLoc);
  8880. CurContext->addDecl(New);
  8881. return New;
  8882. }
  8883. DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
  8884. SourceLocation ImportLoc,
  8885. ModuleIdPath Path) {
  8886. Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
  8887. Module::AllVisible,
  8888. /*IsIncludeDirective=*/false);
  8889. if (!Mod)
  8890. return true;
  8891. llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
  8892. Module *ModCheck = Mod;
  8893. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  8894. // If we've run out of module parents, just drop the remaining identifiers.
  8895. // We need the length to be consistent.
  8896. if (!ModCheck)
  8897. break;
  8898. ModCheck = ModCheck->Parent;
  8899. IdentifierLocs.push_back(Path[I].second);
  8900. }
  8901. ImportDecl *Import = ImportDecl::Create(Context,
  8902. Context.getTranslationUnitDecl(),
  8903. AtLoc.isValid()? AtLoc : ImportLoc,
  8904. Mod, IdentifierLocs);
  8905. Context.getTranslationUnitDecl()->addDecl(Import);
  8906. return Import;
  8907. }
  8908. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  8909. SourceLocation PragmaLoc,
  8910. SourceLocation NameLoc) {
  8911. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  8912. if (PrevDecl) {
  8913. PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
  8914. } else {
  8915. (void)WeakUndeclaredIdentifiers.insert(
  8916. std::pair<IdentifierInfo*,WeakInfo>
  8917. (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
  8918. }
  8919. }
  8920. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  8921. IdentifierInfo* AliasName,
  8922. SourceLocation PragmaLoc,
  8923. SourceLocation NameLoc,
  8924. SourceLocation AliasNameLoc) {
  8925. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  8926. LookupOrdinaryName);
  8927. WeakInfo W = WeakInfo(Name, NameLoc);
  8928. if (PrevDecl) {
  8929. if (!PrevDecl->hasAttr<AliasAttr>())
  8930. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  8931. DeclApplyPragmaWeak(TUScope, ND, W);
  8932. } else {
  8933. (void)WeakUndeclaredIdentifiers.insert(
  8934. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  8935. }
  8936. }
  8937. Decl *Sema::getObjCDeclContext() const {
  8938. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  8939. }
  8940. AvailabilityResult Sema::getCurContextAvailability() const {
  8941. const Decl *D = cast<Decl>(getCurLexicalContext());
  8942. // A category implicitly has the availability of the interface.
  8943. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
  8944. D = CatD->getClassInterface();
  8945. return D->getAvailability();
  8946. }