SemaType.cpp 261 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083
  1. //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
  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 type-related semantic analysis.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "TypeLocBuilder.h"
  15. #include "clang/AST/ASTConsumer.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/ASTMutationListener.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/TypeLoc.h"
  23. #include "clang/AST/TypeLocVisitor.h"
  24. #include "clang/Lex/Preprocessor.h"
  25. #include "clang/Basic/PartialDiagnostic.h"
  26. #include "clang/Basic/TargetInfo.h"
  27. #include "clang/Lex/Preprocessor.h"
  28. #include "clang/Sema/DeclSpec.h"
  29. #include "clang/Sema/DelayedDiagnostic.h"
  30. #include "clang/Sema/Lookup.h"
  31. #include "clang/Sema/ScopeInfo.h"
  32. #include "clang/Sema/Template.h"
  33. #include "llvm/ADT/SmallPtrSet.h"
  34. #include "llvm/ADT/SmallString.h"
  35. #include "llvm/Support/ErrorHandling.h"
  36. using namespace clang;
  37. enum TypeDiagSelector {
  38. TDS_Function,
  39. TDS_Pointer,
  40. TDS_ObjCObjOrBlock
  41. };
  42. /// isOmittedBlockReturnType - Return true if this declarator is missing a
  43. /// return type because this is a omitted return type on a block literal.
  44. static bool isOmittedBlockReturnType(const Declarator &D) {
  45. if (D.getContext() != Declarator::BlockLiteralContext ||
  46. D.getDeclSpec().hasTypeSpecifier())
  47. return false;
  48. if (D.getNumTypeObjects() == 0)
  49. return true; // ^{ ... }
  50. if (D.getNumTypeObjects() == 1 &&
  51. D.getTypeObject(0).Kind == DeclaratorChunk::Function)
  52. return true; // ^(int X, float Y) { ... }
  53. return false;
  54. }
  55. /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
  56. /// doesn't apply to the given type.
  57. static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
  58. QualType type) {
  59. TypeDiagSelector WhichType;
  60. bool useExpansionLoc = true;
  61. switch (attr.getKind()) {
  62. case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break;
  63. case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
  64. default:
  65. // Assume everything else was a function attribute.
  66. WhichType = TDS_Function;
  67. useExpansionLoc = false;
  68. break;
  69. }
  70. SourceLocation loc = attr.getLoc();
  71. StringRef name = attr.getName()->getName();
  72. // The GC attributes are usually written with macros; special-case them.
  73. IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
  74. : nullptr;
  75. if (useExpansionLoc && loc.isMacroID() && II) {
  76. if (II->isStr("strong")) {
  77. if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
  78. } else if (II->isStr("weak")) {
  79. if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
  80. }
  81. }
  82. S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
  83. << type;
  84. }
  85. // objc_gc applies to Objective-C pointers or, otherwise, to the
  86. // smallest available pointer type (i.e. 'void*' in 'void**').
  87. #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
  88. case AttributeList::AT_ObjCGC: \
  89. case AttributeList::AT_ObjCOwnership
  90. // Function type attributes.
  91. #define FUNCTION_TYPE_ATTRS_CASELIST \
  92. case AttributeList::AT_NoReturn: \
  93. case AttributeList::AT_CDecl: \
  94. case AttributeList::AT_FastCall: \
  95. case AttributeList::AT_StdCall: \
  96. case AttributeList::AT_ThisCall: \
  97. case AttributeList::AT_Pascal: \
  98. case AttributeList::AT_VectorCall: \
  99. case AttributeList::AT_MSABI: \
  100. case AttributeList::AT_SysVABI: \
  101. case AttributeList::AT_Regparm: \
  102. case AttributeList::AT_Pcs: \
  103. case AttributeList::AT_IntelOclBicc
  104. // Microsoft-specific type qualifiers.
  105. #define MS_TYPE_ATTRS_CASELIST \
  106. case AttributeList::AT_Ptr32: \
  107. case AttributeList::AT_Ptr64: \
  108. case AttributeList::AT_SPtr: \
  109. case AttributeList::AT_UPtr
  110. // Nullability qualifiers.
  111. #define NULLABILITY_TYPE_ATTRS_CASELIST \
  112. case AttributeList::AT_TypeNonNull: \
  113. case AttributeList::AT_TypeNullable: \
  114. case AttributeList::AT_TypeNullUnspecified
  115. namespace {
  116. /// An object which stores processing state for the entire
  117. /// GetTypeForDeclarator process.
  118. class TypeProcessingState {
  119. Sema &sema;
  120. /// The declarator being processed.
  121. Declarator &declarator;
  122. /// The index of the declarator chunk we're currently processing.
  123. /// May be the total number of valid chunks, indicating the
  124. /// DeclSpec.
  125. unsigned chunkIndex;
  126. /// Whether there are non-trivial modifications to the decl spec.
  127. bool trivial;
  128. /// Whether we saved the attributes in the decl spec.
  129. bool hasSavedAttrs;
  130. /// The original set of attributes on the DeclSpec.
  131. SmallVector<AttributeList*, 2> savedAttrs;
  132. /// A list of attributes to diagnose the uselessness of when the
  133. /// processing is complete.
  134. SmallVector<AttributeList*, 2> ignoredTypeAttrs;
  135. public:
  136. TypeProcessingState(Sema &sema, Declarator &declarator)
  137. : sema(sema), declarator(declarator),
  138. chunkIndex(declarator.getNumTypeObjects()),
  139. trivial(true), hasSavedAttrs(false) {}
  140. Sema &getSema() const {
  141. return sema;
  142. }
  143. Declarator &getDeclarator() const {
  144. return declarator;
  145. }
  146. bool isProcessingDeclSpec() const {
  147. return chunkIndex == declarator.getNumTypeObjects();
  148. }
  149. unsigned getCurrentChunkIndex() const {
  150. return chunkIndex;
  151. }
  152. void setCurrentChunkIndex(unsigned idx) {
  153. assert(idx <= declarator.getNumTypeObjects());
  154. chunkIndex = idx;
  155. }
  156. AttributeList *&getCurrentAttrListRef() const {
  157. if (isProcessingDeclSpec())
  158. return getMutableDeclSpec().getAttributes().getListRef();
  159. return declarator.getTypeObject(chunkIndex).getAttrListRef();
  160. }
  161. /// Save the current set of attributes on the DeclSpec.
  162. void saveDeclSpecAttrs() {
  163. // Don't try to save them multiple times.
  164. if (hasSavedAttrs) return;
  165. DeclSpec &spec = getMutableDeclSpec();
  166. for (AttributeList *attr = spec.getAttributes().getList(); attr;
  167. attr = attr->getNext())
  168. savedAttrs.push_back(attr);
  169. trivial &= savedAttrs.empty();
  170. hasSavedAttrs = true;
  171. }
  172. /// Record that we had nowhere to put the given type attribute.
  173. /// We will diagnose such attributes later.
  174. void addIgnoredTypeAttr(AttributeList &attr) {
  175. ignoredTypeAttrs.push_back(&attr);
  176. }
  177. /// Diagnose all the ignored type attributes, given that the
  178. /// declarator worked out to the given type.
  179. void diagnoseIgnoredTypeAttrs(QualType type) const {
  180. for (auto *Attr : ignoredTypeAttrs)
  181. diagnoseBadTypeAttribute(getSema(), *Attr, type);
  182. }
  183. ~TypeProcessingState() {
  184. if (trivial) return;
  185. restoreDeclSpecAttrs();
  186. }
  187. private:
  188. DeclSpec &getMutableDeclSpec() const {
  189. return const_cast<DeclSpec&>(declarator.getDeclSpec());
  190. }
  191. void restoreDeclSpecAttrs() {
  192. assert(hasSavedAttrs);
  193. if (savedAttrs.empty()) {
  194. getMutableDeclSpec().getAttributes().set(nullptr);
  195. return;
  196. }
  197. getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
  198. for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
  199. savedAttrs[i]->setNext(savedAttrs[i+1]);
  200. savedAttrs.back()->setNext(nullptr);
  201. }
  202. };
  203. }
  204. static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
  205. attr.setNext(head);
  206. head = &attr;
  207. }
  208. static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
  209. if (head == &attr) {
  210. head = attr.getNext();
  211. return;
  212. }
  213. AttributeList *cur = head;
  214. while (true) {
  215. assert(cur && cur->getNext() && "ran out of attrs?");
  216. if (cur->getNext() == &attr) {
  217. cur->setNext(attr.getNext());
  218. return;
  219. }
  220. cur = cur->getNext();
  221. }
  222. }
  223. static void moveAttrFromListToList(AttributeList &attr,
  224. AttributeList *&fromList,
  225. AttributeList *&toList) {
  226. spliceAttrOutOfList(attr, fromList);
  227. spliceAttrIntoList(attr, toList);
  228. }
  229. /// The location of a type attribute.
  230. enum TypeAttrLocation {
  231. /// The attribute is in the decl-specifier-seq.
  232. TAL_DeclSpec,
  233. /// The attribute is part of a DeclaratorChunk.
  234. TAL_DeclChunk,
  235. /// The attribute is immediately after the declaration's name.
  236. TAL_DeclName
  237. };
  238. static void processTypeAttrs(TypeProcessingState &state,
  239. QualType &type, TypeAttrLocation TAL,
  240. AttributeList *attrs);
  241. static bool handleFunctionTypeAttr(TypeProcessingState &state,
  242. AttributeList &attr,
  243. QualType &type);
  244. static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
  245. AttributeList &attr,
  246. QualType &type);
  247. static bool handleObjCGCTypeAttr(TypeProcessingState &state,
  248. AttributeList &attr, QualType &type);
  249. static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
  250. AttributeList &attr, QualType &type);
  251. static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
  252. AttributeList &attr, QualType &type) {
  253. if (attr.getKind() == AttributeList::AT_ObjCGC)
  254. return handleObjCGCTypeAttr(state, attr, type);
  255. assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
  256. return handleObjCOwnershipTypeAttr(state, attr, type);
  257. }
  258. /// Given the index of a declarator chunk, check whether that chunk
  259. /// directly specifies the return type of a function and, if so, find
  260. /// an appropriate place for it.
  261. ///
  262. /// \param i - a notional index which the search will start
  263. /// immediately inside
  264. ///
  265. /// \param onlyBlockPointers Whether we should only look into block
  266. /// pointer types (vs. all pointer types).
  267. static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
  268. unsigned i,
  269. bool onlyBlockPointers) {
  270. assert(i <= declarator.getNumTypeObjects());
  271. DeclaratorChunk *result = nullptr;
  272. // First, look inwards past parens for a function declarator.
  273. for (; i != 0; --i) {
  274. DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
  275. switch (fnChunk.Kind) {
  276. case DeclaratorChunk::Paren:
  277. continue;
  278. // If we find anything except a function, bail out.
  279. case DeclaratorChunk::Pointer:
  280. case DeclaratorChunk::BlockPointer:
  281. case DeclaratorChunk::Array:
  282. case DeclaratorChunk::Reference:
  283. case DeclaratorChunk::MemberPointer:
  284. case DeclaratorChunk::Pipe:
  285. return result;
  286. // If we do find a function declarator, scan inwards from that,
  287. // looking for a (block-)pointer declarator.
  288. case DeclaratorChunk::Function:
  289. for (--i; i != 0; --i) {
  290. DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
  291. switch (ptrChunk.Kind) {
  292. case DeclaratorChunk::Paren:
  293. case DeclaratorChunk::Array:
  294. case DeclaratorChunk::Function:
  295. case DeclaratorChunk::Reference:
  296. case DeclaratorChunk::Pipe:
  297. continue;
  298. case DeclaratorChunk::MemberPointer:
  299. case DeclaratorChunk::Pointer:
  300. if (onlyBlockPointers)
  301. continue;
  302. // fallthrough
  303. case DeclaratorChunk::BlockPointer:
  304. result = &ptrChunk;
  305. goto continue_outer;
  306. }
  307. llvm_unreachable("bad declarator chunk kind");
  308. }
  309. // If we run out of declarators doing that, we're done.
  310. return result;
  311. }
  312. llvm_unreachable("bad declarator chunk kind");
  313. // Okay, reconsider from our new point.
  314. continue_outer: ;
  315. }
  316. // Ran out of chunks, bail out.
  317. return result;
  318. }
  319. /// Given that an objc_gc attribute was written somewhere on a
  320. /// declaration *other* than on the declarator itself (for which, use
  321. /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
  322. /// didn't apply in whatever position it was written in, try to move
  323. /// it to a more appropriate position.
  324. static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
  325. AttributeList &attr,
  326. QualType type) {
  327. Declarator &declarator = state.getDeclarator();
  328. // Move it to the outermost normal or block pointer declarator.
  329. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
  330. DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
  331. switch (chunk.Kind) {
  332. case DeclaratorChunk::Pointer:
  333. case DeclaratorChunk::BlockPointer: {
  334. // But don't move an ARC ownership attribute to the return type
  335. // of a block.
  336. DeclaratorChunk *destChunk = nullptr;
  337. if (state.isProcessingDeclSpec() &&
  338. attr.getKind() == AttributeList::AT_ObjCOwnership)
  339. destChunk = maybeMovePastReturnType(declarator, i - 1,
  340. /*onlyBlockPointers=*/true);
  341. if (!destChunk) destChunk = &chunk;
  342. moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
  343. destChunk->getAttrListRef());
  344. return;
  345. }
  346. case DeclaratorChunk::Paren:
  347. case DeclaratorChunk::Array:
  348. continue;
  349. // We may be starting at the return type of a block.
  350. case DeclaratorChunk::Function:
  351. if (state.isProcessingDeclSpec() &&
  352. attr.getKind() == AttributeList::AT_ObjCOwnership) {
  353. if (DeclaratorChunk *dest = maybeMovePastReturnType(
  354. declarator, i,
  355. /*onlyBlockPointers=*/true)) {
  356. moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
  357. dest->getAttrListRef());
  358. return;
  359. }
  360. }
  361. goto error;
  362. // Don't walk through these.
  363. case DeclaratorChunk::Reference:
  364. case DeclaratorChunk::MemberPointer:
  365. case DeclaratorChunk::Pipe:
  366. goto error;
  367. }
  368. }
  369. error:
  370. diagnoseBadTypeAttribute(state.getSema(), attr, type);
  371. }
  372. /// Distribute an objc_gc type attribute that was written on the
  373. /// declarator.
  374. static void
  375. distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
  376. AttributeList &attr,
  377. QualType &declSpecType) {
  378. Declarator &declarator = state.getDeclarator();
  379. // objc_gc goes on the innermost pointer to something that's not a
  380. // pointer.
  381. unsigned innermost = -1U;
  382. bool considerDeclSpec = true;
  383. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  384. DeclaratorChunk &chunk = declarator.getTypeObject(i);
  385. switch (chunk.Kind) {
  386. case DeclaratorChunk::Pointer:
  387. case DeclaratorChunk::BlockPointer:
  388. innermost = i;
  389. continue;
  390. case DeclaratorChunk::Reference:
  391. case DeclaratorChunk::MemberPointer:
  392. case DeclaratorChunk::Paren:
  393. case DeclaratorChunk::Array:
  394. case DeclaratorChunk::Pipe:
  395. continue;
  396. case DeclaratorChunk::Function:
  397. considerDeclSpec = false;
  398. goto done;
  399. }
  400. }
  401. done:
  402. // That might actually be the decl spec if we weren't blocked by
  403. // anything in the declarator.
  404. if (considerDeclSpec) {
  405. if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
  406. // Splice the attribute into the decl spec. Prevents the
  407. // attribute from being applied multiple times and gives
  408. // the source-location-filler something to work with.
  409. state.saveDeclSpecAttrs();
  410. moveAttrFromListToList(attr, declarator.getAttrListRef(),
  411. declarator.getMutableDeclSpec().getAttributes().getListRef());
  412. return;
  413. }
  414. }
  415. // Otherwise, if we found an appropriate chunk, splice the attribute
  416. // into it.
  417. if (innermost != -1U) {
  418. moveAttrFromListToList(attr, declarator.getAttrListRef(),
  419. declarator.getTypeObject(innermost).getAttrListRef());
  420. return;
  421. }
  422. // Otherwise, diagnose when we're done building the type.
  423. spliceAttrOutOfList(attr, declarator.getAttrListRef());
  424. state.addIgnoredTypeAttr(attr);
  425. }
  426. /// A function type attribute was written somewhere in a declaration
  427. /// *other* than on the declarator itself or in the decl spec. Given
  428. /// that it didn't apply in whatever position it was written in, try
  429. /// to move it to a more appropriate position.
  430. static void distributeFunctionTypeAttr(TypeProcessingState &state,
  431. AttributeList &attr,
  432. QualType type) {
  433. Declarator &declarator = state.getDeclarator();
  434. // Try to push the attribute from the return type of a function to
  435. // the function itself.
  436. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
  437. DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
  438. switch (chunk.Kind) {
  439. case DeclaratorChunk::Function:
  440. moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
  441. chunk.getAttrListRef());
  442. return;
  443. case DeclaratorChunk::Paren:
  444. case DeclaratorChunk::Pointer:
  445. case DeclaratorChunk::BlockPointer:
  446. case DeclaratorChunk::Array:
  447. case DeclaratorChunk::Reference:
  448. case DeclaratorChunk::MemberPointer:
  449. case DeclaratorChunk::Pipe:
  450. continue;
  451. }
  452. }
  453. diagnoseBadTypeAttribute(state.getSema(), attr, type);
  454. }
  455. /// Try to distribute a function type attribute to the innermost
  456. /// function chunk or type. Returns true if the attribute was
  457. /// distributed, false if no location was found.
  458. static bool
  459. distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
  460. AttributeList &attr,
  461. AttributeList *&attrList,
  462. QualType &declSpecType) {
  463. Declarator &declarator = state.getDeclarator();
  464. // Put it on the innermost function chunk, if there is one.
  465. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  466. DeclaratorChunk &chunk = declarator.getTypeObject(i);
  467. if (chunk.Kind != DeclaratorChunk::Function) continue;
  468. moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
  469. return true;
  470. }
  471. return handleFunctionTypeAttr(state, attr, declSpecType);
  472. }
  473. /// A function type attribute was written in the decl spec. Try to
  474. /// apply it somewhere.
  475. static void
  476. distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
  477. AttributeList &attr,
  478. QualType &declSpecType) {
  479. state.saveDeclSpecAttrs();
  480. // C++11 attributes before the decl specifiers actually appertain to
  481. // the declarators. Move them straight there. We don't support the
  482. // 'put them wherever you like' semantics we allow for GNU attributes.
  483. if (attr.isCXX11Attribute()) {
  484. moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
  485. state.getDeclarator().getAttrListRef());
  486. return;
  487. }
  488. // Try to distribute to the innermost.
  489. if (distributeFunctionTypeAttrToInnermost(state, attr,
  490. state.getCurrentAttrListRef(),
  491. declSpecType))
  492. return;
  493. // If that failed, diagnose the bad attribute when the declarator is
  494. // fully built.
  495. state.addIgnoredTypeAttr(attr);
  496. }
  497. /// A function type attribute was written on the declarator. Try to
  498. /// apply it somewhere.
  499. static void
  500. distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
  501. AttributeList &attr,
  502. QualType &declSpecType) {
  503. Declarator &declarator = state.getDeclarator();
  504. // Try to distribute to the innermost.
  505. if (distributeFunctionTypeAttrToInnermost(state, attr,
  506. declarator.getAttrListRef(),
  507. declSpecType))
  508. return;
  509. // If that failed, diagnose the bad attribute when the declarator is
  510. // fully built.
  511. spliceAttrOutOfList(attr, declarator.getAttrListRef());
  512. state.addIgnoredTypeAttr(attr);
  513. }
  514. /// \brief Given that there are attributes written on the declarator
  515. /// itself, try to distribute any type attributes to the appropriate
  516. /// declarator chunk.
  517. ///
  518. /// These are attributes like the following:
  519. /// int f ATTR;
  520. /// int (f ATTR)();
  521. /// but not necessarily this:
  522. /// int f() ATTR;
  523. static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
  524. QualType &declSpecType) {
  525. // Collect all the type attributes from the declarator itself.
  526. assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
  527. AttributeList *attr = state.getDeclarator().getAttributes();
  528. AttributeList *next;
  529. do {
  530. next = attr->getNext();
  531. // Do not distribute C++11 attributes. They have strict rules for what
  532. // they appertain to.
  533. if (attr->isCXX11Attribute())
  534. continue;
  535. switch (attr->getKind()) {
  536. OBJC_POINTER_TYPE_ATTRS_CASELIST:
  537. distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
  538. break;
  539. case AttributeList::AT_NSReturnsRetained:
  540. if (!state.getSema().getLangOpts().ObjCAutoRefCount)
  541. break;
  542. // fallthrough
  543. FUNCTION_TYPE_ATTRS_CASELIST:
  544. distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
  545. break;
  546. MS_TYPE_ATTRS_CASELIST:
  547. // Microsoft type attributes cannot go after the declarator-id.
  548. continue;
  549. NULLABILITY_TYPE_ATTRS_CASELIST:
  550. // Nullability specifiers cannot go after the declarator-id.
  551. // Objective-C __kindof does not get distributed.
  552. case AttributeList::AT_ObjCKindOf:
  553. continue;
  554. default:
  555. break;
  556. }
  557. } while ((attr = next));
  558. }
  559. /// Add a synthetic '()' to a block-literal declarator if it is
  560. /// required, given the return type.
  561. static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
  562. QualType declSpecType) {
  563. Declarator &declarator = state.getDeclarator();
  564. // First, check whether the declarator would produce a function,
  565. // i.e. whether the innermost semantic chunk is a function.
  566. if (declarator.isFunctionDeclarator()) {
  567. // If so, make that declarator a prototyped declarator.
  568. declarator.getFunctionTypeInfo().hasPrototype = true;
  569. return;
  570. }
  571. // If there are any type objects, the type as written won't name a
  572. // function, regardless of the decl spec type. This is because a
  573. // block signature declarator is always an abstract-declarator, and
  574. // abstract-declarators can't just be parentheses chunks. Therefore
  575. // we need to build a function chunk unless there are no type
  576. // objects and the decl spec type is a function.
  577. if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
  578. return;
  579. // Note that there *are* cases with invalid declarators where
  580. // declarators consist solely of parentheses. In general, these
  581. // occur only in failed efforts to make function declarators, so
  582. // faking up the function chunk is still the right thing to do.
  583. // Otherwise, we need to fake up a function declarator.
  584. SourceLocation loc = declarator.getLocStart();
  585. // ...and *prepend* it to the declarator.
  586. SourceLocation NoLoc;
  587. declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
  588. /*HasProto=*/true,
  589. /*IsAmbiguous=*/false,
  590. /*LParenLoc=*/NoLoc,
  591. /*ArgInfo=*/nullptr,
  592. /*NumArgs=*/0,
  593. /*EllipsisLoc=*/NoLoc,
  594. /*RParenLoc=*/NoLoc,
  595. /*TypeQuals=*/0,
  596. /*RefQualifierIsLvalueRef=*/true,
  597. /*RefQualifierLoc=*/NoLoc,
  598. /*ConstQualifierLoc=*/NoLoc,
  599. /*VolatileQualifierLoc=*/NoLoc,
  600. /*RestrictQualifierLoc=*/NoLoc,
  601. /*MutableLoc=*/NoLoc, EST_None,
  602. /*ESpecRange=*/SourceRange(),
  603. /*Exceptions=*/nullptr,
  604. /*ExceptionRanges=*/nullptr,
  605. /*NumExceptions=*/0,
  606. /*NoexceptExpr=*/nullptr,
  607. /*ExceptionSpecTokens=*/nullptr,
  608. loc, loc, declarator));
  609. // For consistency, make sure the state still has us as processing
  610. // the decl spec.
  611. assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
  612. state.setCurrentChunkIndex(declarator.getNumTypeObjects());
  613. }
  614. static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
  615. unsigned &TypeQuals,
  616. QualType TypeSoFar,
  617. unsigned RemoveTQs,
  618. unsigned DiagID) {
  619. // If this occurs outside a template instantiation, warn the user about
  620. // it; they probably didn't mean to specify a redundant qualifier.
  621. typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
  622. for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
  623. QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
  624. QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
  625. if (!(RemoveTQs & Qual.first))
  626. continue;
  627. if (S.ActiveTemplateInstantiations.empty()) {
  628. if (TypeQuals & Qual.first)
  629. S.Diag(Qual.second, DiagID)
  630. << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
  631. << FixItHint::CreateRemoval(Qual.second);
  632. }
  633. TypeQuals &= ~Qual.first;
  634. }
  635. }
  636. /// Apply Objective-C type arguments to the given type.
  637. static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
  638. ArrayRef<TypeSourceInfo *> typeArgs,
  639. SourceRange typeArgsRange,
  640. bool failOnError = false) {
  641. // We can only apply type arguments to an Objective-C class type.
  642. const auto *objcObjectType = type->getAs<ObjCObjectType>();
  643. if (!objcObjectType || !objcObjectType->getInterface()) {
  644. S.Diag(loc, diag::err_objc_type_args_non_class)
  645. << type
  646. << typeArgsRange;
  647. if (failOnError)
  648. return QualType();
  649. return type;
  650. }
  651. // The class type must be parameterized.
  652. ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
  653. ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
  654. if (!typeParams) {
  655. S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
  656. << objcClass->getDeclName()
  657. << FixItHint::CreateRemoval(typeArgsRange);
  658. if (failOnError)
  659. return QualType();
  660. return type;
  661. }
  662. // The type must not already be specialized.
  663. if (objcObjectType->isSpecialized()) {
  664. S.Diag(loc, diag::err_objc_type_args_specialized_class)
  665. << type
  666. << FixItHint::CreateRemoval(typeArgsRange);
  667. if (failOnError)
  668. return QualType();
  669. return type;
  670. }
  671. // Check the type arguments.
  672. SmallVector<QualType, 4> finalTypeArgs;
  673. unsigned numTypeParams = typeParams->size();
  674. bool anyPackExpansions = false;
  675. for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
  676. TypeSourceInfo *typeArgInfo = typeArgs[i];
  677. QualType typeArg = typeArgInfo->getType();
  678. // Type arguments cannot have explicit qualifiers or nullability.
  679. // We ignore indirect sources of these, e.g. behind typedefs or
  680. // template arguments.
  681. if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
  682. bool diagnosed = false;
  683. SourceRange rangeToRemove;
  684. if (auto attr = qual.getAs<AttributedTypeLoc>()) {
  685. rangeToRemove = attr.getLocalSourceRange();
  686. if (attr.getTypePtr()->getImmediateNullability()) {
  687. typeArg = attr.getTypePtr()->getModifiedType();
  688. S.Diag(attr.getLocStart(),
  689. diag::err_objc_type_arg_explicit_nullability)
  690. << typeArg << FixItHint::CreateRemoval(rangeToRemove);
  691. diagnosed = true;
  692. }
  693. }
  694. if (!diagnosed) {
  695. S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified)
  696. << typeArg << typeArg.getQualifiers().getAsString()
  697. << FixItHint::CreateRemoval(rangeToRemove);
  698. }
  699. }
  700. // Remove qualifiers even if they're non-local.
  701. typeArg = typeArg.getUnqualifiedType();
  702. finalTypeArgs.push_back(typeArg);
  703. if (typeArg->getAs<PackExpansionType>())
  704. anyPackExpansions = true;
  705. // Find the corresponding type parameter, if there is one.
  706. ObjCTypeParamDecl *typeParam = nullptr;
  707. if (!anyPackExpansions) {
  708. if (i < numTypeParams) {
  709. typeParam = typeParams->begin()[i];
  710. } else {
  711. // Too many arguments.
  712. S.Diag(loc, diag::err_objc_type_args_wrong_arity)
  713. << false
  714. << objcClass->getDeclName()
  715. << (unsigned)typeArgs.size()
  716. << numTypeParams;
  717. S.Diag(objcClass->getLocation(), diag::note_previous_decl)
  718. << objcClass;
  719. if (failOnError)
  720. return QualType();
  721. return type;
  722. }
  723. }
  724. // Objective-C object pointer types must be substitutable for the bounds.
  725. if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
  726. // If we don't have a type parameter to match against, assume
  727. // everything is fine. There was a prior pack expansion that
  728. // means we won't be able to match anything.
  729. if (!typeParam) {
  730. assert(anyPackExpansions && "Too many arguments?");
  731. continue;
  732. }
  733. // Retrieve the bound.
  734. QualType bound = typeParam->getUnderlyingType();
  735. const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
  736. // Determine whether the type argument is substitutable for the bound.
  737. if (typeArgObjC->isObjCIdType()) {
  738. // When the type argument is 'id', the only acceptable type
  739. // parameter bound is 'id'.
  740. if (boundObjC->isObjCIdType())
  741. continue;
  742. } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
  743. // Otherwise, we follow the assignability rules.
  744. continue;
  745. }
  746. // Diagnose the mismatch.
  747. S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
  748. diag::err_objc_type_arg_does_not_match_bound)
  749. << typeArg << bound << typeParam->getDeclName();
  750. S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
  751. << typeParam->getDeclName();
  752. if (failOnError)
  753. return QualType();
  754. return type;
  755. }
  756. // Block pointer types are permitted for unqualified 'id' bounds.
  757. if (typeArg->isBlockPointerType()) {
  758. // If we don't have a type parameter to match against, assume
  759. // everything is fine. There was a prior pack expansion that
  760. // means we won't be able to match anything.
  761. if (!typeParam) {
  762. assert(anyPackExpansions && "Too many arguments?");
  763. continue;
  764. }
  765. // Retrieve the bound.
  766. QualType bound = typeParam->getUnderlyingType();
  767. if (bound->isBlockCompatibleObjCPointerType(S.Context))
  768. continue;
  769. // Diagnose the mismatch.
  770. S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
  771. diag::err_objc_type_arg_does_not_match_bound)
  772. << typeArg << bound << typeParam->getDeclName();
  773. S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
  774. << typeParam->getDeclName();
  775. if (failOnError)
  776. return QualType();
  777. return type;
  778. }
  779. // Dependent types will be checked at instantiation time.
  780. if (typeArg->isDependentType()) {
  781. continue;
  782. }
  783. // Diagnose non-id-compatible type arguments.
  784. S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
  785. diag::err_objc_type_arg_not_id_compatible)
  786. << typeArg
  787. << typeArgInfo->getTypeLoc().getSourceRange();
  788. if (failOnError)
  789. return QualType();
  790. return type;
  791. }
  792. // Make sure we didn't have the wrong number of arguments.
  793. if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
  794. S.Diag(loc, diag::err_objc_type_args_wrong_arity)
  795. << (typeArgs.size() < typeParams->size())
  796. << objcClass->getDeclName()
  797. << (unsigned)finalTypeArgs.size()
  798. << (unsigned)numTypeParams;
  799. S.Diag(objcClass->getLocation(), diag::note_previous_decl)
  800. << objcClass;
  801. if (failOnError)
  802. return QualType();
  803. return type;
  804. }
  805. // Success. Form the specialized type.
  806. return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
  807. }
  808. /// Apply Objective-C protocol qualifiers to the given type.
  809. static QualType applyObjCProtocolQualifiers(
  810. Sema &S, SourceLocation loc, SourceRange range, QualType type,
  811. ArrayRef<ObjCProtocolDecl *> protocols,
  812. const SourceLocation *protocolLocs,
  813. bool failOnError = false) {
  814. ASTContext &ctx = S.Context;
  815. if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
  816. // FIXME: Check for protocols to which the class type is already
  817. // known to conform.
  818. return ctx.getObjCObjectType(objT->getBaseType(),
  819. objT->getTypeArgsAsWritten(),
  820. protocols,
  821. objT->isKindOfTypeAsWritten());
  822. }
  823. if (type->isObjCObjectType()) {
  824. // Silently overwrite any existing protocol qualifiers.
  825. // TODO: determine whether that's the right thing to do.
  826. // FIXME: Check for protocols to which the class type is already
  827. // known to conform.
  828. return ctx.getObjCObjectType(type, { }, protocols, false);
  829. }
  830. // id<protocol-list>
  831. if (type->isObjCIdType()) {
  832. const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
  833. type = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, { }, protocols,
  834. objPtr->isKindOfType());
  835. return ctx.getObjCObjectPointerType(type);
  836. }
  837. // Class<protocol-list>
  838. if (type->isObjCClassType()) {
  839. const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
  840. type = ctx.getObjCObjectType(ctx.ObjCBuiltinClassTy, { }, protocols,
  841. objPtr->isKindOfType());
  842. return ctx.getObjCObjectPointerType(type);
  843. }
  844. S.Diag(loc, diag::err_invalid_protocol_qualifiers)
  845. << range;
  846. if (failOnError)
  847. return QualType();
  848. return type;
  849. }
  850. QualType Sema::BuildObjCObjectType(QualType BaseType,
  851. SourceLocation Loc,
  852. SourceLocation TypeArgsLAngleLoc,
  853. ArrayRef<TypeSourceInfo *> TypeArgs,
  854. SourceLocation TypeArgsRAngleLoc,
  855. SourceLocation ProtocolLAngleLoc,
  856. ArrayRef<ObjCProtocolDecl *> Protocols,
  857. ArrayRef<SourceLocation> ProtocolLocs,
  858. SourceLocation ProtocolRAngleLoc,
  859. bool FailOnError) {
  860. QualType Result = BaseType;
  861. if (!TypeArgs.empty()) {
  862. Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
  863. SourceRange(TypeArgsLAngleLoc,
  864. TypeArgsRAngleLoc),
  865. FailOnError);
  866. if (FailOnError && Result.isNull())
  867. return QualType();
  868. }
  869. if (!Protocols.empty()) {
  870. Result = applyObjCProtocolQualifiers(*this, Loc,
  871. SourceRange(ProtocolLAngleLoc,
  872. ProtocolRAngleLoc),
  873. Result, Protocols,
  874. ProtocolLocs.data(),
  875. FailOnError);
  876. if (FailOnError && Result.isNull())
  877. return QualType();
  878. }
  879. return Result;
  880. }
  881. TypeResult Sema::actOnObjCProtocolQualifierType(
  882. SourceLocation lAngleLoc,
  883. ArrayRef<Decl *> protocols,
  884. ArrayRef<SourceLocation> protocolLocs,
  885. SourceLocation rAngleLoc) {
  886. // Form id<protocol-list>.
  887. QualType Result = Context.getObjCObjectType(
  888. Context.ObjCBuiltinIdTy, { },
  889. llvm::makeArrayRef(
  890. (ObjCProtocolDecl * const *)protocols.data(),
  891. protocols.size()),
  892. false);
  893. Result = Context.getObjCObjectPointerType(Result);
  894. TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
  895. TypeLoc ResultTL = ResultTInfo->getTypeLoc();
  896. auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
  897. ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
  898. auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
  899. .castAs<ObjCObjectTypeLoc>();
  900. ObjCObjectTL.setHasBaseTypeAsWritten(false);
  901. ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
  902. // No type arguments.
  903. ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
  904. ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
  905. // Fill in protocol qualifiers.
  906. ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
  907. ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
  908. for (unsigned i = 0, n = protocols.size(); i != n; ++i)
  909. ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
  910. // We're done. Return the completed type to the parser.
  911. return CreateParsedType(Result, ResultTInfo);
  912. }
  913. TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
  914. Scope *S,
  915. SourceLocation Loc,
  916. ParsedType BaseType,
  917. SourceLocation TypeArgsLAngleLoc,
  918. ArrayRef<ParsedType> TypeArgs,
  919. SourceLocation TypeArgsRAngleLoc,
  920. SourceLocation ProtocolLAngleLoc,
  921. ArrayRef<Decl *> Protocols,
  922. ArrayRef<SourceLocation> ProtocolLocs,
  923. SourceLocation ProtocolRAngleLoc) {
  924. TypeSourceInfo *BaseTypeInfo = nullptr;
  925. QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
  926. if (T.isNull())
  927. return true;
  928. // Handle missing type-source info.
  929. if (!BaseTypeInfo)
  930. BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  931. // Extract type arguments.
  932. SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
  933. for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
  934. TypeSourceInfo *TypeArgInfo = nullptr;
  935. QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
  936. if (TypeArg.isNull()) {
  937. ActualTypeArgInfos.clear();
  938. break;
  939. }
  940. assert(TypeArgInfo && "No type source info?");
  941. ActualTypeArgInfos.push_back(TypeArgInfo);
  942. }
  943. // Build the object type.
  944. QualType Result = BuildObjCObjectType(
  945. T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
  946. TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
  947. ProtocolLAngleLoc,
  948. llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
  949. Protocols.size()),
  950. ProtocolLocs, ProtocolRAngleLoc,
  951. /*FailOnError=*/false);
  952. if (Result == T)
  953. return BaseType;
  954. // Create source information for this type.
  955. TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
  956. TypeLoc ResultTL = ResultTInfo->getTypeLoc();
  957. // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
  958. // object pointer type. Fill in source information for it.
  959. if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
  960. // The '*' is implicit.
  961. ObjCObjectPointerTL.setStarLoc(SourceLocation());
  962. ResultTL = ObjCObjectPointerTL.getPointeeLoc();
  963. }
  964. auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
  965. // Type argument information.
  966. if (ObjCObjectTL.getNumTypeArgs() > 0) {
  967. assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
  968. ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
  969. ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
  970. for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
  971. ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
  972. } else {
  973. ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
  974. ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
  975. }
  976. // Protocol qualifier information.
  977. if (ObjCObjectTL.getNumProtocols() > 0) {
  978. assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
  979. ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
  980. ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
  981. for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
  982. ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
  983. } else {
  984. ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
  985. ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
  986. }
  987. // Base type.
  988. ObjCObjectTL.setHasBaseTypeAsWritten(true);
  989. if (ObjCObjectTL.getType() == T)
  990. ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
  991. else
  992. ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
  993. // We're done. Return the completed type to the parser.
  994. return CreateParsedType(Result, ResultTInfo);
  995. }
  996. /// \brief Convert the specified declspec to the appropriate type
  997. /// object.
  998. /// \param state Specifies the declarator containing the declaration specifier
  999. /// to be converted, along with other associated processing state.
  1000. /// \returns The type described by the declaration specifiers. This function
  1001. /// never returns null.
  1002. static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
  1003. // FIXME: Should move the logic from DeclSpec::Finish to here for validity
  1004. // checking.
  1005. Sema &S = state.getSema();
  1006. Declarator &declarator = state.getDeclarator();
  1007. const DeclSpec &DS = declarator.getDeclSpec();
  1008. SourceLocation DeclLoc = declarator.getIdentifierLoc();
  1009. if (DeclLoc.isInvalid())
  1010. DeclLoc = DS.getLocStart();
  1011. ASTContext &Context = S.Context;
  1012. QualType Result;
  1013. switch (DS.getTypeSpecType()) {
  1014. case DeclSpec::TST_void:
  1015. Result = Context.VoidTy;
  1016. break;
  1017. case DeclSpec::TST_char:
  1018. if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
  1019. Result = Context.CharTy;
  1020. else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
  1021. Result = Context.SignedCharTy;
  1022. else {
  1023. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
  1024. "Unknown TSS value");
  1025. Result = Context.UnsignedCharTy;
  1026. }
  1027. break;
  1028. case DeclSpec::TST_wchar:
  1029. if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
  1030. Result = Context.WCharTy;
  1031. else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
  1032. S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
  1033. << DS.getSpecifierName(DS.getTypeSpecType(),
  1034. Context.getPrintingPolicy());
  1035. Result = Context.getSignedWCharType();
  1036. } else {
  1037. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
  1038. "Unknown TSS value");
  1039. S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
  1040. << DS.getSpecifierName(DS.getTypeSpecType(),
  1041. Context.getPrintingPolicy());
  1042. Result = Context.getUnsignedWCharType();
  1043. }
  1044. break;
  1045. case DeclSpec::TST_char16:
  1046. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
  1047. "Unknown TSS value");
  1048. Result = Context.Char16Ty;
  1049. break;
  1050. case DeclSpec::TST_char32:
  1051. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
  1052. "Unknown TSS value");
  1053. Result = Context.Char32Ty;
  1054. break;
  1055. case DeclSpec::TST_unspecified:
  1056. // If this is a missing declspec in a block literal return context, then it
  1057. // is inferred from the return statements inside the block.
  1058. // The declspec is always missing in a lambda expr context; it is either
  1059. // specified with a trailing return type or inferred.
  1060. if (S.getLangOpts().CPlusPlus14 &&
  1061. declarator.getContext() == Declarator::LambdaExprContext) {
  1062. // In C++1y, a lambda's implicit return type is 'auto'.
  1063. Result = Context.getAutoDeductType();
  1064. break;
  1065. } else if (declarator.getContext() == Declarator::LambdaExprContext ||
  1066. isOmittedBlockReturnType(declarator)) {
  1067. Result = Context.DependentTy;
  1068. break;
  1069. }
  1070. // Unspecified typespec defaults to int in C90. However, the C90 grammar
  1071. // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
  1072. // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
  1073. // Note that the one exception to this is function definitions, which are
  1074. // allowed to be completely missing a declspec. This is handled in the
  1075. // parser already though by it pretending to have seen an 'int' in this
  1076. // case.
  1077. if (S.getLangOpts().ImplicitInt) {
  1078. // In C89 mode, we only warn if there is a completely missing declspec
  1079. // when one is not allowed.
  1080. if (DS.isEmpty()) {
  1081. S.Diag(DeclLoc, diag::ext_missing_declspec)
  1082. << DS.getSourceRange()
  1083. << FixItHint::CreateInsertion(DS.getLocStart(), "int");
  1084. }
  1085. } else if (!DS.hasTypeSpecifier()) {
  1086. // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
  1087. // "At least one type specifier shall be given in the declaration
  1088. // specifiers in each declaration, and in the specifier-qualifier list in
  1089. // each struct declaration and type name."
  1090. if (S.getLangOpts().CPlusPlus) {
  1091. S.Diag(DeclLoc, diag::err_missing_type_specifier)
  1092. << DS.getSourceRange();
  1093. // When this occurs in C++ code, often something is very broken with the
  1094. // value being declared, poison it as invalid so we don't get chains of
  1095. // errors.
  1096. declarator.setInvalidType(true);
  1097. } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
  1098. S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
  1099. << DS.getSourceRange();
  1100. declarator.setInvalidType(true);
  1101. } else {
  1102. S.Diag(DeclLoc, diag::ext_missing_type_specifier)
  1103. << DS.getSourceRange();
  1104. }
  1105. }
  1106. // FALL THROUGH.
  1107. case DeclSpec::TST_int: {
  1108. if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
  1109. switch (DS.getTypeSpecWidth()) {
  1110. case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
  1111. case DeclSpec::TSW_short: Result = Context.ShortTy; break;
  1112. case DeclSpec::TSW_long: Result = Context.LongTy; break;
  1113. case DeclSpec::TSW_longlong:
  1114. Result = Context.LongLongTy;
  1115. // 'long long' is a C99 or C++11 feature.
  1116. if (!S.getLangOpts().C99) {
  1117. if (S.getLangOpts().CPlusPlus)
  1118. S.Diag(DS.getTypeSpecWidthLoc(),
  1119. S.getLangOpts().CPlusPlus11 ?
  1120. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  1121. else
  1122. S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
  1123. }
  1124. break;
  1125. }
  1126. } else {
  1127. switch (DS.getTypeSpecWidth()) {
  1128. case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
  1129. case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
  1130. case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
  1131. case DeclSpec::TSW_longlong:
  1132. Result = Context.UnsignedLongLongTy;
  1133. // 'long long' is a C99 or C++11 feature.
  1134. if (!S.getLangOpts().C99) {
  1135. if (S.getLangOpts().CPlusPlus)
  1136. S.Diag(DS.getTypeSpecWidthLoc(),
  1137. S.getLangOpts().CPlusPlus11 ?
  1138. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  1139. else
  1140. S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
  1141. }
  1142. break;
  1143. }
  1144. }
  1145. break;
  1146. }
  1147. case DeclSpec::TST_int128:
  1148. if (!S.Context.getTargetInfo().hasInt128Type())
  1149. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
  1150. if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
  1151. Result = Context.UnsignedInt128Ty;
  1152. else
  1153. Result = Context.Int128Ty;
  1154. break;
  1155. case DeclSpec::TST_half: Result = Context.HalfTy; break;
  1156. case DeclSpec::TST_float: Result = Context.FloatTy; break;
  1157. case DeclSpec::TST_double:
  1158. if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
  1159. Result = Context.LongDoubleTy;
  1160. else
  1161. Result = Context.DoubleTy;
  1162. if (S.getLangOpts().OpenCL &&
  1163. !((S.getLangOpts().OpenCLVersion >= 120) ||
  1164. S.getOpenCLOptions().cl_khr_fp64)) {
  1165. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
  1166. << Result << "cl_khr_fp64";
  1167. declarator.setInvalidType(true);
  1168. }
  1169. break;
  1170. case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
  1171. case DeclSpec::TST_decimal32: // _Decimal32
  1172. case DeclSpec::TST_decimal64: // _Decimal64
  1173. case DeclSpec::TST_decimal128: // _Decimal128
  1174. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
  1175. Result = Context.IntTy;
  1176. declarator.setInvalidType(true);
  1177. break;
  1178. case DeclSpec::TST_class:
  1179. case DeclSpec::TST_enum:
  1180. case DeclSpec::TST_union:
  1181. case DeclSpec::TST_struct:
  1182. case DeclSpec::TST_interface: {
  1183. TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
  1184. if (!D) {
  1185. // This can happen in C++ with ambiguous lookups.
  1186. Result = Context.IntTy;
  1187. declarator.setInvalidType(true);
  1188. break;
  1189. }
  1190. // If the type is deprecated or unavailable, diagnose it.
  1191. S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
  1192. assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
  1193. DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
  1194. // TypeQuals handled by caller.
  1195. Result = Context.getTypeDeclType(D);
  1196. // In both C and C++, make an ElaboratedType.
  1197. ElaboratedTypeKeyword Keyword
  1198. = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
  1199. Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
  1200. break;
  1201. }
  1202. case DeclSpec::TST_typename: {
  1203. assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
  1204. DS.getTypeSpecSign() == 0 &&
  1205. "Can't handle qualifiers on typedef names yet!");
  1206. Result = S.GetTypeFromParser(DS.getRepAsType());
  1207. if (Result.isNull()) {
  1208. declarator.setInvalidType(true);
  1209. } else if (S.getLangOpts().OpenCL) {
  1210. if (Result->getAs<AtomicType>()) {
  1211. StringRef TypeName = Result.getBaseTypeIdentifier()->getName();
  1212. bool NoExtTypes =
  1213. llvm::StringSwitch<bool>(TypeName)
  1214. .Cases("atomic_int", "atomic_uint", "atomic_float",
  1215. "atomic_flag", true)
  1216. .Default(false);
  1217. if (!S.getOpenCLOptions().cl_khr_int64_base_atomics && !NoExtTypes) {
  1218. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
  1219. << Result << "cl_khr_int64_base_atomics";
  1220. declarator.setInvalidType(true);
  1221. }
  1222. if (!S.getOpenCLOptions().cl_khr_int64_extended_atomics &&
  1223. !NoExtTypes) {
  1224. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
  1225. << Result << "cl_khr_int64_extended_atomics";
  1226. declarator.setInvalidType(true);
  1227. }
  1228. if (!S.getOpenCLOptions().cl_khr_fp64 &&
  1229. !TypeName.compare("atomic_double")) {
  1230. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
  1231. << Result << "cl_khr_fp64";
  1232. declarator.setInvalidType(true);
  1233. }
  1234. } else if (!S.getOpenCLOptions().cl_khr_gl_msaa_sharing &&
  1235. (Result->isImage2dMSAAT() || Result->isImage2dArrayMSAAT() ||
  1236. Result->isImage2dArrayMSAATDepth() ||
  1237. Result->isImage2dMSAATDepth())) {
  1238. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
  1239. << Result << "cl_khr_gl_msaa_sharing";
  1240. declarator.setInvalidType(true);
  1241. }
  1242. }
  1243. // TypeQuals handled by caller.
  1244. break;
  1245. }
  1246. case DeclSpec::TST_typeofType:
  1247. // FIXME: Preserve type source info.
  1248. Result = S.GetTypeFromParser(DS.getRepAsType());
  1249. assert(!Result.isNull() && "Didn't get a type for typeof?");
  1250. if (!Result->isDependentType())
  1251. if (const TagType *TT = Result->getAs<TagType>())
  1252. S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
  1253. // TypeQuals handled by caller.
  1254. Result = Context.getTypeOfType(Result);
  1255. break;
  1256. case DeclSpec::TST_typeofExpr: {
  1257. Expr *E = DS.getRepAsExpr();
  1258. assert(E && "Didn't get an expression for typeof?");
  1259. // TypeQuals handled by caller.
  1260. Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
  1261. if (Result.isNull()) {
  1262. Result = Context.IntTy;
  1263. declarator.setInvalidType(true);
  1264. }
  1265. break;
  1266. }
  1267. case DeclSpec::TST_decltype: {
  1268. Expr *E = DS.getRepAsExpr();
  1269. assert(E && "Didn't get an expression for decltype?");
  1270. // TypeQuals handled by caller.
  1271. Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
  1272. if (Result.isNull()) {
  1273. Result = Context.IntTy;
  1274. declarator.setInvalidType(true);
  1275. }
  1276. break;
  1277. }
  1278. case DeclSpec::TST_underlyingType:
  1279. Result = S.GetTypeFromParser(DS.getRepAsType());
  1280. assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
  1281. Result = S.BuildUnaryTransformType(Result,
  1282. UnaryTransformType::EnumUnderlyingType,
  1283. DS.getTypeSpecTypeLoc());
  1284. if (Result.isNull()) {
  1285. Result = Context.IntTy;
  1286. declarator.setInvalidType(true);
  1287. }
  1288. break;
  1289. case DeclSpec::TST_auto:
  1290. // TypeQuals handled by caller.
  1291. // If auto is mentioned in a lambda parameter context, convert it to a
  1292. // template parameter type immediately, with the appropriate depth and
  1293. // index, and update sema's state (LambdaScopeInfo) for the current lambda
  1294. // being analyzed (which tracks the invented type template parameter).
  1295. if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
  1296. sema::LambdaScopeInfo *LSI = S.getCurLambda();
  1297. assert(LSI && "No LambdaScopeInfo on the stack!");
  1298. const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
  1299. const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
  1300. const bool IsParameterPack = declarator.hasEllipsis();
  1301. // Turns out we must create the TemplateTypeParmDecl here to
  1302. // retrieve the corresponding template parameter type.
  1303. TemplateTypeParmDecl *CorrespondingTemplateParam =
  1304. TemplateTypeParmDecl::Create(Context,
  1305. // Temporarily add to the TranslationUnit DeclContext. When the
  1306. // associated TemplateParameterList is attached to a template
  1307. // declaration (such as FunctionTemplateDecl), the DeclContext
  1308. // for each template parameter gets updated appropriately via
  1309. // a call to AdoptTemplateParameterList.
  1310. Context.getTranslationUnitDecl(),
  1311. /*KeyLoc*/ SourceLocation(),
  1312. /*NameLoc*/ declarator.getLocStart(),
  1313. TemplateParameterDepth,
  1314. AutoParameterPosition, // our template param index
  1315. /* Identifier*/ nullptr, false, IsParameterPack);
  1316. LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
  1317. // Replace the 'auto' in the function parameter with this invented
  1318. // template type parameter.
  1319. Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
  1320. } else {
  1321. Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
  1322. }
  1323. break;
  1324. case DeclSpec::TST_auto_type:
  1325. Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
  1326. break;
  1327. case DeclSpec::TST_decltype_auto:
  1328. Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
  1329. /*IsDependent*/ false);
  1330. break;
  1331. case DeclSpec::TST_unknown_anytype:
  1332. Result = Context.UnknownAnyTy;
  1333. break;
  1334. case DeclSpec::TST_atomic:
  1335. Result = S.GetTypeFromParser(DS.getRepAsType());
  1336. assert(!Result.isNull() && "Didn't get a type for _Atomic?");
  1337. Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
  1338. if (Result.isNull()) {
  1339. Result = Context.IntTy;
  1340. declarator.setInvalidType(true);
  1341. }
  1342. break;
  1343. case DeclSpec::TST_error:
  1344. Result = Context.IntTy;
  1345. declarator.setInvalidType(true);
  1346. break;
  1347. }
  1348. // Handle complex types.
  1349. if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
  1350. if (S.getLangOpts().Freestanding)
  1351. S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
  1352. Result = Context.getComplexType(Result);
  1353. } else if (DS.isTypeAltiVecVector()) {
  1354. unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
  1355. assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
  1356. VectorType::VectorKind VecKind = VectorType::AltiVecVector;
  1357. if (DS.isTypeAltiVecPixel())
  1358. VecKind = VectorType::AltiVecPixel;
  1359. else if (DS.isTypeAltiVecBool())
  1360. VecKind = VectorType::AltiVecBool;
  1361. Result = Context.getVectorType(Result, 128/typeSize, VecKind);
  1362. }
  1363. // FIXME: Imaginary.
  1364. if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
  1365. S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
  1366. // Before we process any type attributes, synthesize a block literal
  1367. // function declarator if necessary.
  1368. if (declarator.getContext() == Declarator::BlockLiteralContext)
  1369. maybeSynthesizeBlockSignature(state, Result);
  1370. // Apply any type attributes from the decl spec. This may cause the
  1371. // list of type attributes to be temporarily saved while the type
  1372. // attributes are pushed around.
  1373. // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
  1374. if (!DS.isTypeSpecPipe())
  1375. processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList());
  1376. // Apply const/volatile/restrict qualifiers to T.
  1377. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  1378. // Warn about CV qualifiers on function types.
  1379. // C99 6.7.3p8:
  1380. // If the specification of a function type includes any type qualifiers,
  1381. // the behavior is undefined.
  1382. // C++11 [dcl.fct]p7:
  1383. // The effect of a cv-qualifier-seq in a function declarator is not the
  1384. // same as adding cv-qualification on top of the function type. In the
  1385. // latter case, the cv-qualifiers are ignored.
  1386. if (TypeQuals && Result->isFunctionType()) {
  1387. diagnoseAndRemoveTypeQualifiers(
  1388. S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
  1389. S.getLangOpts().CPlusPlus
  1390. ? diag::warn_typecheck_function_qualifiers_ignored
  1391. : diag::warn_typecheck_function_qualifiers_unspecified);
  1392. // No diagnostic for 'restrict' or '_Atomic' applied to a
  1393. // function type; we'll diagnose those later, in BuildQualifiedType.
  1394. }
  1395. // C++11 [dcl.ref]p1:
  1396. // Cv-qualified references are ill-formed except when the
  1397. // cv-qualifiers are introduced through the use of a typedef-name
  1398. // or decltype-specifier, in which case the cv-qualifiers are ignored.
  1399. //
  1400. // There don't appear to be any other contexts in which a cv-qualified
  1401. // reference type could be formed, so the 'ill-formed' clause here appears
  1402. // to never happen.
  1403. if (TypeQuals && Result->isReferenceType()) {
  1404. diagnoseAndRemoveTypeQualifiers(
  1405. S, DS, TypeQuals, Result,
  1406. DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
  1407. diag::warn_typecheck_reference_qualifiers);
  1408. }
  1409. // C90 6.5.3 constraints: "The same type qualifier shall not appear more
  1410. // than once in the same specifier-list or qualifier-list, either directly
  1411. // or via one or more typedefs."
  1412. if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
  1413. && TypeQuals & Result.getCVRQualifiers()) {
  1414. if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
  1415. S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
  1416. << "const";
  1417. }
  1418. if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
  1419. S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
  1420. << "volatile";
  1421. }
  1422. // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
  1423. // produce a warning in this case.
  1424. }
  1425. QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
  1426. // If adding qualifiers fails, just use the unqualified type.
  1427. if (Qualified.isNull())
  1428. declarator.setInvalidType(true);
  1429. else
  1430. Result = Qualified;
  1431. }
  1432. assert(!Result.isNull() && "This function should not return a null type");
  1433. return Result;
  1434. }
  1435. static std::string getPrintableNameForEntity(DeclarationName Entity) {
  1436. if (Entity)
  1437. return Entity.getAsString();
  1438. return "type name";
  1439. }
  1440. QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
  1441. Qualifiers Qs, const DeclSpec *DS) {
  1442. if (T.isNull())
  1443. return QualType();
  1444. // Enforce C99 6.7.3p2: "Types other than pointer types derived from
  1445. // object or incomplete types shall not be restrict-qualified."
  1446. if (Qs.hasRestrict()) {
  1447. unsigned DiagID = 0;
  1448. QualType ProblemTy;
  1449. if (T->isAnyPointerType() || T->isReferenceType() ||
  1450. T->isMemberPointerType()) {
  1451. QualType EltTy;
  1452. if (T->isObjCObjectPointerType())
  1453. EltTy = T;
  1454. else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
  1455. EltTy = PTy->getPointeeType();
  1456. else
  1457. EltTy = T->getPointeeType();
  1458. // If we have a pointer or reference, the pointee must have an object
  1459. // incomplete type.
  1460. if (!EltTy->isIncompleteOrObjectType()) {
  1461. DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
  1462. ProblemTy = EltTy;
  1463. }
  1464. } else if (!T->isDependentType()) {
  1465. DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
  1466. ProblemTy = T;
  1467. }
  1468. if (DiagID) {
  1469. Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
  1470. Qs.removeRestrict();
  1471. }
  1472. }
  1473. return Context.getQualifiedType(T, Qs);
  1474. }
  1475. QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
  1476. unsigned CVRA, const DeclSpec *DS) {
  1477. if (T.isNull())
  1478. return QualType();
  1479. // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
  1480. unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
  1481. // C11 6.7.3/5:
  1482. // If the same qualifier appears more than once in the same
  1483. // specifier-qualifier-list, either directly or via one or more typedefs,
  1484. // the behavior is the same as if it appeared only once.
  1485. //
  1486. // It's not specified what happens when the _Atomic qualifier is applied to
  1487. // a type specified with the _Atomic specifier, but we assume that this
  1488. // should be treated as if the _Atomic qualifier appeared multiple times.
  1489. if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) {
  1490. // C11 6.7.3/5:
  1491. // If other qualifiers appear along with the _Atomic qualifier in a
  1492. // specifier-qualifier-list, the resulting type is the so-qualified
  1493. // atomic type.
  1494. //
  1495. // Don't need to worry about array types here, since _Atomic can't be
  1496. // applied to such types.
  1497. SplitQualType Split = T.getSplitUnqualifiedType();
  1498. T = BuildAtomicType(QualType(Split.Ty, 0),
  1499. DS ? DS->getAtomicSpecLoc() : Loc);
  1500. if (T.isNull())
  1501. return T;
  1502. Split.Quals.addCVRQualifiers(CVR);
  1503. return BuildQualifiedType(T, Loc, Split.Quals);
  1504. }
  1505. return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS);
  1506. }
  1507. /// \brief Build a paren type including \p T.
  1508. QualType Sema::BuildParenType(QualType T) {
  1509. return Context.getParenType(T);
  1510. }
  1511. /// Given that we're building a pointer or reference to the given
  1512. static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
  1513. SourceLocation loc,
  1514. bool isReference) {
  1515. // Bail out if retention is unrequired or already specified.
  1516. if (!type->isObjCLifetimeType() ||
  1517. type.getObjCLifetime() != Qualifiers::OCL_None)
  1518. return type;
  1519. Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
  1520. // If the object type is const-qualified, we can safely use
  1521. // __unsafe_unretained. This is safe (because there are no read
  1522. // barriers), and it'll be safe to coerce anything but __weak* to
  1523. // the resulting type.
  1524. if (type.isConstQualified()) {
  1525. implicitLifetime = Qualifiers::OCL_ExplicitNone;
  1526. // Otherwise, check whether the static type does not require
  1527. // retaining. This currently only triggers for Class (possibly
  1528. // protocol-qualifed, and arrays thereof).
  1529. } else if (type->isObjCARCImplicitlyUnretainedType()) {
  1530. implicitLifetime = Qualifiers::OCL_ExplicitNone;
  1531. // If we are in an unevaluated context, like sizeof, skip adding a
  1532. // qualification.
  1533. } else if (S.isUnevaluatedContext()) {
  1534. return type;
  1535. // If that failed, give an error and recover using __strong. __strong
  1536. // is the option most likely to prevent spurious second-order diagnostics,
  1537. // like when binding a reference to a field.
  1538. } else {
  1539. // These types can show up in private ivars in system headers, so
  1540. // we need this to not be an error in those cases. Instead we
  1541. // want to delay.
  1542. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
  1543. S.DelayedDiagnostics.add(
  1544. sema::DelayedDiagnostic::makeForbiddenType(loc,
  1545. diag::err_arc_indirect_no_ownership, type, isReference));
  1546. } else {
  1547. S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
  1548. }
  1549. implicitLifetime = Qualifiers::OCL_Strong;
  1550. }
  1551. assert(implicitLifetime && "didn't infer any lifetime!");
  1552. Qualifiers qs;
  1553. qs.addObjCLifetime(implicitLifetime);
  1554. return S.Context.getQualifiedType(type, qs);
  1555. }
  1556. static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
  1557. std::string Quals =
  1558. Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
  1559. switch (FnTy->getRefQualifier()) {
  1560. case RQ_None:
  1561. break;
  1562. case RQ_LValue:
  1563. if (!Quals.empty())
  1564. Quals += ' ';
  1565. Quals += '&';
  1566. break;
  1567. case RQ_RValue:
  1568. if (!Quals.empty())
  1569. Quals += ' ';
  1570. Quals += "&&";
  1571. break;
  1572. }
  1573. return Quals;
  1574. }
  1575. namespace {
  1576. /// Kinds of declarator that cannot contain a qualified function type.
  1577. ///
  1578. /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
  1579. /// a function type with a cv-qualifier or a ref-qualifier can only appear
  1580. /// at the topmost level of a type.
  1581. ///
  1582. /// Parens and member pointers are permitted. We don't diagnose array and
  1583. /// function declarators, because they don't allow function types at all.
  1584. ///
  1585. /// The values of this enum are used in diagnostics.
  1586. enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
  1587. }
  1588. /// Check whether the type T is a qualified function type, and if it is,
  1589. /// diagnose that it cannot be contained within the given kind of declarator.
  1590. static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
  1591. QualifiedFunctionKind QFK) {
  1592. // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
  1593. const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
  1594. if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
  1595. return false;
  1596. S.Diag(Loc, diag::err_compound_qualified_function_type)
  1597. << QFK << isa<FunctionType>(T.IgnoreParens()) << T
  1598. << getFunctionQualifiersAsString(FPT);
  1599. return true;
  1600. }
  1601. /// \brief Build a pointer type.
  1602. ///
  1603. /// \param T The type to which we'll be building a pointer.
  1604. ///
  1605. /// \param Loc The location of the entity whose type involves this
  1606. /// pointer type or, if there is no such entity, the location of the
  1607. /// type that will have pointer type.
  1608. ///
  1609. /// \param Entity The name of the entity that involves the pointer
  1610. /// type, if known.
  1611. ///
  1612. /// \returns A suitable pointer type, if there are no
  1613. /// errors. Otherwise, returns a NULL type.
  1614. QualType Sema::BuildPointerType(QualType T,
  1615. SourceLocation Loc, DeclarationName Entity) {
  1616. if (T->isReferenceType()) {
  1617. // C++ 8.3.2p4: There shall be no ... pointers to references ...
  1618. Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
  1619. << getPrintableNameForEntity(Entity) << T;
  1620. return QualType();
  1621. }
  1622. if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
  1623. return QualType();
  1624. assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
  1625. // In ARC, it is forbidden to build pointers to unqualified pointers.
  1626. if (getLangOpts().ObjCAutoRefCount)
  1627. T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
  1628. // Build the pointer type.
  1629. return Context.getPointerType(T);
  1630. }
  1631. /// \brief Build a reference type.
  1632. ///
  1633. /// \param T The type to which we'll be building a reference.
  1634. ///
  1635. /// \param Loc The location of the entity whose type involves this
  1636. /// reference type or, if there is no such entity, the location of the
  1637. /// type that will have reference type.
  1638. ///
  1639. /// \param Entity The name of the entity that involves the reference
  1640. /// type, if known.
  1641. ///
  1642. /// \returns A suitable reference type, if there are no
  1643. /// errors. Otherwise, returns a NULL type.
  1644. QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
  1645. SourceLocation Loc,
  1646. DeclarationName Entity) {
  1647. assert(Context.getCanonicalType(T) != Context.OverloadTy &&
  1648. "Unresolved overloaded function type");
  1649. // C++0x [dcl.ref]p6:
  1650. // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
  1651. // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
  1652. // type T, an attempt to create the type "lvalue reference to cv TR" creates
  1653. // the type "lvalue reference to T", while an attempt to create the type
  1654. // "rvalue reference to cv TR" creates the type TR.
  1655. bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
  1656. // C++ [dcl.ref]p4: There shall be no references to references.
  1657. //
  1658. // According to C++ DR 106, references to references are only
  1659. // diagnosed when they are written directly (e.g., "int & &"),
  1660. // but not when they happen via a typedef:
  1661. //
  1662. // typedef int& intref;
  1663. // typedef intref& intref2;
  1664. //
  1665. // Parser::ParseDeclaratorInternal diagnoses the case where
  1666. // references are written directly; here, we handle the
  1667. // collapsing of references-to-references as described in C++0x.
  1668. // DR 106 and 540 introduce reference-collapsing into C++98/03.
  1669. // C++ [dcl.ref]p1:
  1670. // A declarator that specifies the type "reference to cv void"
  1671. // is ill-formed.
  1672. if (T->isVoidType()) {
  1673. Diag(Loc, diag::err_reference_to_void);
  1674. return QualType();
  1675. }
  1676. if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
  1677. return QualType();
  1678. // In ARC, it is forbidden to build references to unqualified pointers.
  1679. if (getLangOpts().ObjCAutoRefCount)
  1680. T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
  1681. // Handle restrict on references.
  1682. if (LValueRef)
  1683. return Context.getLValueReferenceType(T, SpelledAsLValue);
  1684. return Context.getRValueReferenceType(T);
  1685. }
  1686. /// \brief Build a Pipe type.
  1687. ///
  1688. /// \param T The type to which we'll be building a Pipe.
  1689. ///
  1690. /// \param Loc We do not use it for now.
  1691. ///
  1692. /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
  1693. /// NULL type.
  1694. QualType Sema::BuildPipeType(QualType T, SourceLocation Loc) {
  1695. assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
  1696. // Build the pipe type.
  1697. return Context.getPipeType(T);
  1698. }
  1699. /// Check whether the specified array size makes the array type a VLA. If so,
  1700. /// return true, if not, return the size of the array in SizeVal.
  1701. static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
  1702. // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
  1703. // (like gnu99, but not c99) accept any evaluatable value as an extension.
  1704. class VLADiagnoser : public Sema::VerifyICEDiagnoser {
  1705. public:
  1706. VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
  1707. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  1708. }
  1709. void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
  1710. S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
  1711. }
  1712. } Diagnoser;
  1713. return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
  1714. S.LangOpts.GNUMode).isInvalid();
  1715. }
  1716. /// \brief Build an array type.
  1717. ///
  1718. /// \param T The type of each element in the array.
  1719. ///
  1720. /// \param ASM C99 array size modifier (e.g., '*', 'static').
  1721. ///
  1722. /// \param ArraySize Expression describing the size of the array.
  1723. ///
  1724. /// \param Brackets The range from the opening '[' to the closing ']'.
  1725. ///
  1726. /// \param Entity The name of the entity that involves the array
  1727. /// type, if known.
  1728. ///
  1729. /// \returns A suitable array type, if there are no errors. Otherwise,
  1730. /// returns a NULL type.
  1731. QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
  1732. Expr *ArraySize, unsigned Quals,
  1733. SourceRange Brackets, DeclarationName Entity) {
  1734. SourceLocation Loc = Brackets.getBegin();
  1735. if (getLangOpts().CPlusPlus) {
  1736. // C++ [dcl.array]p1:
  1737. // T is called the array element type; this type shall not be a reference
  1738. // type, the (possibly cv-qualified) type void, a function type or an
  1739. // abstract class type.
  1740. //
  1741. // C++ [dcl.array]p3:
  1742. // When several "array of" specifications are adjacent, [...] only the
  1743. // first of the constant expressions that specify the bounds of the arrays
  1744. // may be omitted.
  1745. //
  1746. // Note: function types are handled in the common path with C.
  1747. if (T->isReferenceType()) {
  1748. Diag(Loc, diag::err_illegal_decl_array_of_references)
  1749. << getPrintableNameForEntity(Entity) << T;
  1750. return QualType();
  1751. }
  1752. if (T->isVoidType() || T->isIncompleteArrayType()) {
  1753. Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
  1754. return QualType();
  1755. }
  1756. if (RequireNonAbstractType(Brackets.getBegin(), T,
  1757. diag::err_array_of_abstract_type))
  1758. return QualType();
  1759. // Mentioning a member pointer type for an array type causes us to lock in
  1760. // an inheritance model, even if it's inside an unused typedef.
  1761. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  1762. if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
  1763. if (!MPTy->getClass()->isDependentType())
  1764. (void)isCompleteType(Loc, T);
  1765. } else {
  1766. // C99 6.7.5.2p1: If the element type is an incomplete or function type,
  1767. // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
  1768. if (RequireCompleteType(Loc, T,
  1769. diag::err_illegal_decl_array_incomplete_type))
  1770. return QualType();
  1771. }
  1772. if (T->isFunctionType()) {
  1773. Diag(Loc, diag::err_illegal_decl_array_of_functions)
  1774. << getPrintableNameForEntity(Entity) << T;
  1775. return QualType();
  1776. }
  1777. if (const RecordType *EltTy = T->getAs<RecordType>()) {
  1778. // If the element type is a struct or union that contains a variadic
  1779. // array, accept it as a GNU extension: C99 6.7.2.1p2.
  1780. if (EltTy->getDecl()->hasFlexibleArrayMember())
  1781. Diag(Loc, diag::ext_flexible_array_in_array) << T;
  1782. } else if (T->isObjCObjectType()) {
  1783. Diag(Loc, diag::err_objc_array_of_interfaces) << T;
  1784. return QualType();
  1785. }
  1786. // Do placeholder conversions on the array size expression.
  1787. if (ArraySize && ArraySize->hasPlaceholderType()) {
  1788. ExprResult Result = CheckPlaceholderExpr(ArraySize);
  1789. if (Result.isInvalid()) return QualType();
  1790. ArraySize = Result.get();
  1791. }
  1792. // Do lvalue-to-rvalue conversions on the array size expression.
  1793. if (ArraySize && !ArraySize->isRValue()) {
  1794. ExprResult Result = DefaultLvalueConversion(ArraySize);
  1795. if (Result.isInvalid())
  1796. return QualType();
  1797. ArraySize = Result.get();
  1798. }
  1799. // C99 6.7.5.2p1: The size expression shall have integer type.
  1800. // C++11 allows contextual conversions to such types.
  1801. if (!getLangOpts().CPlusPlus11 &&
  1802. ArraySize && !ArraySize->isTypeDependent() &&
  1803. !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
  1804. Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
  1805. << ArraySize->getType() << ArraySize->getSourceRange();
  1806. return QualType();
  1807. }
  1808. llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
  1809. if (!ArraySize) {
  1810. if (ASM == ArrayType::Star)
  1811. T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
  1812. else
  1813. T = Context.getIncompleteArrayType(T, ASM, Quals);
  1814. } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
  1815. T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
  1816. } else if ((!T->isDependentType() && !T->isIncompleteType() &&
  1817. !T->isConstantSizeType()) ||
  1818. isArraySizeVLA(*this, ArraySize, ConstVal)) {
  1819. // Even in C++11, don't allow contextual conversions in the array bound
  1820. // of a VLA.
  1821. if (getLangOpts().CPlusPlus11 &&
  1822. !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
  1823. Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
  1824. << ArraySize->getType() << ArraySize->getSourceRange();
  1825. return QualType();
  1826. }
  1827. // C99: an array with an element type that has a non-constant-size is a VLA.
  1828. // C99: an array with a non-ICE size is a VLA. We accept any expression
  1829. // that we can fold to a non-zero positive value as an extension.
  1830. T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
  1831. } else {
  1832. // C99 6.7.5.2p1: If the expression is a constant expression, it shall
  1833. // have a value greater than zero.
  1834. if (ConstVal.isSigned() && ConstVal.isNegative()) {
  1835. if (Entity)
  1836. Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
  1837. << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
  1838. else
  1839. Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
  1840. << ArraySize->getSourceRange();
  1841. return QualType();
  1842. }
  1843. if (ConstVal == 0) {
  1844. // GCC accepts zero sized static arrays. We allow them when
  1845. // we're not in a SFINAE context.
  1846. Diag(ArraySize->getLocStart(),
  1847. isSFINAEContext()? diag::err_typecheck_zero_array_size
  1848. : diag::ext_typecheck_zero_array_size)
  1849. << ArraySize->getSourceRange();
  1850. if (ASM == ArrayType::Static) {
  1851. Diag(ArraySize->getLocStart(),
  1852. diag::warn_typecheck_zero_static_array_size)
  1853. << ArraySize->getSourceRange();
  1854. ASM = ArrayType::Normal;
  1855. }
  1856. } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
  1857. !T->isIncompleteType() && !T->isUndeducedType()) {
  1858. // Is the array too large?
  1859. unsigned ActiveSizeBits
  1860. = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
  1861. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  1862. Diag(ArraySize->getLocStart(), diag::err_array_too_large)
  1863. << ConstVal.toString(10)
  1864. << ArraySize->getSourceRange();
  1865. return QualType();
  1866. }
  1867. }
  1868. T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
  1869. }
  1870. // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
  1871. if (getLangOpts().OpenCL && T->isVariableArrayType()) {
  1872. Diag(Loc, diag::err_opencl_vla);
  1873. return QualType();
  1874. }
  1875. // If this is not C99, extwarn about VLA's and C99 array size modifiers.
  1876. if (!getLangOpts().C99) {
  1877. if (T->isVariableArrayType()) {
  1878. // Prohibit the use of non-POD types in VLAs.
  1879. QualType BaseT = Context.getBaseElementType(T);
  1880. if (!T->isDependentType() && isCompleteType(Loc, BaseT) &&
  1881. !BaseT.isPODType(Context) && !BaseT->isObjCLifetimeType()) {
  1882. Diag(Loc, diag::err_vla_non_pod) << BaseT;
  1883. return QualType();
  1884. }
  1885. // Prohibit the use of VLAs during template argument deduction.
  1886. else if (isSFINAEContext()) {
  1887. Diag(Loc, diag::err_vla_in_sfinae);
  1888. return QualType();
  1889. }
  1890. // Just extwarn about VLAs.
  1891. else
  1892. Diag(Loc, diag::ext_vla);
  1893. } else if (ASM != ArrayType::Normal || Quals != 0)
  1894. Diag(Loc,
  1895. getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
  1896. : diag::ext_c99_array_usage) << ASM;
  1897. }
  1898. if (T->isVariableArrayType()) {
  1899. // Warn about VLAs for -Wvla.
  1900. Diag(Loc, diag::warn_vla_used);
  1901. }
  1902. return T;
  1903. }
  1904. /// \brief Build an ext-vector type.
  1905. ///
  1906. /// Run the required checks for the extended vector type.
  1907. QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
  1908. SourceLocation AttrLoc) {
  1909. // unlike gcc's vector_size attribute, we do not allow vectors to be defined
  1910. // in conjunction with complex types (pointers, arrays, functions, etc.).
  1911. if (!T->isDependentType() &&
  1912. !T->isIntegerType() && !T->isRealFloatingType()) {
  1913. Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
  1914. return QualType();
  1915. }
  1916. if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
  1917. llvm::APSInt vecSize(32);
  1918. if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
  1919. Diag(AttrLoc, diag::err_attribute_argument_type)
  1920. << "ext_vector_type" << AANT_ArgumentIntegerConstant
  1921. << ArraySize->getSourceRange();
  1922. return QualType();
  1923. }
  1924. // unlike gcc's vector_size attribute, the size is specified as the
  1925. // number of elements, not the number of bytes.
  1926. unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
  1927. if (vectorSize == 0) {
  1928. Diag(AttrLoc, diag::err_attribute_zero_size)
  1929. << ArraySize->getSourceRange();
  1930. return QualType();
  1931. }
  1932. if (VectorType::isVectorSizeTooLarge(vectorSize)) {
  1933. Diag(AttrLoc, diag::err_attribute_size_too_large)
  1934. << ArraySize->getSourceRange();
  1935. return QualType();
  1936. }
  1937. return Context.getExtVectorType(T, vectorSize);
  1938. }
  1939. return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
  1940. }
  1941. bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
  1942. if (T->isArrayType() || T->isFunctionType()) {
  1943. Diag(Loc, diag::err_func_returning_array_function)
  1944. << T->isFunctionType() << T;
  1945. return true;
  1946. }
  1947. // Functions cannot return half FP.
  1948. if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
  1949. Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
  1950. FixItHint::CreateInsertion(Loc, "*");
  1951. return true;
  1952. }
  1953. // Methods cannot return interface types. All ObjC objects are
  1954. // passed by reference.
  1955. if (T->isObjCObjectType()) {
  1956. Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
  1957. return 0;
  1958. }
  1959. return false;
  1960. }
  1961. QualType Sema::BuildFunctionType(QualType T,
  1962. MutableArrayRef<QualType> ParamTypes,
  1963. SourceLocation Loc, DeclarationName Entity,
  1964. const FunctionProtoType::ExtProtoInfo &EPI) {
  1965. bool Invalid = false;
  1966. Invalid |= CheckFunctionReturnType(T, Loc);
  1967. for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
  1968. // FIXME: Loc is too inprecise here, should use proper locations for args.
  1969. QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
  1970. if (ParamType->isVoidType()) {
  1971. Diag(Loc, diag::err_param_with_void_type);
  1972. Invalid = true;
  1973. } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
  1974. // Disallow half FP arguments.
  1975. Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
  1976. FixItHint::CreateInsertion(Loc, "*");
  1977. Invalid = true;
  1978. }
  1979. ParamTypes[Idx] = ParamType;
  1980. }
  1981. if (Invalid)
  1982. return QualType();
  1983. return Context.getFunctionType(T, ParamTypes, EPI);
  1984. }
  1985. /// \brief Build a member pointer type \c T Class::*.
  1986. ///
  1987. /// \param T the type to which the member pointer refers.
  1988. /// \param Class the class type into which the member pointer points.
  1989. /// \param Loc the location where this type begins
  1990. /// \param Entity the name of the entity that will have this member pointer type
  1991. ///
  1992. /// \returns a member pointer type, if successful, or a NULL type if there was
  1993. /// an error.
  1994. QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
  1995. SourceLocation Loc,
  1996. DeclarationName Entity) {
  1997. // Verify that we're not building a pointer to pointer to function with
  1998. // exception specification.
  1999. if (CheckDistantExceptionSpec(T)) {
  2000. Diag(Loc, diag::err_distant_exception_spec);
  2001. return QualType();
  2002. }
  2003. // C++ 8.3.3p3: A pointer to member shall not point to ... a member
  2004. // with reference type, or "cv void."
  2005. if (T->isReferenceType()) {
  2006. Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
  2007. << getPrintableNameForEntity(Entity) << T;
  2008. return QualType();
  2009. }
  2010. if (T->isVoidType()) {
  2011. Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
  2012. << getPrintableNameForEntity(Entity);
  2013. return QualType();
  2014. }
  2015. if (!Class->isDependentType() && !Class->isRecordType()) {
  2016. Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
  2017. return QualType();
  2018. }
  2019. // Adjust the default free function calling convention to the default method
  2020. // calling convention.
  2021. bool IsCtorOrDtor =
  2022. (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
  2023. (Entity.getNameKind() == DeclarationName::CXXDestructorName);
  2024. if (T->isFunctionType())
  2025. adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
  2026. return Context.getMemberPointerType(T, Class.getTypePtr());
  2027. }
  2028. /// \brief Build a block pointer type.
  2029. ///
  2030. /// \param T The type to which we'll be building a block pointer.
  2031. ///
  2032. /// \param Loc The source location, used for diagnostics.
  2033. ///
  2034. /// \param Entity The name of the entity that involves the block pointer
  2035. /// type, if known.
  2036. ///
  2037. /// \returns A suitable block pointer type, if there are no
  2038. /// errors. Otherwise, returns a NULL type.
  2039. QualType Sema::BuildBlockPointerType(QualType T,
  2040. SourceLocation Loc,
  2041. DeclarationName Entity) {
  2042. if (!T->isFunctionType()) {
  2043. Diag(Loc, diag::err_nonfunction_block_type);
  2044. return QualType();
  2045. }
  2046. if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
  2047. return QualType();
  2048. return Context.getBlockPointerType(T);
  2049. }
  2050. QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
  2051. QualType QT = Ty.get();
  2052. if (QT.isNull()) {
  2053. if (TInfo) *TInfo = nullptr;
  2054. return QualType();
  2055. }
  2056. TypeSourceInfo *DI = nullptr;
  2057. if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
  2058. QT = LIT->getType();
  2059. DI = LIT->getTypeSourceInfo();
  2060. }
  2061. if (TInfo) *TInfo = DI;
  2062. return QT;
  2063. }
  2064. static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
  2065. Qualifiers::ObjCLifetime ownership,
  2066. unsigned chunkIndex);
  2067. /// Given that this is the declaration of a parameter under ARC,
  2068. /// attempt to infer attributes and such for pointer-to-whatever
  2069. /// types.
  2070. static void inferARCWriteback(TypeProcessingState &state,
  2071. QualType &declSpecType) {
  2072. Sema &S = state.getSema();
  2073. Declarator &declarator = state.getDeclarator();
  2074. // TODO: should we care about decl qualifiers?
  2075. // Check whether the declarator has the expected form. We walk
  2076. // from the inside out in order to make the block logic work.
  2077. unsigned outermostPointerIndex = 0;
  2078. bool isBlockPointer = false;
  2079. unsigned numPointers = 0;
  2080. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  2081. unsigned chunkIndex = i;
  2082. DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
  2083. switch (chunk.Kind) {
  2084. case DeclaratorChunk::Paren:
  2085. // Ignore parens.
  2086. break;
  2087. case DeclaratorChunk::Reference:
  2088. case DeclaratorChunk::Pointer:
  2089. // Count the number of pointers. Treat references
  2090. // interchangeably as pointers; if they're mis-ordered, normal
  2091. // type building will discover that.
  2092. outermostPointerIndex = chunkIndex;
  2093. numPointers++;
  2094. break;
  2095. case DeclaratorChunk::BlockPointer:
  2096. // If we have a pointer to block pointer, that's an acceptable
  2097. // indirect reference; anything else is not an application of
  2098. // the rules.
  2099. if (numPointers != 1) return;
  2100. numPointers++;
  2101. outermostPointerIndex = chunkIndex;
  2102. isBlockPointer = true;
  2103. // We don't care about pointer structure in return values here.
  2104. goto done;
  2105. case DeclaratorChunk::Array: // suppress if written (id[])?
  2106. case DeclaratorChunk::Function:
  2107. case DeclaratorChunk::MemberPointer:
  2108. case DeclaratorChunk::Pipe:
  2109. return;
  2110. }
  2111. }
  2112. done:
  2113. // If we have *one* pointer, then we want to throw the qualifier on
  2114. // the declaration-specifiers, which means that it needs to be a
  2115. // retainable object type.
  2116. if (numPointers == 1) {
  2117. // If it's not a retainable object type, the rule doesn't apply.
  2118. if (!declSpecType->isObjCRetainableType()) return;
  2119. // If it already has lifetime, don't do anything.
  2120. if (declSpecType.getObjCLifetime()) return;
  2121. // Otherwise, modify the type in-place.
  2122. Qualifiers qs;
  2123. if (declSpecType->isObjCARCImplicitlyUnretainedType())
  2124. qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
  2125. else
  2126. qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
  2127. declSpecType = S.Context.getQualifiedType(declSpecType, qs);
  2128. // If we have *two* pointers, then we want to throw the qualifier on
  2129. // the outermost pointer.
  2130. } else if (numPointers == 2) {
  2131. // If we don't have a block pointer, we need to check whether the
  2132. // declaration-specifiers gave us something that will turn into a
  2133. // retainable object pointer after we slap the first pointer on it.
  2134. if (!isBlockPointer && !declSpecType->isObjCObjectType())
  2135. return;
  2136. // Look for an explicit lifetime attribute there.
  2137. DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
  2138. if (chunk.Kind != DeclaratorChunk::Pointer &&
  2139. chunk.Kind != DeclaratorChunk::BlockPointer)
  2140. return;
  2141. for (const AttributeList *attr = chunk.getAttrs(); attr;
  2142. attr = attr->getNext())
  2143. if (attr->getKind() == AttributeList::AT_ObjCOwnership)
  2144. return;
  2145. transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
  2146. outermostPointerIndex);
  2147. // Any other number of pointers/references does not trigger the rule.
  2148. } else return;
  2149. // TODO: mark whether we did this inference?
  2150. }
  2151. void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
  2152. SourceLocation FallbackLoc,
  2153. SourceLocation ConstQualLoc,
  2154. SourceLocation VolatileQualLoc,
  2155. SourceLocation RestrictQualLoc,
  2156. SourceLocation AtomicQualLoc) {
  2157. if (!Quals)
  2158. return;
  2159. struct Qual {
  2160. const char *Name;
  2161. unsigned Mask;
  2162. SourceLocation Loc;
  2163. } const QualKinds[4] = {
  2164. { "const", DeclSpec::TQ_const, ConstQualLoc },
  2165. { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
  2166. { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
  2167. { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
  2168. };
  2169. SmallString<32> QualStr;
  2170. unsigned NumQuals = 0;
  2171. SourceLocation Loc;
  2172. FixItHint FixIts[4];
  2173. // Build a string naming the redundant qualifiers.
  2174. for (unsigned I = 0; I != 4; ++I) {
  2175. if (Quals & QualKinds[I].Mask) {
  2176. if (!QualStr.empty()) QualStr += ' ';
  2177. QualStr += QualKinds[I].Name;
  2178. // If we have a location for the qualifier, offer a fixit.
  2179. SourceLocation QualLoc = QualKinds[I].Loc;
  2180. if (QualLoc.isValid()) {
  2181. FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
  2182. if (Loc.isInvalid() ||
  2183. getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
  2184. Loc = QualLoc;
  2185. }
  2186. ++NumQuals;
  2187. }
  2188. }
  2189. Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
  2190. << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
  2191. }
  2192. // Diagnose pointless type qualifiers on the return type of a function.
  2193. static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
  2194. Declarator &D,
  2195. unsigned FunctionChunkIndex) {
  2196. if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
  2197. // FIXME: TypeSourceInfo doesn't preserve location information for
  2198. // qualifiers.
  2199. S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
  2200. RetTy.getLocalCVRQualifiers(),
  2201. D.getIdentifierLoc());
  2202. return;
  2203. }
  2204. for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
  2205. End = D.getNumTypeObjects();
  2206. OuterChunkIndex != End; ++OuterChunkIndex) {
  2207. DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
  2208. switch (OuterChunk.Kind) {
  2209. case DeclaratorChunk::Paren:
  2210. continue;
  2211. case DeclaratorChunk::Pointer: {
  2212. DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
  2213. S.diagnoseIgnoredQualifiers(
  2214. diag::warn_qual_return_type,
  2215. PTI.TypeQuals,
  2216. SourceLocation(),
  2217. SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
  2218. SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
  2219. SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
  2220. SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc));
  2221. return;
  2222. }
  2223. case DeclaratorChunk::Function:
  2224. case DeclaratorChunk::BlockPointer:
  2225. case DeclaratorChunk::Reference:
  2226. case DeclaratorChunk::Array:
  2227. case DeclaratorChunk::MemberPointer:
  2228. case DeclaratorChunk::Pipe:
  2229. // FIXME: We can't currently provide an accurate source location and a
  2230. // fix-it hint for these.
  2231. unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
  2232. S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
  2233. RetTy.getCVRQualifiers() | AtomicQual,
  2234. D.getIdentifierLoc());
  2235. return;
  2236. }
  2237. llvm_unreachable("unknown declarator chunk kind");
  2238. }
  2239. // If the qualifiers come from a conversion function type, don't diagnose
  2240. // them -- they're not necessarily redundant, since such a conversion
  2241. // operator can be explicitly called as "x.operator const int()".
  2242. if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
  2243. return;
  2244. // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
  2245. // which are present there.
  2246. S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
  2247. D.getDeclSpec().getTypeQualifiers(),
  2248. D.getIdentifierLoc(),
  2249. D.getDeclSpec().getConstSpecLoc(),
  2250. D.getDeclSpec().getVolatileSpecLoc(),
  2251. D.getDeclSpec().getRestrictSpecLoc(),
  2252. D.getDeclSpec().getAtomicSpecLoc());
  2253. }
  2254. static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
  2255. TypeSourceInfo *&ReturnTypeInfo) {
  2256. Sema &SemaRef = state.getSema();
  2257. Declarator &D = state.getDeclarator();
  2258. QualType T;
  2259. ReturnTypeInfo = nullptr;
  2260. // The TagDecl owned by the DeclSpec.
  2261. TagDecl *OwnedTagDecl = nullptr;
  2262. switch (D.getName().getKind()) {
  2263. case UnqualifiedId::IK_ImplicitSelfParam:
  2264. case UnqualifiedId::IK_OperatorFunctionId:
  2265. case UnqualifiedId::IK_Identifier:
  2266. case UnqualifiedId::IK_LiteralOperatorId:
  2267. case UnqualifiedId::IK_TemplateId:
  2268. T = ConvertDeclSpecToType(state);
  2269. if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
  2270. OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  2271. // Owned declaration is embedded in declarator.
  2272. OwnedTagDecl->setEmbeddedInDeclarator(true);
  2273. }
  2274. break;
  2275. case UnqualifiedId::IK_ConstructorName:
  2276. case UnqualifiedId::IK_ConstructorTemplateId:
  2277. case UnqualifiedId::IK_DestructorName:
  2278. // Constructors and destructors don't have return types. Use
  2279. // "void" instead.
  2280. T = SemaRef.Context.VoidTy;
  2281. processTypeAttrs(state, T, TAL_DeclSpec,
  2282. D.getDeclSpec().getAttributes().getList());
  2283. break;
  2284. case UnqualifiedId::IK_ConversionFunctionId:
  2285. // The result type of a conversion function is the type that it
  2286. // converts to.
  2287. T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
  2288. &ReturnTypeInfo);
  2289. break;
  2290. }
  2291. if (D.getAttributes())
  2292. distributeTypeAttrsFromDeclarator(state, T);
  2293. // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
  2294. if (D.getDeclSpec().containsPlaceholderType()) {
  2295. int Error = -1;
  2296. switch (D.getContext()) {
  2297. case Declarator::LambdaExprContext:
  2298. llvm_unreachable("Can't specify a type specifier in lambda grammar");
  2299. case Declarator::ObjCParameterContext:
  2300. case Declarator::ObjCResultContext:
  2301. case Declarator::PrototypeContext:
  2302. Error = 0;
  2303. break;
  2304. case Declarator::LambdaExprParameterContext:
  2305. // In C++14, generic lambdas allow 'auto' in their parameters.
  2306. if (!(SemaRef.getLangOpts().CPlusPlus14
  2307. && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
  2308. Error = 16;
  2309. break;
  2310. case Declarator::MemberContext: {
  2311. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
  2312. D.isFunctionDeclarator())
  2313. break;
  2314. bool Cxx = SemaRef.getLangOpts().CPlusPlus;
  2315. switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
  2316. case TTK_Enum: llvm_unreachable("unhandled tag kind");
  2317. case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
  2318. case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
  2319. case TTK_Class: Error = 5; /* Class member */ break;
  2320. case TTK_Interface: Error = 6; /* Interface member */ break;
  2321. }
  2322. break;
  2323. }
  2324. case Declarator::CXXCatchContext:
  2325. case Declarator::ObjCCatchContext:
  2326. Error = 7; // Exception declaration
  2327. break;
  2328. case Declarator::TemplateParamContext:
  2329. Error = 8; // Template parameter
  2330. break;
  2331. case Declarator::BlockLiteralContext:
  2332. Error = 9; // Block literal
  2333. break;
  2334. case Declarator::TemplateTypeArgContext:
  2335. Error = 10; // Template type argument
  2336. break;
  2337. case Declarator::AliasDeclContext:
  2338. case Declarator::AliasTemplateContext:
  2339. Error = 12; // Type alias
  2340. break;
  2341. case Declarator::TrailingReturnContext:
  2342. if (!SemaRef.getLangOpts().CPlusPlus14 ||
  2343. D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
  2344. Error = 13; // Function return type
  2345. break;
  2346. case Declarator::ConversionIdContext:
  2347. if (!SemaRef.getLangOpts().CPlusPlus14 ||
  2348. D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
  2349. Error = 14; // conversion-type-id
  2350. break;
  2351. case Declarator::TypeNameContext:
  2352. Error = 15; // Generic
  2353. break;
  2354. case Declarator::FileContext:
  2355. case Declarator::BlockContext:
  2356. case Declarator::ForContext:
  2357. case Declarator::ConditionContext:
  2358. break;
  2359. case Declarator::CXXNewContext:
  2360. if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
  2361. Error = 17; // 'new' type
  2362. break;
  2363. case Declarator::KNRTypeListContext:
  2364. Error = 18; // K&R function parameter
  2365. break;
  2366. }
  2367. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  2368. Error = 11;
  2369. // In Objective-C it is an error to use 'auto' on a function declarator
  2370. // (and everywhere for '__auto_type').
  2371. if (D.isFunctionDeclarator() &&
  2372. (!SemaRef.getLangOpts().CPlusPlus11 ||
  2373. D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type))
  2374. Error = 13;
  2375. bool HaveTrailing = false;
  2376. // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
  2377. // contains a trailing return type. That is only legal at the outermost
  2378. // level. Check all declarator chunks (outermost first) anyway, to give
  2379. // better diagnostics.
  2380. // We don't support '__auto_type' with trailing return types.
  2381. if (SemaRef.getLangOpts().CPlusPlus11 &&
  2382. D.getDeclSpec().getTypeSpecType() != DeclSpec::TST_auto_type) {
  2383. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  2384. unsigned chunkIndex = e - i - 1;
  2385. state.setCurrentChunkIndex(chunkIndex);
  2386. DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
  2387. if (DeclType.Kind == DeclaratorChunk::Function) {
  2388. const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
  2389. if (FTI.hasTrailingReturnType()) {
  2390. HaveTrailing = true;
  2391. Error = -1;
  2392. break;
  2393. }
  2394. }
  2395. }
  2396. }
  2397. SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
  2398. if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
  2399. AutoRange = D.getName().getSourceRange();
  2400. if (Error != -1) {
  2401. unsigned Keyword;
  2402. switch (D.getDeclSpec().getTypeSpecType()) {
  2403. case DeclSpec::TST_auto: Keyword = 0; break;
  2404. case DeclSpec::TST_decltype_auto: Keyword = 1; break;
  2405. case DeclSpec::TST_auto_type: Keyword = 2; break;
  2406. default: llvm_unreachable("unknown auto TypeSpecType");
  2407. }
  2408. SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
  2409. << Keyword << Error << AutoRange;
  2410. T = SemaRef.Context.IntTy;
  2411. D.setInvalidType(true);
  2412. } else if (!HaveTrailing) {
  2413. // If there was a trailing return type, we already got
  2414. // warn_cxx98_compat_trailing_return_type in the parser.
  2415. SemaRef.Diag(AutoRange.getBegin(),
  2416. diag::warn_cxx98_compat_auto_type_specifier)
  2417. << AutoRange;
  2418. }
  2419. }
  2420. if (SemaRef.getLangOpts().CPlusPlus &&
  2421. OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
  2422. // Check the contexts where C++ forbids the declaration of a new class
  2423. // or enumeration in a type-specifier-seq.
  2424. unsigned DiagID = 0;
  2425. switch (D.getContext()) {
  2426. case Declarator::TrailingReturnContext:
  2427. // Class and enumeration definitions are syntactically not allowed in
  2428. // trailing return types.
  2429. llvm_unreachable("parser should not have allowed this");
  2430. break;
  2431. case Declarator::FileContext:
  2432. case Declarator::MemberContext:
  2433. case Declarator::BlockContext:
  2434. case Declarator::ForContext:
  2435. case Declarator::BlockLiteralContext:
  2436. case Declarator::LambdaExprContext:
  2437. // C++11 [dcl.type]p3:
  2438. // A type-specifier-seq shall not define a class or enumeration unless
  2439. // it appears in the type-id of an alias-declaration (7.1.3) that is not
  2440. // the declaration of a template-declaration.
  2441. case Declarator::AliasDeclContext:
  2442. break;
  2443. case Declarator::AliasTemplateContext:
  2444. DiagID = diag::err_type_defined_in_alias_template;
  2445. break;
  2446. case Declarator::TypeNameContext:
  2447. case Declarator::ConversionIdContext:
  2448. case Declarator::TemplateParamContext:
  2449. case Declarator::CXXNewContext:
  2450. case Declarator::CXXCatchContext:
  2451. case Declarator::ObjCCatchContext:
  2452. case Declarator::TemplateTypeArgContext:
  2453. DiagID = diag::err_type_defined_in_type_specifier;
  2454. break;
  2455. case Declarator::PrototypeContext:
  2456. case Declarator::LambdaExprParameterContext:
  2457. case Declarator::ObjCParameterContext:
  2458. case Declarator::ObjCResultContext:
  2459. case Declarator::KNRTypeListContext:
  2460. // C++ [dcl.fct]p6:
  2461. // Types shall not be defined in return or parameter types.
  2462. DiagID = diag::err_type_defined_in_param_type;
  2463. break;
  2464. case Declarator::ConditionContext:
  2465. // C++ 6.4p2:
  2466. // The type-specifier-seq shall not contain typedef and shall not declare
  2467. // a new class or enumeration.
  2468. DiagID = diag::err_type_defined_in_condition;
  2469. break;
  2470. }
  2471. if (DiagID != 0) {
  2472. SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
  2473. << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
  2474. D.setInvalidType(true);
  2475. }
  2476. }
  2477. assert(!T.isNull() && "This function should not return a null type");
  2478. return T;
  2479. }
  2480. /// Produce an appropriate diagnostic for an ambiguity between a function
  2481. /// declarator and a C++ direct-initializer.
  2482. static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
  2483. DeclaratorChunk &DeclType, QualType RT) {
  2484. const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
  2485. assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
  2486. // If the return type is void there is no ambiguity.
  2487. if (RT->isVoidType())
  2488. return;
  2489. // An initializer for a non-class type can have at most one argument.
  2490. if (!RT->isRecordType() && FTI.NumParams > 1)
  2491. return;
  2492. // An initializer for a reference must have exactly one argument.
  2493. if (RT->isReferenceType() && FTI.NumParams != 1)
  2494. return;
  2495. // Only warn if this declarator is declaring a function at block scope, and
  2496. // doesn't have a storage class (such as 'extern') specified.
  2497. if (!D.isFunctionDeclarator() ||
  2498. D.getFunctionDefinitionKind() != FDK_Declaration ||
  2499. !S.CurContext->isFunctionOrMethod() ||
  2500. D.getDeclSpec().getStorageClassSpec()
  2501. != DeclSpec::SCS_unspecified)
  2502. return;
  2503. // Inside a condition, a direct initializer is not permitted. We allow one to
  2504. // be parsed in order to give better diagnostics in condition parsing.
  2505. if (D.getContext() == Declarator::ConditionContext)
  2506. return;
  2507. SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
  2508. S.Diag(DeclType.Loc,
  2509. FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
  2510. : diag::warn_empty_parens_are_function_decl)
  2511. << ParenRange;
  2512. // If the declaration looks like:
  2513. // T var1,
  2514. // f();
  2515. // and name lookup finds a function named 'f', then the ',' was
  2516. // probably intended to be a ';'.
  2517. if (!D.isFirstDeclarator() && D.getIdentifier()) {
  2518. FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
  2519. FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
  2520. if (Comma.getFileID() != Name.getFileID() ||
  2521. Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
  2522. LookupResult Result(S, D.getIdentifier(), SourceLocation(),
  2523. Sema::LookupOrdinaryName);
  2524. if (S.LookupName(Result, S.getCurScope()))
  2525. S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
  2526. << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
  2527. << D.getIdentifier();
  2528. }
  2529. }
  2530. if (FTI.NumParams > 0) {
  2531. // For a declaration with parameters, eg. "T var(T());", suggest adding
  2532. // parens around the first parameter to turn the declaration into a
  2533. // variable declaration.
  2534. SourceRange Range = FTI.Params[0].Param->getSourceRange();
  2535. SourceLocation B = Range.getBegin();
  2536. SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
  2537. // FIXME: Maybe we should suggest adding braces instead of parens
  2538. // in C++11 for classes that don't have an initializer_list constructor.
  2539. S.Diag(B, diag::note_additional_parens_for_variable_declaration)
  2540. << FixItHint::CreateInsertion(B, "(")
  2541. << FixItHint::CreateInsertion(E, ")");
  2542. } else {
  2543. // For a declaration without parameters, eg. "T var();", suggest replacing
  2544. // the parens with an initializer to turn the declaration into a variable
  2545. // declaration.
  2546. const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
  2547. // Empty parens mean value-initialization, and no parens mean
  2548. // default initialization. These are equivalent if the default
  2549. // constructor is user-provided or if zero-initialization is a
  2550. // no-op.
  2551. if (RD && RD->hasDefinition() &&
  2552. (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
  2553. S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
  2554. << FixItHint::CreateRemoval(ParenRange);
  2555. else {
  2556. std::string Init =
  2557. S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
  2558. if (Init.empty() && S.LangOpts.CPlusPlus11)
  2559. Init = "{}";
  2560. if (!Init.empty())
  2561. S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
  2562. << FixItHint::CreateReplacement(ParenRange, Init);
  2563. }
  2564. }
  2565. }
  2566. /// Helper for figuring out the default CC for a function declarator type. If
  2567. /// this is the outermost chunk, then we can determine the CC from the
  2568. /// declarator context. If not, then this could be either a member function
  2569. /// type or normal function type.
  2570. static CallingConv
  2571. getCCForDeclaratorChunk(Sema &S, Declarator &D,
  2572. const DeclaratorChunk::FunctionTypeInfo &FTI,
  2573. unsigned ChunkIndex) {
  2574. assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
  2575. bool IsCXXInstanceMethod = false;
  2576. if (S.getLangOpts().CPlusPlus) {
  2577. // Look inwards through parentheses to see if this chunk will form a
  2578. // member pointer type or if we're the declarator. Any type attributes
  2579. // between here and there will override the CC we choose here.
  2580. unsigned I = ChunkIndex;
  2581. bool FoundNonParen = false;
  2582. while (I && !FoundNonParen) {
  2583. --I;
  2584. if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
  2585. FoundNonParen = true;
  2586. }
  2587. if (FoundNonParen) {
  2588. // If we're not the declarator, we're a regular function type unless we're
  2589. // in a member pointer.
  2590. IsCXXInstanceMethod =
  2591. D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
  2592. } else if (D.getContext() == Declarator::LambdaExprContext) {
  2593. // This can only be a call operator for a lambda, which is an instance
  2594. // method.
  2595. IsCXXInstanceMethod = true;
  2596. } else {
  2597. // We're the innermost decl chunk, so must be a function declarator.
  2598. assert(D.isFunctionDeclarator());
  2599. // If we're inside a record, we're declaring a method, but it could be
  2600. // explicitly or implicitly static.
  2601. IsCXXInstanceMethod =
  2602. D.isFirstDeclarationOfMember() &&
  2603. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  2604. !D.isStaticMember();
  2605. }
  2606. }
  2607. CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
  2608. IsCXXInstanceMethod);
  2609. // Attribute AT_OpenCLKernel affects the calling convention only on
  2610. // the SPIR target, hence it cannot be treated as a calling
  2611. // convention attribute. This is the simplest place to infer
  2612. // "spir_kernel" for OpenCL kernels on SPIR.
  2613. if (CC == CC_SpirFunction) {
  2614. for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
  2615. Attr; Attr = Attr->getNext()) {
  2616. if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
  2617. CC = CC_SpirKernel;
  2618. break;
  2619. }
  2620. }
  2621. }
  2622. return CC;
  2623. }
  2624. namespace {
  2625. /// A simple notion of pointer kinds, which matches up with the various
  2626. /// pointer declarators.
  2627. enum class SimplePointerKind {
  2628. Pointer,
  2629. BlockPointer,
  2630. MemberPointer,
  2631. };
  2632. }
  2633. IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
  2634. switch (nullability) {
  2635. case NullabilityKind::NonNull:
  2636. if (!Ident__Nonnull)
  2637. Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
  2638. return Ident__Nonnull;
  2639. case NullabilityKind::Nullable:
  2640. if (!Ident__Nullable)
  2641. Ident__Nullable = PP.getIdentifierInfo("_Nullable");
  2642. return Ident__Nullable;
  2643. case NullabilityKind::Unspecified:
  2644. if (!Ident__Null_unspecified)
  2645. Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
  2646. return Ident__Null_unspecified;
  2647. }
  2648. llvm_unreachable("Unknown nullability kind.");
  2649. }
  2650. /// Retrieve the identifier "NSError".
  2651. IdentifierInfo *Sema::getNSErrorIdent() {
  2652. if (!Ident_NSError)
  2653. Ident_NSError = PP.getIdentifierInfo("NSError");
  2654. return Ident_NSError;
  2655. }
  2656. /// Check whether there is a nullability attribute of any kind in the given
  2657. /// attribute list.
  2658. static bool hasNullabilityAttr(const AttributeList *attrs) {
  2659. for (const AttributeList *attr = attrs; attr;
  2660. attr = attr->getNext()) {
  2661. if (attr->getKind() == AttributeList::AT_TypeNonNull ||
  2662. attr->getKind() == AttributeList::AT_TypeNullable ||
  2663. attr->getKind() == AttributeList::AT_TypeNullUnspecified)
  2664. return true;
  2665. }
  2666. return false;
  2667. }
  2668. namespace {
  2669. /// Describes the kind of a pointer a declarator describes.
  2670. enum class PointerDeclaratorKind {
  2671. // Not a pointer.
  2672. NonPointer,
  2673. // Single-level pointer.
  2674. SingleLevelPointer,
  2675. // Multi-level pointer (of any pointer kind).
  2676. MultiLevelPointer,
  2677. // CFFooRef*
  2678. MaybePointerToCFRef,
  2679. // CFErrorRef*
  2680. CFErrorRefPointer,
  2681. // NSError**
  2682. NSErrorPointerPointer,
  2683. };
  2684. }
  2685. /// Classify the given declarator, whose type-specified is \c type, based on
  2686. /// what kind of pointer it refers to.
  2687. ///
  2688. /// This is used to determine the default nullability.
  2689. static PointerDeclaratorKind classifyPointerDeclarator(Sema &S,
  2690. QualType type,
  2691. Declarator &declarator) {
  2692. unsigned numNormalPointers = 0;
  2693. // For any dependent type, we consider it a non-pointer.
  2694. if (type->isDependentType())
  2695. return PointerDeclaratorKind::NonPointer;
  2696. // Look through the declarator chunks to identify pointers.
  2697. for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
  2698. DeclaratorChunk &chunk = declarator.getTypeObject(i);
  2699. switch (chunk.Kind) {
  2700. case DeclaratorChunk::Array:
  2701. case DeclaratorChunk::Function:
  2702. case DeclaratorChunk::Pipe:
  2703. break;
  2704. case DeclaratorChunk::BlockPointer:
  2705. case DeclaratorChunk::MemberPointer:
  2706. return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
  2707. : PointerDeclaratorKind::SingleLevelPointer;
  2708. case DeclaratorChunk::Paren:
  2709. case DeclaratorChunk::Reference:
  2710. continue;
  2711. case DeclaratorChunk::Pointer:
  2712. ++numNormalPointers;
  2713. if (numNormalPointers > 2)
  2714. return PointerDeclaratorKind::MultiLevelPointer;
  2715. continue;
  2716. }
  2717. }
  2718. // Then, dig into the type specifier itself.
  2719. unsigned numTypeSpecifierPointers = 0;
  2720. do {
  2721. // Decompose normal pointers.
  2722. if (auto ptrType = type->getAs<PointerType>()) {
  2723. ++numNormalPointers;
  2724. if (numNormalPointers > 2)
  2725. return PointerDeclaratorKind::MultiLevelPointer;
  2726. type = ptrType->getPointeeType();
  2727. ++numTypeSpecifierPointers;
  2728. continue;
  2729. }
  2730. // Decompose block pointers.
  2731. if (type->getAs<BlockPointerType>()) {
  2732. return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
  2733. : PointerDeclaratorKind::SingleLevelPointer;
  2734. }
  2735. // Decompose member pointers.
  2736. if (type->getAs<MemberPointerType>()) {
  2737. return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
  2738. : PointerDeclaratorKind::SingleLevelPointer;
  2739. }
  2740. // Look at Objective-C object pointers.
  2741. if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
  2742. ++numNormalPointers;
  2743. ++numTypeSpecifierPointers;
  2744. // If this is NSError**, report that.
  2745. if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
  2746. if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
  2747. numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
  2748. return PointerDeclaratorKind::NSErrorPointerPointer;
  2749. }
  2750. }
  2751. break;
  2752. }
  2753. // Look at Objective-C class types.
  2754. if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
  2755. if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
  2756. if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
  2757. return PointerDeclaratorKind::NSErrorPointerPointer;;
  2758. }
  2759. break;
  2760. }
  2761. // If at this point we haven't seen a pointer, we won't see one.
  2762. if (numNormalPointers == 0)
  2763. return PointerDeclaratorKind::NonPointer;
  2764. if (auto recordType = type->getAs<RecordType>()) {
  2765. RecordDecl *recordDecl = recordType->getDecl();
  2766. bool isCFError = false;
  2767. if (S.CFError) {
  2768. // If we already know about CFError, test it directly.
  2769. isCFError = (S.CFError == recordDecl);
  2770. } else {
  2771. // Check whether this is CFError, which we identify based on its bridge
  2772. // to NSError.
  2773. if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
  2774. if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) {
  2775. if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) {
  2776. S.CFError = recordDecl;
  2777. isCFError = true;
  2778. }
  2779. }
  2780. }
  2781. }
  2782. // If this is CFErrorRef*, report it as such.
  2783. if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
  2784. return PointerDeclaratorKind::CFErrorRefPointer;
  2785. }
  2786. break;
  2787. }
  2788. break;
  2789. } while (true);
  2790. switch (numNormalPointers) {
  2791. case 0:
  2792. return PointerDeclaratorKind::NonPointer;
  2793. case 1:
  2794. return PointerDeclaratorKind::SingleLevelPointer;
  2795. case 2:
  2796. return PointerDeclaratorKind::MaybePointerToCFRef;
  2797. default:
  2798. return PointerDeclaratorKind::MultiLevelPointer;
  2799. }
  2800. }
  2801. static FileID getNullabilityCompletenessCheckFileID(Sema &S,
  2802. SourceLocation loc) {
  2803. // If we're anywhere in a function, method, or closure context, don't perform
  2804. // completeness checks.
  2805. for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
  2806. if (ctx->isFunctionOrMethod())
  2807. return FileID();
  2808. if (ctx->isFileContext())
  2809. break;
  2810. }
  2811. // We only care about the expansion location.
  2812. loc = S.SourceMgr.getExpansionLoc(loc);
  2813. FileID file = S.SourceMgr.getFileID(loc);
  2814. if (file.isInvalid())
  2815. return FileID();
  2816. // Retrieve file information.
  2817. bool invalid = false;
  2818. const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
  2819. if (invalid || !sloc.isFile())
  2820. return FileID();
  2821. // We don't want to perform completeness checks on the main file or in
  2822. // system headers.
  2823. const SrcMgr::FileInfo &fileInfo = sloc.getFile();
  2824. if (fileInfo.getIncludeLoc().isInvalid())
  2825. return FileID();
  2826. if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
  2827. S.Diags.getSuppressSystemWarnings()) {
  2828. return FileID();
  2829. }
  2830. return file;
  2831. }
  2832. /// Check for consistent use of nullability.
  2833. static void checkNullabilityConsistency(TypeProcessingState &state,
  2834. SimplePointerKind pointerKind,
  2835. SourceLocation pointerLoc) {
  2836. Sema &S = state.getSema();
  2837. // Determine which file we're performing consistency checking for.
  2838. FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
  2839. if (file.isInvalid())
  2840. return;
  2841. // If we haven't seen any type nullability in this file, we won't warn now
  2842. // about anything.
  2843. FileNullability &fileNullability = S.NullabilityMap[file];
  2844. if (!fileNullability.SawTypeNullability) {
  2845. // If this is the first pointer declarator in the file, record it.
  2846. if (fileNullability.PointerLoc.isInvalid() &&
  2847. !S.Context.getDiagnostics().isIgnored(diag::warn_nullability_missing,
  2848. pointerLoc)) {
  2849. fileNullability.PointerLoc = pointerLoc;
  2850. fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
  2851. }
  2852. return;
  2853. }
  2854. // Complain about missing nullability.
  2855. S.Diag(pointerLoc, diag::warn_nullability_missing)
  2856. << static_cast<unsigned>(pointerKind);
  2857. }
  2858. static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
  2859. QualType declSpecType,
  2860. TypeSourceInfo *TInfo) {
  2861. // The TypeSourceInfo that this function returns will not be a null type.
  2862. // If there is an error, this function will fill in a dummy type as fallback.
  2863. QualType T = declSpecType;
  2864. Declarator &D = state.getDeclarator();
  2865. Sema &S = state.getSema();
  2866. ASTContext &Context = S.Context;
  2867. const LangOptions &LangOpts = S.getLangOpts();
  2868. // The name we're declaring, if any.
  2869. DeclarationName Name;
  2870. if (D.getIdentifier())
  2871. Name = D.getIdentifier();
  2872. // Does this declaration declare a typedef-name?
  2873. bool IsTypedefName =
  2874. D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
  2875. D.getContext() == Declarator::AliasDeclContext ||
  2876. D.getContext() == Declarator::AliasTemplateContext;
  2877. // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
  2878. bool IsQualifiedFunction = T->isFunctionProtoType() &&
  2879. (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
  2880. T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
  2881. // If T is 'decltype(auto)', the only declarators we can have are parens
  2882. // and at most one function declarator if this is a function declaration.
  2883. if (const AutoType *AT = T->getAs<AutoType>()) {
  2884. if (AT->isDecltypeAuto()) {
  2885. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  2886. unsigned Index = E - I - 1;
  2887. DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
  2888. unsigned DiagId = diag::err_decltype_auto_compound_type;
  2889. unsigned DiagKind = 0;
  2890. switch (DeclChunk.Kind) {
  2891. case DeclaratorChunk::Paren:
  2892. continue;
  2893. case DeclaratorChunk::Function: {
  2894. unsigned FnIndex;
  2895. if (D.isFunctionDeclarationContext() &&
  2896. D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
  2897. continue;
  2898. DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
  2899. break;
  2900. }
  2901. case DeclaratorChunk::Pointer:
  2902. case DeclaratorChunk::BlockPointer:
  2903. case DeclaratorChunk::MemberPointer:
  2904. DiagKind = 0;
  2905. break;
  2906. case DeclaratorChunk::Reference:
  2907. DiagKind = 1;
  2908. break;
  2909. case DeclaratorChunk::Array:
  2910. DiagKind = 2;
  2911. break;
  2912. case DeclaratorChunk::Pipe:
  2913. break;
  2914. }
  2915. S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
  2916. D.setInvalidType(true);
  2917. break;
  2918. }
  2919. }
  2920. }
  2921. // Determine whether we should infer _Nonnull on pointer types.
  2922. Optional<NullabilityKind> inferNullability;
  2923. bool inferNullabilityCS = false;
  2924. bool inferNullabilityInnerOnly = false;
  2925. bool inferNullabilityInnerOnlyComplete = false;
  2926. // Are we in an assume-nonnull region?
  2927. bool inAssumeNonNullRegion = false;
  2928. if (S.PP.getPragmaAssumeNonNullLoc().isValid()) {
  2929. inAssumeNonNullRegion = true;
  2930. // Determine which file we saw the assume-nonnull region in.
  2931. FileID file = getNullabilityCompletenessCheckFileID(
  2932. S, S.PP.getPragmaAssumeNonNullLoc());
  2933. if (file.isValid()) {
  2934. FileNullability &fileNullability = S.NullabilityMap[file];
  2935. // If we haven't seen any type nullability before, now we have.
  2936. if (!fileNullability.SawTypeNullability) {
  2937. if (fileNullability.PointerLoc.isValid()) {
  2938. S.Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
  2939. << static_cast<unsigned>(fileNullability.PointerKind);
  2940. }
  2941. fileNullability.SawTypeNullability = true;
  2942. }
  2943. }
  2944. }
  2945. // Whether to complain about missing nullability specifiers or not.
  2946. enum {
  2947. /// Never complain.
  2948. CAMN_No,
  2949. /// Complain on the inner pointers (but not the outermost
  2950. /// pointer).
  2951. CAMN_InnerPointers,
  2952. /// Complain about any pointers that don't have nullability
  2953. /// specified or inferred.
  2954. CAMN_Yes
  2955. } complainAboutMissingNullability = CAMN_No;
  2956. unsigned NumPointersRemaining = 0;
  2957. if (IsTypedefName) {
  2958. // For typedefs, we do not infer any nullability (the default),
  2959. // and we only complain about missing nullability specifiers on
  2960. // inner pointers.
  2961. complainAboutMissingNullability = CAMN_InnerPointers;
  2962. if (T->canHaveNullability() && !T->getNullability(S.Context)) {
  2963. ++NumPointersRemaining;
  2964. }
  2965. for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
  2966. DeclaratorChunk &chunk = D.getTypeObject(i);
  2967. switch (chunk.Kind) {
  2968. case DeclaratorChunk::Array:
  2969. case DeclaratorChunk::Function:
  2970. case DeclaratorChunk::Pipe:
  2971. break;
  2972. case DeclaratorChunk::BlockPointer:
  2973. case DeclaratorChunk::MemberPointer:
  2974. ++NumPointersRemaining;
  2975. break;
  2976. case DeclaratorChunk::Paren:
  2977. case DeclaratorChunk::Reference:
  2978. continue;
  2979. case DeclaratorChunk::Pointer:
  2980. ++NumPointersRemaining;
  2981. continue;
  2982. }
  2983. }
  2984. } else {
  2985. bool isFunctionOrMethod = false;
  2986. switch (auto context = state.getDeclarator().getContext()) {
  2987. case Declarator::ObjCParameterContext:
  2988. case Declarator::ObjCResultContext:
  2989. case Declarator::PrototypeContext:
  2990. case Declarator::TrailingReturnContext:
  2991. isFunctionOrMethod = true;
  2992. // fallthrough
  2993. case Declarator::MemberContext:
  2994. if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
  2995. complainAboutMissingNullability = CAMN_No;
  2996. break;
  2997. }
  2998. // Weak properties are inferred to be nullable.
  2999. if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
  3000. inferNullability = NullabilityKind::Nullable;
  3001. break;
  3002. }
  3003. // fallthrough
  3004. case Declarator::FileContext:
  3005. case Declarator::KNRTypeListContext:
  3006. complainAboutMissingNullability = CAMN_Yes;
  3007. // Nullability inference depends on the type and declarator.
  3008. switch (classifyPointerDeclarator(S, T, D)) {
  3009. case PointerDeclaratorKind::NonPointer:
  3010. case PointerDeclaratorKind::MultiLevelPointer:
  3011. // Cannot infer nullability.
  3012. break;
  3013. case PointerDeclaratorKind::SingleLevelPointer:
  3014. // Infer _Nonnull if we are in an assumes-nonnull region.
  3015. if (inAssumeNonNullRegion) {
  3016. inferNullability = NullabilityKind::NonNull;
  3017. inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
  3018. context == Declarator::ObjCResultContext);
  3019. }
  3020. break;
  3021. case PointerDeclaratorKind::CFErrorRefPointer:
  3022. case PointerDeclaratorKind::NSErrorPointerPointer:
  3023. // Within a function or method signature, infer _Nullable at both
  3024. // levels.
  3025. if (isFunctionOrMethod && inAssumeNonNullRegion)
  3026. inferNullability = NullabilityKind::Nullable;
  3027. break;
  3028. case PointerDeclaratorKind::MaybePointerToCFRef:
  3029. if (isFunctionOrMethod) {
  3030. // On pointer-to-pointer parameters marked cf_returns_retained or
  3031. // cf_returns_not_retained, if the outer pointer is explicit then
  3032. // infer the inner pointer as _Nullable.
  3033. auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
  3034. while (NextAttr) {
  3035. if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
  3036. NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
  3037. return true;
  3038. NextAttr = NextAttr->getNext();
  3039. }
  3040. return false;
  3041. };
  3042. if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
  3043. if (hasCFReturnsAttr(D.getAttributes()) ||
  3044. hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
  3045. hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
  3046. inferNullability = NullabilityKind::Nullable;
  3047. inferNullabilityInnerOnly = true;
  3048. }
  3049. }
  3050. }
  3051. break;
  3052. }
  3053. break;
  3054. case Declarator::ConversionIdContext:
  3055. complainAboutMissingNullability = CAMN_Yes;
  3056. break;
  3057. case Declarator::AliasDeclContext:
  3058. case Declarator::AliasTemplateContext:
  3059. case Declarator::BlockContext:
  3060. case Declarator::BlockLiteralContext:
  3061. case Declarator::ConditionContext:
  3062. case Declarator::CXXCatchContext:
  3063. case Declarator::CXXNewContext:
  3064. case Declarator::ForContext:
  3065. case Declarator::LambdaExprContext:
  3066. case Declarator::LambdaExprParameterContext:
  3067. case Declarator::ObjCCatchContext:
  3068. case Declarator::TemplateParamContext:
  3069. case Declarator::TemplateTypeArgContext:
  3070. case Declarator::TypeNameContext:
  3071. // Don't infer in these contexts.
  3072. break;
  3073. }
  3074. }
  3075. // Local function that checks the nullability for a given pointer declarator.
  3076. // Returns true if _Nonnull was inferred.
  3077. auto inferPointerNullability = [&](SimplePointerKind pointerKind,
  3078. SourceLocation pointerLoc,
  3079. AttributeList *&attrs) -> AttributeList * {
  3080. // We've seen a pointer.
  3081. if (NumPointersRemaining > 0)
  3082. --NumPointersRemaining;
  3083. // If a nullability attribute is present, there's nothing to do.
  3084. if (hasNullabilityAttr(attrs))
  3085. return nullptr;
  3086. // If we're supposed to infer nullability, do so now.
  3087. if (inferNullability && !inferNullabilityInnerOnlyComplete) {
  3088. AttributeList::Syntax syntax
  3089. = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
  3090. : AttributeList::AS_Keyword;
  3091. AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
  3092. .create(
  3093. S.getNullabilityKeyword(
  3094. *inferNullability),
  3095. SourceRange(pointerLoc),
  3096. nullptr, SourceLocation(),
  3097. nullptr, 0, syntax);
  3098. spliceAttrIntoList(*nullabilityAttr, attrs);
  3099. if (inferNullabilityCS) {
  3100. state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
  3101. ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
  3102. }
  3103. if (inferNullabilityInnerOnly)
  3104. inferNullabilityInnerOnlyComplete = true;
  3105. return nullabilityAttr;
  3106. }
  3107. // If we're supposed to complain about missing nullability, do so
  3108. // now if it's truly missing.
  3109. switch (complainAboutMissingNullability) {
  3110. case CAMN_No:
  3111. break;
  3112. case CAMN_InnerPointers:
  3113. if (NumPointersRemaining == 0)
  3114. break;
  3115. // Fallthrough.
  3116. case CAMN_Yes:
  3117. checkNullabilityConsistency(state, pointerKind, pointerLoc);
  3118. }
  3119. return nullptr;
  3120. };
  3121. // If the type itself could have nullability but does not, infer pointer
  3122. // nullability and perform consistency checking.
  3123. if (T->canHaveNullability() && S.ActiveTemplateInstantiations.empty() &&
  3124. !T->getNullability(S.Context)) {
  3125. SimplePointerKind pointerKind = SimplePointerKind::Pointer;
  3126. if (T->isBlockPointerType())
  3127. pointerKind = SimplePointerKind::BlockPointer;
  3128. else if (T->isMemberPointerType())
  3129. pointerKind = SimplePointerKind::MemberPointer;
  3130. if (auto *attr = inferPointerNullability(
  3131. pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
  3132. D.getMutableDeclSpec().getAttributes().getListRef())) {
  3133. T = Context.getAttributedType(
  3134. AttributedType::getNullabilityAttrKind(*inferNullability), T, T);
  3135. attr->setUsedAsTypeAttr();
  3136. }
  3137. }
  3138. // Walk the DeclTypeInfo, building the recursive type as we go.
  3139. // DeclTypeInfos are ordered from the identifier out, which is
  3140. // opposite of what we want :).
  3141. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  3142. unsigned chunkIndex = e - i - 1;
  3143. state.setCurrentChunkIndex(chunkIndex);
  3144. DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
  3145. IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
  3146. switch (DeclType.Kind) {
  3147. case DeclaratorChunk::Paren:
  3148. T = S.BuildParenType(T);
  3149. break;
  3150. case DeclaratorChunk::BlockPointer:
  3151. // If blocks are disabled, emit an error.
  3152. if (!LangOpts.Blocks)
  3153. S.Diag(DeclType.Loc, diag::err_blocks_disable);
  3154. // Handle pointer nullability.
  3155. inferPointerNullability(SimplePointerKind::BlockPointer,
  3156. DeclType.Loc, DeclType.getAttrListRef());
  3157. T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
  3158. if (DeclType.Cls.TypeQuals)
  3159. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
  3160. break;
  3161. case DeclaratorChunk::Pointer:
  3162. // Verify that we're not building a pointer to pointer to function with
  3163. // exception specification.
  3164. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  3165. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  3166. D.setInvalidType(true);
  3167. // Build the type anyway.
  3168. }
  3169. // Handle pointer nullability
  3170. inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
  3171. DeclType.getAttrListRef());
  3172. if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
  3173. T = Context.getObjCObjectPointerType(T);
  3174. if (DeclType.Ptr.TypeQuals)
  3175. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
  3176. break;
  3177. }
  3178. T = S.BuildPointerType(T, DeclType.Loc, Name);
  3179. if (DeclType.Ptr.TypeQuals)
  3180. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
  3181. break;
  3182. case DeclaratorChunk::Reference: {
  3183. // Verify that we're not building a reference to pointer to function with
  3184. // exception specification.
  3185. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  3186. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  3187. D.setInvalidType(true);
  3188. // Build the type anyway.
  3189. }
  3190. T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
  3191. if (DeclType.Ref.HasRestrict)
  3192. T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
  3193. break;
  3194. }
  3195. case DeclaratorChunk::Array: {
  3196. // Verify that we're not building an array of pointers to function with
  3197. // exception specification.
  3198. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  3199. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  3200. D.setInvalidType(true);
  3201. // Build the type anyway.
  3202. }
  3203. DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
  3204. Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
  3205. ArrayType::ArraySizeModifier ASM;
  3206. if (ATI.isStar)
  3207. ASM = ArrayType::Star;
  3208. else if (ATI.hasStatic)
  3209. ASM = ArrayType::Static;
  3210. else
  3211. ASM = ArrayType::Normal;
  3212. if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
  3213. // FIXME: This check isn't quite right: it allows star in prototypes
  3214. // for function definitions, and disallows some edge cases detailed
  3215. // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
  3216. S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
  3217. ASM = ArrayType::Normal;
  3218. D.setInvalidType(true);
  3219. }
  3220. // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
  3221. // shall appear only in a declaration of a function parameter with an
  3222. // array type, ...
  3223. if (ASM == ArrayType::Static || ATI.TypeQuals) {
  3224. if (!(D.isPrototypeContext() ||
  3225. D.getContext() == Declarator::KNRTypeListContext)) {
  3226. S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
  3227. (ASM == ArrayType::Static ? "'static'" : "type qualifier");
  3228. // Remove the 'static' and the type qualifiers.
  3229. if (ASM == ArrayType::Static)
  3230. ASM = ArrayType::Normal;
  3231. ATI.TypeQuals = 0;
  3232. D.setInvalidType(true);
  3233. }
  3234. // C99 6.7.5.2p1: ... and then only in the outermost array type
  3235. // derivation.
  3236. unsigned x = chunkIndex;
  3237. while (x != 0) {
  3238. // Walk outwards along the declarator chunks.
  3239. x--;
  3240. const DeclaratorChunk &DC = D.getTypeObject(x);
  3241. switch (DC.Kind) {
  3242. case DeclaratorChunk::Paren:
  3243. continue;
  3244. case DeclaratorChunk::Array:
  3245. case DeclaratorChunk::Pointer:
  3246. case DeclaratorChunk::Reference:
  3247. case DeclaratorChunk::MemberPointer:
  3248. S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
  3249. (ASM == ArrayType::Static ? "'static'" : "type qualifier");
  3250. if (ASM == ArrayType::Static)
  3251. ASM = ArrayType::Normal;
  3252. ATI.TypeQuals = 0;
  3253. D.setInvalidType(true);
  3254. break;
  3255. case DeclaratorChunk::Function:
  3256. case DeclaratorChunk::BlockPointer:
  3257. case DeclaratorChunk::Pipe:
  3258. // These are invalid anyway, so just ignore.
  3259. break;
  3260. }
  3261. }
  3262. }
  3263. const AutoType *AT = T->getContainedAutoType();
  3264. // Allow arrays of auto if we are a generic lambda parameter.
  3265. // i.e. [](auto (&array)[5]) { return array[0]; }; OK
  3266. if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
  3267. // We've already diagnosed this for decltype(auto).
  3268. if (!AT->isDecltypeAuto())
  3269. S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
  3270. << getPrintableNameForEntity(Name) << T;
  3271. T = QualType();
  3272. break;
  3273. }
  3274. T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
  3275. SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
  3276. break;
  3277. }
  3278. case DeclaratorChunk::Function: {
  3279. // If the function declarator has a prototype (i.e. it is not () and
  3280. // does not have a K&R-style identifier list), then the arguments are part
  3281. // of the type, otherwise the argument list is ().
  3282. const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
  3283. IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
  3284. // Check for auto functions and trailing return type and adjust the
  3285. // return type accordingly.
  3286. if (!D.isInvalidType()) {
  3287. // trailing-return-type is only required if we're declaring a function,
  3288. // and not, for instance, a pointer to a function.
  3289. if (D.getDeclSpec().containsPlaceholderType() &&
  3290. !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
  3291. !S.getLangOpts().CPlusPlus14) {
  3292. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  3293. D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
  3294. ? diag::err_auto_missing_trailing_return
  3295. : diag::err_deduced_return_type);
  3296. T = Context.IntTy;
  3297. D.setInvalidType(true);
  3298. } else if (FTI.hasTrailingReturnType()) {
  3299. // T must be exactly 'auto' at this point. See CWG issue 681.
  3300. if (isa<ParenType>(T)) {
  3301. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  3302. diag::err_trailing_return_in_parens)
  3303. << T << D.getDeclSpec().getSourceRange();
  3304. D.setInvalidType(true);
  3305. } else if (D.getContext() != Declarator::LambdaExprContext &&
  3306. (T.hasQualifiers() || !isa<AutoType>(T) ||
  3307. cast<AutoType>(T)->getKeyword() != AutoTypeKeyword::Auto)) {
  3308. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  3309. diag::err_trailing_return_without_auto)
  3310. << T << D.getDeclSpec().getSourceRange();
  3311. D.setInvalidType(true);
  3312. }
  3313. T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
  3314. if (T.isNull()) {
  3315. // An error occurred parsing the trailing return type.
  3316. T = Context.IntTy;
  3317. D.setInvalidType(true);
  3318. }
  3319. }
  3320. }
  3321. // C99 6.7.5.3p1: The return type may not be a function or array type.
  3322. // For conversion functions, we'll diagnose this particular error later.
  3323. if ((T->isArrayType() || T->isFunctionType()) &&
  3324. (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
  3325. unsigned diagID = diag::err_func_returning_array_function;
  3326. // Last processing chunk in block context means this function chunk
  3327. // represents the block.
  3328. if (chunkIndex == 0 &&
  3329. D.getContext() == Declarator::BlockLiteralContext)
  3330. diagID = diag::err_block_returning_array_function;
  3331. S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
  3332. T = Context.IntTy;
  3333. D.setInvalidType(true);
  3334. }
  3335. // Do not allow returning half FP value.
  3336. // FIXME: This really should be in BuildFunctionType.
  3337. if (T->isHalfType()) {
  3338. if (S.getLangOpts().OpenCL) {
  3339. if (!S.getOpenCLOptions().cl_khr_fp16) {
  3340. S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
  3341. D.setInvalidType(true);
  3342. }
  3343. } else if (!S.getLangOpts().HalfArgsAndReturns) {
  3344. S.Diag(D.getIdentifierLoc(),
  3345. diag::err_parameters_retval_cannot_have_fp16_type) << 1;
  3346. D.setInvalidType(true);
  3347. }
  3348. }
  3349. // Methods cannot return interface types. All ObjC objects are
  3350. // passed by reference.
  3351. if (T->isObjCObjectType()) {
  3352. SourceLocation DiagLoc, FixitLoc;
  3353. if (TInfo) {
  3354. DiagLoc = TInfo->getTypeLoc().getLocStart();
  3355. FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
  3356. } else {
  3357. DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
  3358. FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
  3359. }
  3360. S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
  3361. << 0 << T
  3362. << FixItHint::CreateInsertion(FixitLoc, "*");
  3363. T = Context.getObjCObjectPointerType(T);
  3364. if (TInfo) {
  3365. TypeLocBuilder TLB;
  3366. TLB.pushFullCopy(TInfo->getTypeLoc());
  3367. ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
  3368. TLoc.setStarLoc(FixitLoc);
  3369. TInfo = TLB.getTypeSourceInfo(Context, T);
  3370. }
  3371. D.setInvalidType(true);
  3372. }
  3373. // cv-qualifiers on return types are pointless except when the type is a
  3374. // class type in C++.
  3375. if ((T.getCVRQualifiers() || T->isAtomicType()) &&
  3376. !(S.getLangOpts().CPlusPlus &&
  3377. (T->isDependentType() || T->isRecordType()))) {
  3378. if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
  3379. D.getFunctionDefinitionKind() == FDK_Definition) {
  3380. // [6.9.1/3] qualified void return is invalid on a C
  3381. // function definition. Apparently ok on declarations and
  3382. // in C++ though (!)
  3383. S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
  3384. } else
  3385. diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
  3386. }
  3387. // Objective-C ARC ownership qualifiers are ignored on the function
  3388. // return type (by type canonicalization). Complain if this attribute
  3389. // was written here.
  3390. if (T.getQualifiers().hasObjCLifetime()) {
  3391. SourceLocation AttrLoc;
  3392. if (chunkIndex + 1 < D.getNumTypeObjects()) {
  3393. DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
  3394. for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
  3395. Attr; Attr = Attr->getNext()) {
  3396. if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
  3397. AttrLoc = Attr->getLoc();
  3398. break;
  3399. }
  3400. }
  3401. }
  3402. if (AttrLoc.isInvalid()) {
  3403. for (const AttributeList *Attr
  3404. = D.getDeclSpec().getAttributes().getList();
  3405. Attr; Attr = Attr->getNext()) {
  3406. if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
  3407. AttrLoc = Attr->getLoc();
  3408. break;
  3409. }
  3410. }
  3411. }
  3412. if (AttrLoc.isValid()) {
  3413. // The ownership attributes are almost always written via
  3414. // the predefined
  3415. // __strong/__weak/__autoreleasing/__unsafe_unretained.
  3416. if (AttrLoc.isMacroID())
  3417. AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
  3418. S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
  3419. << T.getQualifiers().getObjCLifetime();
  3420. }
  3421. }
  3422. if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
  3423. // C++ [dcl.fct]p6:
  3424. // Types shall not be defined in return or parameter types.
  3425. TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  3426. S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
  3427. << Context.getTypeDeclType(Tag);
  3428. }
  3429. // Exception specs are not allowed in typedefs. Complain, but add it
  3430. // anyway.
  3431. if (IsTypedefName && FTI.getExceptionSpecType())
  3432. S.Diag(FTI.getExceptionSpecLocBeg(),
  3433. diag::err_exception_spec_in_typedef)
  3434. << (D.getContext() == Declarator::AliasDeclContext ||
  3435. D.getContext() == Declarator::AliasTemplateContext);
  3436. // If we see "T var();" or "T var(T());" at block scope, it is probably
  3437. // an attempt to initialize a variable, not a function declaration.
  3438. if (FTI.isAmbiguous)
  3439. warnAboutAmbiguousFunction(S, D, DeclType, T);
  3440. FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
  3441. if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
  3442. // Simple void foo(), where the incoming T is the result type.
  3443. T = Context.getFunctionNoProtoType(T, EI);
  3444. } else {
  3445. // We allow a zero-parameter variadic function in C if the
  3446. // function is marked with the "overloadable" attribute. Scan
  3447. // for this attribute now.
  3448. if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
  3449. bool Overloadable = false;
  3450. for (const AttributeList *Attrs = D.getAttributes();
  3451. Attrs; Attrs = Attrs->getNext()) {
  3452. if (Attrs->getKind() == AttributeList::AT_Overloadable) {
  3453. Overloadable = true;
  3454. break;
  3455. }
  3456. }
  3457. if (!Overloadable)
  3458. S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
  3459. }
  3460. if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
  3461. // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
  3462. // definition.
  3463. S.Diag(FTI.Params[0].IdentLoc,
  3464. diag::err_ident_list_in_fn_declaration);
  3465. D.setInvalidType(true);
  3466. // Recover by creating a K&R-style function type.
  3467. T = Context.getFunctionNoProtoType(T, EI);
  3468. break;
  3469. }
  3470. FunctionProtoType::ExtProtoInfo EPI;
  3471. EPI.ExtInfo = EI;
  3472. EPI.Variadic = FTI.isVariadic;
  3473. EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
  3474. EPI.TypeQuals = FTI.TypeQuals;
  3475. EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
  3476. : FTI.RefQualifierIsLValueRef? RQ_LValue
  3477. : RQ_RValue;
  3478. // Otherwise, we have a function with a parameter list that is
  3479. // potentially variadic.
  3480. SmallVector<QualType, 16> ParamTys;
  3481. ParamTys.reserve(FTI.NumParams);
  3482. SmallVector<bool, 16> ConsumedParameters;
  3483. ConsumedParameters.reserve(FTI.NumParams);
  3484. bool HasAnyConsumedParameters = false;
  3485. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  3486. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  3487. QualType ParamTy = Param->getType();
  3488. assert(!ParamTy.isNull() && "Couldn't parse type?");
  3489. // Look for 'void'. void is allowed only as a single parameter to a
  3490. // function with no other parameters (C99 6.7.5.3p10). We record
  3491. // int(void) as a FunctionProtoType with an empty parameter list.
  3492. if (ParamTy->isVoidType()) {
  3493. // If this is something like 'float(int, void)', reject it. 'void'
  3494. // is an incomplete type (C99 6.2.5p19) and function decls cannot
  3495. // have parameters of incomplete type.
  3496. if (FTI.NumParams != 1 || FTI.isVariadic) {
  3497. S.Diag(DeclType.Loc, diag::err_void_only_param);
  3498. ParamTy = Context.IntTy;
  3499. Param->setType(ParamTy);
  3500. } else if (FTI.Params[i].Ident) {
  3501. // Reject, but continue to parse 'int(void abc)'.
  3502. S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
  3503. ParamTy = Context.IntTy;
  3504. Param->setType(ParamTy);
  3505. } else {
  3506. // Reject, but continue to parse 'float(const void)'.
  3507. if (ParamTy.hasQualifiers())
  3508. S.Diag(DeclType.Loc, diag::err_void_param_qualified);
  3509. // Do not add 'void' to the list.
  3510. break;
  3511. }
  3512. } else if (ParamTy->isHalfType()) {
  3513. // Disallow half FP parameters.
  3514. // FIXME: This really should be in BuildFunctionType.
  3515. if (S.getLangOpts().OpenCL) {
  3516. if (!S.getOpenCLOptions().cl_khr_fp16) {
  3517. S.Diag(Param->getLocation(),
  3518. diag::err_opencl_half_param) << ParamTy;
  3519. D.setInvalidType();
  3520. Param->setInvalidDecl();
  3521. }
  3522. } else if (!S.getLangOpts().HalfArgsAndReturns) {
  3523. S.Diag(Param->getLocation(),
  3524. diag::err_parameters_retval_cannot_have_fp16_type) << 0;
  3525. D.setInvalidType();
  3526. }
  3527. } else if (!FTI.hasPrototype) {
  3528. if (ParamTy->isPromotableIntegerType()) {
  3529. ParamTy = Context.getPromotedIntegerType(ParamTy);
  3530. Param->setKNRPromoted(true);
  3531. } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
  3532. if (BTy->getKind() == BuiltinType::Float) {
  3533. ParamTy = Context.DoubleTy;
  3534. Param->setKNRPromoted(true);
  3535. }
  3536. }
  3537. }
  3538. if (LangOpts.ObjCAutoRefCount) {
  3539. bool Consumed = Param->hasAttr<NSConsumedAttr>();
  3540. ConsumedParameters.push_back(Consumed);
  3541. HasAnyConsumedParameters |= Consumed;
  3542. }
  3543. ParamTys.push_back(ParamTy);
  3544. }
  3545. if (HasAnyConsumedParameters)
  3546. EPI.ConsumedParameters = ConsumedParameters.data();
  3547. SmallVector<QualType, 4> Exceptions;
  3548. SmallVector<ParsedType, 2> DynamicExceptions;
  3549. SmallVector<SourceRange, 2> DynamicExceptionRanges;
  3550. Expr *NoexceptExpr = nullptr;
  3551. if (FTI.getExceptionSpecType() == EST_Dynamic) {
  3552. // FIXME: It's rather inefficient to have to split into two vectors
  3553. // here.
  3554. unsigned N = FTI.NumExceptions;
  3555. DynamicExceptions.reserve(N);
  3556. DynamicExceptionRanges.reserve(N);
  3557. for (unsigned I = 0; I != N; ++I) {
  3558. DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
  3559. DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
  3560. }
  3561. } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
  3562. NoexceptExpr = FTI.NoexceptExpr;
  3563. }
  3564. S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
  3565. FTI.getExceptionSpecType(),
  3566. DynamicExceptions,
  3567. DynamicExceptionRanges,
  3568. NoexceptExpr,
  3569. Exceptions,
  3570. EPI.ExceptionSpec);
  3571. T = Context.getFunctionType(T, ParamTys, EPI);
  3572. }
  3573. break;
  3574. }
  3575. case DeclaratorChunk::MemberPointer: {
  3576. // The scope spec must refer to a class, or be dependent.
  3577. CXXScopeSpec &SS = DeclType.Mem.Scope();
  3578. QualType ClsType;
  3579. // Handle pointer nullability.
  3580. inferPointerNullability(SimplePointerKind::MemberPointer,
  3581. DeclType.Loc, DeclType.getAttrListRef());
  3582. if (SS.isInvalid()) {
  3583. // Avoid emitting extra errors if we already errored on the scope.
  3584. D.setInvalidType(true);
  3585. } else if (S.isDependentScopeSpecifier(SS) ||
  3586. dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
  3587. NestedNameSpecifier *NNS = SS.getScopeRep();
  3588. NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
  3589. switch (NNS->getKind()) {
  3590. case NestedNameSpecifier::Identifier:
  3591. ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
  3592. NNS->getAsIdentifier());
  3593. break;
  3594. case NestedNameSpecifier::Namespace:
  3595. case NestedNameSpecifier::NamespaceAlias:
  3596. case NestedNameSpecifier::Global:
  3597. case NestedNameSpecifier::Super:
  3598. llvm_unreachable("Nested-name-specifier must name a type");
  3599. case NestedNameSpecifier::TypeSpec:
  3600. case NestedNameSpecifier::TypeSpecWithTemplate:
  3601. ClsType = QualType(NNS->getAsType(), 0);
  3602. // Note: if the NNS has a prefix and ClsType is a nondependent
  3603. // TemplateSpecializationType, then the NNS prefix is NOT included
  3604. // in ClsType; hence we wrap ClsType into an ElaboratedType.
  3605. // NOTE: in particular, no wrap occurs if ClsType already is an
  3606. // Elaborated, DependentName, or DependentTemplateSpecialization.
  3607. if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
  3608. ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
  3609. break;
  3610. }
  3611. } else {
  3612. S.Diag(DeclType.Mem.Scope().getBeginLoc(),
  3613. diag::err_illegal_decl_mempointer_in_nonclass)
  3614. << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
  3615. << DeclType.Mem.Scope().getRange();
  3616. D.setInvalidType(true);
  3617. }
  3618. if (!ClsType.isNull())
  3619. T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
  3620. D.getIdentifier());
  3621. if (T.isNull()) {
  3622. T = Context.IntTy;
  3623. D.setInvalidType(true);
  3624. } else if (DeclType.Mem.TypeQuals) {
  3625. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
  3626. }
  3627. break;
  3628. }
  3629. case DeclaratorChunk::Pipe: {
  3630. T = S.BuildPipeType(T, DeclType.Loc );
  3631. break;
  3632. }
  3633. }
  3634. if (T.isNull()) {
  3635. D.setInvalidType(true);
  3636. T = Context.IntTy;
  3637. }
  3638. // See if there are any attributes on this declarator chunk.
  3639. processTypeAttrs(state, T, TAL_DeclChunk,
  3640. const_cast<AttributeList *>(DeclType.getAttrs()));
  3641. }
  3642. assert(!T.isNull() && "T must not be null after this point");
  3643. if (LangOpts.CPlusPlus && T->isFunctionType()) {
  3644. const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
  3645. assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
  3646. // C++ 8.3.5p4:
  3647. // A cv-qualifier-seq shall only be part of the function type
  3648. // for a nonstatic member function, the function type to which a pointer
  3649. // to member refers, or the top-level function type of a function typedef
  3650. // declaration.
  3651. //
  3652. // Core issue 547 also allows cv-qualifiers on function types that are
  3653. // top-level template type arguments.
  3654. bool FreeFunction;
  3655. if (!D.getCXXScopeSpec().isSet()) {
  3656. FreeFunction = ((D.getContext() != Declarator::MemberContext &&
  3657. D.getContext() != Declarator::LambdaExprContext) ||
  3658. D.getDeclSpec().isFriendSpecified());
  3659. } else {
  3660. DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
  3661. FreeFunction = (DC && !DC->isRecord());
  3662. }
  3663. // C++11 [dcl.fct]p6 (w/DR1417):
  3664. // An attempt to specify a function type with a cv-qualifier-seq or a
  3665. // ref-qualifier (including by typedef-name) is ill-formed unless it is:
  3666. // - the function type for a non-static member function,
  3667. // - the function type to which a pointer to member refers,
  3668. // - the top-level function type of a function typedef declaration or
  3669. // alias-declaration,
  3670. // - the type-id in the default argument of a type-parameter, or
  3671. // - the type-id of a template-argument for a type-parameter
  3672. //
  3673. // FIXME: Checking this here is insufficient. We accept-invalid on:
  3674. //
  3675. // template<typename T> struct S { void f(T); };
  3676. // S<int() const> s;
  3677. //
  3678. // ... for instance.
  3679. if (IsQualifiedFunction &&
  3680. !(!FreeFunction &&
  3681. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
  3682. !IsTypedefName &&
  3683. D.getContext() != Declarator::TemplateTypeArgContext) {
  3684. SourceLocation Loc = D.getLocStart();
  3685. SourceRange RemovalRange;
  3686. unsigned I;
  3687. if (D.isFunctionDeclarator(I)) {
  3688. SmallVector<SourceLocation, 4> RemovalLocs;
  3689. const DeclaratorChunk &Chunk = D.getTypeObject(I);
  3690. assert(Chunk.Kind == DeclaratorChunk::Function);
  3691. if (Chunk.Fun.hasRefQualifier())
  3692. RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
  3693. if (Chunk.Fun.TypeQuals & Qualifiers::Const)
  3694. RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
  3695. if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
  3696. RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
  3697. if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
  3698. RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
  3699. if (!RemovalLocs.empty()) {
  3700. std::sort(RemovalLocs.begin(), RemovalLocs.end(),
  3701. BeforeThanCompare<SourceLocation>(S.getSourceManager()));
  3702. RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
  3703. Loc = RemovalLocs.front();
  3704. }
  3705. }
  3706. S.Diag(Loc, diag::err_invalid_qualified_function_type)
  3707. << FreeFunction << D.isFunctionDeclarator() << T
  3708. << getFunctionQualifiersAsString(FnTy)
  3709. << FixItHint::CreateRemoval(RemovalRange);
  3710. // Strip the cv-qualifiers and ref-qualifiers from the type.
  3711. FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
  3712. EPI.TypeQuals = 0;
  3713. EPI.RefQualifier = RQ_None;
  3714. T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
  3715. EPI);
  3716. // Rebuild any parens around the identifier in the function type.
  3717. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  3718. if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
  3719. break;
  3720. T = S.BuildParenType(T);
  3721. }
  3722. }
  3723. }
  3724. // Apply any undistributed attributes from the declarator.
  3725. processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
  3726. // Diagnose any ignored type attributes.
  3727. state.diagnoseIgnoredTypeAttrs(T);
  3728. // C++0x [dcl.constexpr]p9:
  3729. // A constexpr specifier used in an object declaration declares the object
  3730. // as const.
  3731. if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
  3732. T.addConst();
  3733. }
  3734. // If there was an ellipsis in the declarator, the declaration declares a
  3735. // parameter pack whose type may be a pack expansion type.
  3736. if (D.hasEllipsis()) {
  3737. // C++0x [dcl.fct]p13:
  3738. // A declarator-id or abstract-declarator containing an ellipsis shall
  3739. // only be used in a parameter-declaration. Such a parameter-declaration
  3740. // is a parameter pack (14.5.3). [...]
  3741. switch (D.getContext()) {
  3742. case Declarator::PrototypeContext:
  3743. case Declarator::LambdaExprParameterContext:
  3744. // C++0x [dcl.fct]p13:
  3745. // [...] When it is part of a parameter-declaration-clause, the
  3746. // parameter pack is a function parameter pack (14.5.3). The type T
  3747. // of the declarator-id of the function parameter pack shall contain
  3748. // a template parameter pack; each template parameter pack in T is
  3749. // expanded by the function parameter pack.
  3750. //
  3751. // We represent function parameter packs as function parameters whose
  3752. // type is a pack expansion.
  3753. if (!T->containsUnexpandedParameterPack()) {
  3754. S.Diag(D.getEllipsisLoc(),
  3755. diag::err_function_parameter_pack_without_parameter_packs)
  3756. << T << D.getSourceRange();
  3757. D.setEllipsisLoc(SourceLocation());
  3758. } else {
  3759. T = Context.getPackExpansionType(T, None);
  3760. }
  3761. break;
  3762. case Declarator::TemplateParamContext:
  3763. // C++0x [temp.param]p15:
  3764. // If a template-parameter is a [...] is a parameter-declaration that
  3765. // declares a parameter pack (8.3.5), then the template-parameter is a
  3766. // template parameter pack (14.5.3).
  3767. //
  3768. // Note: core issue 778 clarifies that, if there are any unexpanded
  3769. // parameter packs in the type of the non-type template parameter, then
  3770. // it expands those parameter packs.
  3771. if (T->containsUnexpandedParameterPack())
  3772. T = Context.getPackExpansionType(T, None);
  3773. else
  3774. S.Diag(D.getEllipsisLoc(),
  3775. LangOpts.CPlusPlus11
  3776. ? diag::warn_cxx98_compat_variadic_templates
  3777. : diag::ext_variadic_templates);
  3778. break;
  3779. case Declarator::FileContext:
  3780. case Declarator::KNRTypeListContext:
  3781. case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
  3782. case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
  3783. case Declarator::TypeNameContext:
  3784. case Declarator::CXXNewContext:
  3785. case Declarator::AliasDeclContext:
  3786. case Declarator::AliasTemplateContext:
  3787. case Declarator::MemberContext:
  3788. case Declarator::BlockContext:
  3789. case Declarator::ForContext:
  3790. case Declarator::ConditionContext:
  3791. case Declarator::CXXCatchContext:
  3792. case Declarator::ObjCCatchContext:
  3793. case Declarator::BlockLiteralContext:
  3794. case Declarator::LambdaExprContext:
  3795. case Declarator::ConversionIdContext:
  3796. case Declarator::TrailingReturnContext:
  3797. case Declarator::TemplateTypeArgContext:
  3798. // FIXME: We may want to allow parameter packs in block-literal contexts
  3799. // in the future.
  3800. S.Diag(D.getEllipsisLoc(),
  3801. diag::err_ellipsis_in_declarator_not_parameter);
  3802. D.setEllipsisLoc(SourceLocation());
  3803. break;
  3804. }
  3805. }
  3806. assert(!T.isNull() && "T must not be null at the end of this function");
  3807. if (D.isInvalidType())
  3808. return Context.getTrivialTypeSourceInfo(T);
  3809. return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
  3810. }
  3811. /// GetTypeForDeclarator - Convert the type for the specified
  3812. /// declarator to Type instances.
  3813. ///
  3814. /// The result of this call will never be null, but the associated
  3815. /// type may be a null type if there's an unrecoverable error.
  3816. TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
  3817. // Determine the type of the declarator. Not all forms of declarator
  3818. // have a type.
  3819. TypeProcessingState state(*this, D);
  3820. TypeSourceInfo *ReturnTypeInfo = nullptr;
  3821. QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
  3822. if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
  3823. inferARCWriteback(state, T);
  3824. return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
  3825. }
  3826. static void transferARCOwnershipToDeclSpec(Sema &S,
  3827. QualType &declSpecTy,
  3828. Qualifiers::ObjCLifetime ownership) {
  3829. if (declSpecTy->isObjCRetainableType() &&
  3830. declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
  3831. Qualifiers qs;
  3832. qs.addObjCLifetime(ownership);
  3833. declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
  3834. }
  3835. }
  3836. static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
  3837. Qualifiers::ObjCLifetime ownership,
  3838. unsigned chunkIndex) {
  3839. Sema &S = state.getSema();
  3840. Declarator &D = state.getDeclarator();
  3841. // Look for an explicit lifetime attribute.
  3842. DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
  3843. for (const AttributeList *attr = chunk.getAttrs(); attr;
  3844. attr = attr->getNext())
  3845. if (attr->getKind() == AttributeList::AT_ObjCOwnership)
  3846. return;
  3847. const char *attrStr = nullptr;
  3848. switch (ownership) {
  3849. case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
  3850. case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
  3851. case Qualifiers::OCL_Strong: attrStr = "strong"; break;
  3852. case Qualifiers::OCL_Weak: attrStr = "weak"; break;
  3853. case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
  3854. }
  3855. IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
  3856. Arg->Ident = &S.Context.Idents.get(attrStr);
  3857. Arg->Loc = SourceLocation();
  3858. ArgsUnion Args(Arg);
  3859. // If there wasn't one, add one (with an invalid source location
  3860. // so that we don't make an AttributedType for it).
  3861. AttributeList *attr = D.getAttributePool()
  3862. .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
  3863. /*scope*/ nullptr, SourceLocation(),
  3864. /*args*/ &Args, 1, AttributeList::AS_GNU);
  3865. spliceAttrIntoList(*attr, chunk.getAttrListRef());
  3866. // TODO: mark whether we did this inference?
  3867. }
  3868. /// \brief Used for transferring ownership in casts resulting in l-values.
  3869. static void transferARCOwnership(TypeProcessingState &state,
  3870. QualType &declSpecTy,
  3871. Qualifiers::ObjCLifetime ownership) {
  3872. Sema &S = state.getSema();
  3873. Declarator &D = state.getDeclarator();
  3874. int inner = -1;
  3875. bool hasIndirection = false;
  3876. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  3877. DeclaratorChunk &chunk = D.getTypeObject(i);
  3878. switch (chunk.Kind) {
  3879. case DeclaratorChunk::Paren:
  3880. // Ignore parens.
  3881. break;
  3882. case DeclaratorChunk::Array:
  3883. case DeclaratorChunk::Reference:
  3884. case DeclaratorChunk::Pointer:
  3885. if (inner != -1)
  3886. hasIndirection = true;
  3887. inner = i;
  3888. break;
  3889. case DeclaratorChunk::BlockPointer:
  3890. if (inner != -1)
  3891. transferARCOwnershipToDeclaratorChunk(state, ownership, i);
  3892. return;
  3893. case DeclaratorChunk::Function:
  3894. case DeclaratorChunk::MemberPointer:
  3895. case DeclaratorChunk::Pipe:
  3896. return;
  3897. }
  3898. }
  3899. if (inner == -1)
  3900. return;
  3901. DeclaratorChunk &chunk = D.getTypeObject(inner);
  3902. if (chunk.Kind == DeclaratorChunk::Pointer) {
  3903. if (declSpecTy->isObjCRetainableType())
  3904. return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
  3905. if (declSpecTy->isObjCObjectType() && hasIndirection)
  3906. return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
  3907. } else {
  3908. assert(chunk.Kind == DeclaratorChunk::Array ||
  3909. chunk.Kind == DeclaratorChunk::Reference);
  3910. return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
  3911. }
  3912. }
  3913. TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
  3914. TypeProcessingState state(*this, D);
  3915. TypeSourceInfo *ReturnTypeInfo = nullptr;
  3916. QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
  3917. if (getLangOpts().ObjC1) {
  3918. Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
  3919. if (ownership != Qualifiers::OCL_None)
  3920. transferARCOwnership(state, declSpecTy, ownership);
  3921. }
  3922. return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
  3923. }
  3924. /// Map an AttributedType::Kind to an AttributeList::Kind.
  3925. static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
  3926. switch (kind) {
  3927. case AttributedType::attr_address_space:
  3928. return AttributeList::AT_AddressSpace;
  3929. case AttributedType::attr_regparm:
  3930. return AttributeList::AT_Regparm;
  3931. case AttributedType::attr_vector_size:
  3932. return AttributeList::AT_VectorSize;
  3933. case AttributedType::attr_neon_vector_type:
  3934. return AttributeList::AT_NeonVectorType;
  3935. case AttributedType::attr_neon_polyvector_type:
  3936. return AttributeList::AT_NeonPolyVectorType;
  3937. case AttributedType::attr_objc_gc:
  3938. return AttributeList::AT_ObjCGC;
  3939. case AttributedType::attr_objc_ownership:
  3940. case AttributedType::attr_objc_inert_unsafe_unretained:
  3941. return AttributeList::AT_ObjCOwnership;
  3942. case AttributedType::attr_noreturn:
  3943. return AttributeList::AT_NoReturn;
  3944. case AttributedType::attr_cdecl:
  3945. return AttributeList::AT_CDecl;
  3946. case AttributedType::attr_fastcall:
  3947. return AttributeList::AT_FastCall;
  3948. case AttributedType::attr_stdcall:
  3949. return AttributeList::AT_StdCall;
  3950. case AttributedType::attr_thiscall:
  3951. return AttributeList::AT_ThisCall;
  3952. case AttributedType::attr_pascal:
  3953. return AttributeList::AT_Pascal;
  3954. case AttributedType::attr_vectorcall:
  3955. return AttributeList::AT_VectorCall;
  3956. case AttributedType::attr_pcs:
  3957. case AttributedType::attr_pcs_vfp:
  3958. return AttributeList::AT_Pcs;
  3959. case AttributedType::attr_inteloclbicc:
  3960. return AttributeList::AT_IntelOclBicc;
  3961. case AttributedType::attr_ms_abi:
  3962. return AttributeList::AT_MSABI;
  3963. case AttributedType::attr_sysv_abi:
  3964. return AttributeList::AT_SysVABI;
  3965. case AttributedType::attr_ptr32:
  3966. return AttributeList::AT_Ptr32;
  3967. case AttributedType::attr_ptr64:
  3968. return AttributeList::AT_Ptr64;
  3969. case AttributedType::attr_sptr:
  3970. return AttributeList::AT_SPtr;
  3971. case AttributedType::attr_uptr:
  3972. return AttributeList::AT_UPtr;
  3973. case AttributedType::attr_nonnull:
  3974. return AttributeList::AT_TypeNonNull;
  3975. case AttributedType::attr_nullable:
  3976. return AttributeList::AT_TypeNullable;
  3977. case AttributedType::attr_null_unspecified:
  3978. return AttributeList::AT_TypeNullUnspecified;
  3979. case AttributedType::attr_objc_kindof:
  3980. return AttributeList::AT_ObjCKindOf;
  3981. }
  3982. llvm_unreachable("unexpected attribute kind!");
  3983. }
  3984. static void fillAttributedTypeLoc(AttributedTypeLoc TL,
  3985. const AttributeList *attrs,
  3986. const AttributeList *DeclAttrs = nullptr) {
  3987. // DeclAttrs and attrs cannot be both empty.
  3988. assert((attrs || DeclAttrs) &&
  3989. "no type attributes in the expected location!");
  3990. AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
  3991. // Try to search for an attribute of matching kind in attrs list.
  3992. while (attrs && attrs->getKind() != parsedKind)
  3993. attrs = attrs->getNext();
  3994. if (!attrs) {
  3995. // No matching type attribute in attrs list found.
  3996. // Try searching through C++11 attributes in the declarator attribute list.
  3997. while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
  3998. DeclAttrs->getKind() != parsedKind))
  3999. DeclAttrs = DeclAttrs->getNext();
  4000. attrs = DeclAttrs;
  4001. }
  4002. assert(attrs && "no matching type attribute in expected location!");
  4003. TL.setAttrNameLoc(attrs->getLoc());
  4004. if (TL.hasAttrExprOperand()) {
  4005. assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
  4006. TL.setAttrExprOperand(attrs->getArgAsExpr(0));
  4007. } else if (TL.hasAttrEnumOperand()) {
  4008. assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
  4009. "unexpected attribute operand kind");
  4010. if (attrs->isArgIdent(0))
  4011. TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
  4012. else
  4013. TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
  4014. }
  4015. // FIXME: preserve this information to here.
  4016. if (TL.hasAttrOperand())
  4017. TL.setAttrOperandParensRange(SourceRange());
  4018. }
  4019. namespace {
  4020. class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
  4021. ASTContext &Context;
  4022. const DeclSpec &DS;
  4023. public:
  4024. TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
  4025. : Context(Context), DS(DS) {}
  4026. void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  4027. fillAttributedTypeLoc(TL, DS.getAttributes().getList());
  4028. Visit(TL.getModifiedLoc());
  4029. }
  4030. void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  4031. Visit(TL.getUnqualifiedLoc());
  4032. }
  4033. void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  4034. TL.setNameLoc(DS.getTypeSpecTypeLoc());
  4035. }
  4036. void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  4037. TL.setNameLoc(DS.getTypeSpecTypeLoc());
  4038. // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
  4039. // addition field. What we have is good enough for dispay of location
  4040. // of 'fixit' on interface name.
  4041. TL.setNameEndLoc(DS.getLocEnd());
  4042. }
  4043. void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  4044. TypeSourceInfo *RepTInfo = nullptr;
  4045. Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
  4046. TL.copy(RepTInfo->getTypeLoc());
  4047. }
  4048. void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  4049. TypeSourceInfo *RepTInfo = nullptr;
  4050. Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
  4051. TL.copy(RepTInfo->getTypeLoc());
  4052. }
  4053. void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
  4054. TypeSourceInfo *TInfo = nullptr;
  4055. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4056. // If we got no declarator info from previous Sema routines,
  4057. // just fill with the typespec loc.
  4058. if (!TInfo) {
  4059. TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
  4060. return;
  4061. }
  4062. TypeLoc OldTL = TInfo->getTypeLoc();
  4063. if (TInfo->getType()->getAs<ElaboratedType>()) {
  4064. ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
  4065. TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
  4066. .castAs<TemplateSpecializationTypeLoc>();
  4067. TL.copy(NamedTL);
  4068. } else {
  4069. TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
  4070. assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
  4071. }
  4072. }
  4073. void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  4074. assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
  4075. TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
  4076. TL.setParensRange(DS.getTypeofParensRange());
  4077. }
  4078. void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  4079. assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
  4080. TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
  4081. TL.setParensRange(DS.getTypeofParensRange());
  4082. assert(DS.getRepAsType());
  4083. TypeSourceInfo *TInfo = nullptr;
  4084. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4085. TL.setUnderlyingTInfo(TInfo);
  4086. }
  4087. void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  4088. // FIXME: This holds only because we only have one unary transform.
  4089. assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
  4090. TL.setKWLoc(DS.getTypeSpecTypeLoc());
  4091. TL.setParensRange(DS.getTypeofParensRange());
  4092. assert(DS.getRepAsType());
  4093. TypeSourceInfo *TInfo = nullptr;
  4094. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4095. TL.setUnderlyingTInfo(TInfo);
  4096. }
  4097. void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  4098. // By default, use the source location of the type specifier.
  4099. TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
  4100. if (TL.needsExtraLocalData()) {
  4101. // Set info for the written builtin specifiers.
  4102. TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
  4103. // Try to have a meaningful source location.
  4104. if (TL.getWrittenSignSpec() != TSS_unspecified)
  4105. // Sign spec loc overrides the others (e.g., 'unsigned long').
  4106. TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
  4107. else if (TL.getWrittenWidthSpec() != TSW_unspecified)
  4108. // Width spec loc overrides type spec loc (e.g., 'short int').
  4109. TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
  4110. }
  4111. }
  4112. void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  4113. ElaboratedTypeKeyword Keyword
  4114. = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
  4115. if (DS.getTypeSpecType() == TST_typename) {
  4116. TypeSourceInfo *TInfo = nullptr;
  4117. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4118. if (TInfo) {
  4119. TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
  4120. return;
  4121. }
  4122. }
  4123. TL.setElaboratedKeywordLoc(Keyword != ETK_None
  4124. ? DS.getTypeSpecTypeLoc()
  4125. : SourceLocation());
  4126. const CXXScopeSpec& SS = DS.getTypeSpecScope();
  4127. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  4128. Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
  4129. }
  4130. void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  4131. assert(DS.getTypeSpecType() == TST_typename);
  4132. TypeSourceInfo *TInfo = nullptr;
  4133. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4134. assert(TInfo);
  4135. TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
  4136. }
  4137. void VisitDependentTemplateSpecializationTypeLoc(
  4138. DependentTemplateSpecializationTypeLoc TL) {
  4139. assert(DS.getTypeSpecType() == TST_typename);
  4140. TypeSourceInfo *TInfo = nullptr;
  4141. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4142. assert(TInfo);
  4143. TL.copy(
  4144. TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
  4145. }
  4146. void VisitTagTypeLoc(TagTypeLoc TL) {
  4147. TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
  4148. }
  4149. void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  4150. // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
  4151. // or an _Atomic qualifier.
  4152. if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
  4153. TL.setKWLoc(DS.getTypeSpecTypeLoc());
  4154. TL.setParensRange(DS.getTypeofParensRange());
  4155. TypeSourceInfo *TInfo = nullptr;
  4156. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4157. assert(TInfo);
  4158. TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
  4159. } else {
  4160. TL.setKWLoc(DS.getAtomicSpecLoc());
  4161. // No parens, to indicate this was spelled as an _Atomic qualifier.
  4162. TL.setParensRange(SourceRange());
  4163. Visit(TL.getValueLoc());
  4164. }
  4165. }
  4166. void VisitPipeTypeLoc(PipeTypeLoc TL) {
  4167. TL.setKWLoc(DS.getTypeSpecTypeLoc());
  4168. TypeSourceInfo *TInfo = 0;
  4169. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4170. TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
  4171. }
  4172. void VisitTypeLoc(TypeLoc TL) {
  4173. // FIXME: add other typespec types and change this to an assert.
  4174. TL.initialize(Context, DS.getTypeSpecTypeLoc());
  4175. }
  4176. };
  4177. class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
  4178. ASTContext &Context;
  4179. const DeclaratorChunk &Chunk;
  4180. public:
  4181. DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
  4182. : Context(Context), Chunk(Chunk) {}
  4183. void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  4184. llvm_unreachable("qualified type locs not expected here!");
  4185. }
  4186. void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
  4187. llvm_unreachable("decayed type locs not expected here!");
  4188. }
  4189. void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  4190. fillAttributedTypeLoc(TL, Chunk.getAttrs());
  4191. }
  4192. void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
  4193. // nothing
  4194. }
  4195. void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  4196. assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
  4197. TL.setCaretLoc(Chunk.Loc);
  4198. }
  4199. void VisitPointerTypeLoc(PointerTypeLoc TL) {
  4200. assert(Chunk.Kind == DeclaratorChunk::Pointer);
  4201. TL.setStarLoc(Chunk.Loc);
  4202. }
  4203. void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  4204. assert(Chunk.Kind == DeclaratorChunk::Pointer);
  4205. TL.setStarLoc(Chunk.Loc);
  4206. }
  4207. void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  4208. assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
  4209. const CXXScopeSpec& SS = Chunk.Mem.Scope();
  4210. NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
  4211. const Type* ClsTy = TL.getClass();
  4212. QualType ClsQT = QualType(ClsTy, 0);
  4213. TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
  4214. // Now copy source location info into the type loc component.
  4215. TypeLoc ClsTL = ClsTInfo->getTypeLoc();
  4216. switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
  4217. case NestedNameSpecifier::Identifier:
  4218. assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
  4219. {
  4220. DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
  4221. DNTLoc.setElaboratedKeywordLoc(SourceLocation());
  4222. DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
  4223. DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
  4224. }
  4225. break;
  4226. case NestedNameSpecifier::TypeSpec:
  4227. case NestedNameSpecifier::TypeSpecWithTemplate:
  4228. if (isa<ElaboratedType>(ClsTy)) {
  4229. ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
  4230. ETLoc.setElaboratedKeywordLoc(SourceLocation());
  4231. ETLoc.setQualifierLoc(NNSLoc.getPrefix());
  4232. TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
  4233. NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
  4234. } else {
  4235. ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
  4236. }
  4237. break;
  4238. case NestedNameSpecifier::Namespace:
  4239. case NestedNameSpecifier::NamespaceAlias:
  4240. case NestedNameSpecifier::Global:
  4241. case NestedNameSpecifier::Super:
  4242. llvm_unreachable("Nested-name-specifier must name a type");
  4243. }
  4244. // Finally fill in MemberPointerLocInfo fields.
  4245. TL.setStarLoc(Chunk.Loc);
  4246. TL.setClassTInfo(ClsTInfo);
  4247. }
  4248. void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  4249. assert(Chunk.Kind == DeclaratorChunk::Reference);
  4250. // 'Amp' is misleading: this might have been originally
  4251. /// spelled with AmpAmp.
  4252. TL.setAmpLoc(Chunk.Loc);
  4253. }
  4254. void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  4255. assert(Chunk.Kind == DeclaratorChunk::Reference);
  4256. assert(!Chunk.Ref.LValueRef);
  4257. TL.setAmpAmpLoc(Chunk.Loc);
  4258. }
  4259. void VisitArrayTypeLoc(ArrayTypeLoc TL) {
  4260. assert(Chunk.Kind == DeclaratorChunk::Array);
  4261. TL.setLBracketLoc(Chunk.Loc);
  4262. TL.setRBracketLoc(Chunk.EndLoc);
  4263. TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
  4264. }
  4265. void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  4266. assert(Chunk.Kind == DeclaratorChunk::Function);
  4267. TL.setLocalRangeBegin(Chunk.Loc);
  4268. TL.setLocalRangeEnd(Chunk.EndLoc);
  4269. const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
  4270. TL.setLParenLoc(FTI.getLParenLoc());
  4271. TL.setRParenLoc(FTI.getRParenLoc());
  4272. for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
  4273. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  4274. TL.setParam(tpi++, Param);
  4275. }
  4276. // FIXME: exception specs
  4277. }
  4278. void VisitParenTypeLoc(ParenTypeLoc TL) {
  4279. assert(Chunk.Kind == DeclaratorChunk::Paren);
  4280. TL.setLParenLoc(Chunk.Loc);
  4281. TL.setRParenLoc(Chunk.EndLoc);
  4282. }
  4283. void VisitPipeTypeLoc(PipeTypeLoc TL) {
  4284. assert(Chunk.Kind == DeclaratorChunk::Pipe);
  4285. TL.setKWLoc(Chunk.Loc);
  4286. }
  4287. void VisitTypeLoc(TypeLoc TL) {
  4288. llvm_unreachable("unsupported TypeLoc kind in declarator!");
  4289. }
  4290. };
  4291. }
  4292. static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
  4293. SourceLocation Loc;
  4294. switch (Chunk.Kind) {
  4295. case DeclaratorChunk::Function:
  4296. case DeclaratorChunk::Array:
  4297. case DeclaratorChunk::Paren:
  4298. case DeclaratorChunk::Pipe:
  4299. llvm_unreachable("cannot be _Atomic qualified");
  4300. case DeclaratorChunk::Pointer:
  4301. Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
  4302. break;
  4303. case DeclaratorChunk::BlockPointer:
  4304. case DeclaratorChunk::Reference:
  4305. case DeclaratorChunk::MemberPointer:
  4306. // FIXME: Provide a source location for the _Atomic keyword.
  4307. break;
  4308. }
  4309. ATL.setKWLoc(Loc);
  4310. ATL.setParensRange(SourceRange());
  4311. }
  4312. /// \brief Create and instantiate a TypeSourceInfo with type source information.
  4313. ///
  4314. /// \param T QualType referring to the type as written in source code.
  4315. ///
  4316. /// \param ReturnTypeInfo For declarators whose return type does not show
  4317. /// up in the normal place in the declaration specifiers (such as a C++
  4318. /// conversion function), this pointer will refer to a type source information
  4319. /// for that return type.
  4320. TypeSourceInfo *
  4321. Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
  4322. TypeSourceInfo *ReturnTypeInfo) {
  4323. TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
  4324. UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
  4325. const AttributeList *DeclAttrs = D.getAttributes();
  4326. // Handle parameter packs whose type is a pack expansion.
  4327. if (isa<PackExpansionType>(T)) {
  4328. CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
  4329. CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
  4330. }
  4331. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  4332. // An AtomicTypeLoc might be produced by an atomic qualifier in this
  4333. // declarator chunk.
  4334. if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
  4335. fillAtomicQualLoc(ATL, D.getTypeObject(i));
  4336. CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
  4337. }
  4338. while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
  4339. fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
  4340. CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
  4341. }
  4342. // FIXME: Ordering here?
  4343. while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
  4344. CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
  4345. DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
  4346. CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
  4347. }
  4348. // If we have different source information for the return type, use
  4349. // that. This really only applies to C++ conversion functions.
  4350. if (ReturnTypeInfo) {
  4351. TypeLoc TL = ReturnTypeInfo->getTypeLoc();
  4352. assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
  4353. memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
  4354. } else {
  4355. TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
  4356. }
  4357. return TInfo;
  4358. }
  4359. /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
  4360. ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
  4361. // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
  4362. // and Sema during declaration parsing. Try deallocating/caching them when
  4363. // it's appropriate, instead of allocating them and keeping them around.
  4364. LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
  4365. TypeAlignment);
  4366. new (LocT) LocInfoType(T, TInfo);
  4367. assert(LocT->getTypeClass() != T->getTypeClass() &&
  4368. "LocInfoType's TypeClass conflicts with an existing Type class");
  4369. return ParsedType::make(QualType(LocT, 0));
  4370. }
  4371. void LocInfoType::getAsStringInternal(std::string &Str,
  4372. const PrintingPolicy &Policy) const {
  4373. llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
  4374. " was used directly instead of getting the QualType through"
  4375. " GetTypeFromParser");
  4376. }
  4377. TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
  4378. // C99 6.7.6: Type names have no identifier. This is already validated by
  4379. // the parser.
  4380. assert(D.getIdentifier() == nullptr &&
  4381. "Type name should have no identifier!");
  4382. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4383. QualType T = TInfo->getType();
  4384. if (D.isInvalidType())
  4385. return true;
  4386. // Make sure there are no unused decl attributes on the declarator.
  4387. // We don't want to do this for ObjC parameters because we're going
  4388. // to apply them to the actual parameter declaration.
  4389. // Likewise, we don't want to do this for alias declarations, because
  4390. // we are actually going to build a declaration from this eventually.
  4391. if (D.getContext() != Declarator::ObjCParameterContext &&
  4392. D.getContext() != Declarator::AliasDeclContext &&
  4393. D.getContext() != Declarator::AliasTemplateContext)
  4394. checkUnusedDeclAttributes(D);
  4395. if (getLangOpts().CPlusPlus) {
  4396. // Check that there are no default arguments (C++ only).
  4397. CheckExtraCXXDefaultArguments(D);
  4398. }
  4399. return CreateParsedType(T, TInfo);
  4400. }
  4401. ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
  4402. QualType T = Context.getObjCInstanceType();
  4403. TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  4404. return CreateParsedType(T, TInfo);
  4405. }
  4406. //===----------------------------------------------------------------------===//
  4407. // Type Attribute Processing
  4408. //===----------------------------------------------------------------------===//
  4409. /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
  4410. /// specified type. The attribute contains 1 argument, the id of the address
  4411. /// space for the type.
  4412. static void HandleAddressSpaceTypeAttribute(QualType &Type,
  4413. const AttributeList &Attr, Sema &S){
  4414. // If this type is already address space qualified, reject it.
  4415. // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
  4416. // qualifiers for two or more different address spaces."
  4417. if (Type.getAddressSpace()) {
  4418. S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
  4419. Attr.setInvalid();
  4420. return;
  4421. }
  4422. // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
  4423. // qualified by an address-space qualifier."
  4424. if (Type->isFunctionType()) {
  4425. S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
  4426. Attr.setInvalid();
  4427. return;
  4428. }
  4429. unsigned ASIdx;
  4430. if (Attr.getKind() == AttributeList::AT_AddressSpace) {
  4431. // Check the attribute arguments.
  4432. if (Attr.getNumArgs() != 1) {
  4433. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
  4434. << Attr.getName() << 1;
  4435. Attr.setInvalid();
  4436. return;
  4437. }
  4438. Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
  4439. llvm::APSInt addrSpace(32);
  4440. if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
  4441. !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
  4442. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  4443. << Attr.getName() << AANT_ArgumentIntegerConstant
  4444. << ASArgExpr->getSourceRange();
  4445. Attr.setInvalid();
  4446. return;
  4447. }
  4448. // Bounds checking.
  4449. if (addrSpace.isSigned()) {
  4450. if (addrSpace.isNegative()) {
  4451. S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
  4452. << ASArgExpr->getSourceRange();
  4453. Attr.setInvalid();
  4454. return;
  4455. }
  4456. addrSpace.setIsSigned(false);
  4457. }
  4458. llvm::APSInt max(addrSpace.getBitWidth());
  4459. max = Qualifiers::MaxAddressSpace;
  4460. if (addrSpace > max) {
  4461. S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
  4462. << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
  4463. Attr.setInvalid();
  4464. return;
  4465. }
  4466. ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
  4467. } else {
  4468. // The keyword-based type attributes imply which address space to use.
  4469. switch (Attr.getKind()) {
  4470. case AttributeList::AT_OpenCLGlobalAddressSpace:
  4471. ASIdx = LangAS::opencl_global; break;
  4472. case AttributeList::AT_OpenCLLocalAddressSpace:
  4473. ASIdx = LangAS::opencl_local; break;
  4474. case AttributeList::AT_OpenCLConstantAddressSpace:
  4475. ASIdx = LangAS::opencl_constant; break;
  4476. case AttributeList::AT_OpenCLGenericAddressSpace:
  4477. ASIdx = LangAS::opencl_generic; break;
  4478. default:
  4479. assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
  4480. ASIdx = 0; break;
  4481. }
  4482. }
  4483. Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
  4484. }
  4485. /// Does this type have a "direct" ownership qualifier? That is,
  4486. /// is it written like "__strong id", as opposed to something like
  4487. /// "typeof(foo)", where that happens to be strong?
  4488. static bool hasDirectOwnershipQualifier(QualType type) {
  4489. // Fast path: no qualifier at all.
  4490. assert(type.getQualifiers().hasObjCLifetime());
  4491. while (true) {
  4492. // __strong id
  4493. if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
  4494. if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
  4495. return true;
  4496. type = attr->getModifiedType();
  4497. // X *__strong (...)
  4498. } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
  4499. type = paren->getInnerType();
  4500. // That's it for things we want to complain about. In particular,
  4501. // we do not want to look through typedefs, typeof(expr),
  4502. // typeof(type), or any other way that the type is somehow
  4503. // abstracted.
  4504. } else {
  4505. return false;
  4506. }
  4507. }
  4508. }
  4509. /// handleObjCOwnershipTypeAttr - Process an objc_ownership
  4510. /// attribute on the specified type.
  4511. ///
  4512. /// Returns 'true' if the attribute was handled.
  4513. static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
  4514. AttributeList &attr,
  4515. QualType &type) {
  4516. bool NonObjCPointer = false;
  4517. if (!type->isDependentType() && !type->isUndeducedType()) {
  4518. if (const PointerType *ptr = type->getAs<PointerType>()) {
  4519. QualType pointee = ptr->getPointeeType();
  4520. if (pointee->isObjCRetainableType() || pointee->isPointerType())
  4521. return false;
  4522. // It is important not to lose the source info that there was an attribute
  4523. // applied to non-objc pointer. We will create an attributed type but
  4524. // its type will be the same as the original type.
  4525. NonObjCPointer = true;
  4526. } else if (!type->isObjCRetainableType()) {
  4527. return false;
  4528. }
  4529. // Don't accept an ownership attribute in the declspec if it would
  4530. // just be the return type of a block pointer.
  4531. if (state.isProcessingDeclSpec()) {
  4532. Declarator &D = state.getDeclarator();
  4533. if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
  4534. /*onlyBlockPointers=*/true))
  4535. return false;
  4536. }
  4537. }
  4538. Sema &S = state.getSema();
  4539. SourceLocation AttrLoc = attr.getLoc();
  4540. if (AttrLoc.isMacroID())
  4541. AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
  4542. if (!attr.isArgIdent(0)) {
  4543. S.Diag(AttrLoc, diag::err_attribute_argument_type)
  4544. << attr.getName() << AANT_ArgumentString;
  4545. attr.setInvalid();
  4546. return true;
  4547. }
  4548. IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
  4549. Qualifiers::ObjCLifetime lifetime;
  4550. if (II->isStr("none"))
  4551. lifetime = Qualifiers::OCL_ExplicitNone;
  4552. else if (II->isStr("strong"))
  4553. lifetime = Qualifiers::OCL_Strong;
  4554. else if (II->isStr("weak"))
  4555. lifetime = Qualifiers::OCL_Weak;
  4556. else if (II->isStr("autoreleasing"))
  4557. lifetime = Qualifiers::OCL_Autoreleasing;
  4558. else {
  4559. S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
  4560. << attr.getName() << II;
  4561. attr.setInvalid();
  4562. return true;
  4563. }
  4564. // Just ignore lifetime attributes other than __weak and __unsafe_unretained
  4565. // outside of ARC mode.
  4566. if (!S.getLangOpts().ObjCAutoRefCount &&
  4567. lifetime != Qualifiers::OCL_Weak &&
  4568. lifetime != Qualifiers::OCL_ExplicitNone) {
  4569. return true;
  4570. }
  4571. SplitQualType underlyingType = type.split();
  4572. // Check for redundant/conflicting ownership qualifiers.
  4573. if (Qualifiers::ObjCLifetime previousLifetime
  4574. = type.getQualifiers().getObjCLifetime()) {
  4575. // If it's written directly, that's an error.
  4576. if (hasDirectOwnershipQualifier(type)) {
  4577. S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
  4578. << type;
  4579. return true;
  4580. }
  4581. // Otherwise, if the qualifiers actually conflict, pull sugar off
  4582. // until we reach a type that is directly qualified.
  4583. if (previousLifetime != lifetime) {
  4584. // This should always terminate: the canonical type is
  4585. // qualified, so some bit of sugar must be hiding it.
  4586. while (!underlyingType.Quals.hasObjCLifetime()) {
  4587. underlyingType = underlyingType.getSingleStepDesugaredType();
  4588. }
  4589. underlyingType.Quals.removeObjCLifetime();
  4590. }
  4591. }
  4592. underlyingType.Quals.addObjCLifetime(lifetime);
  4593. if (NonObjCPointer) {
  4594. StringRef name = attr.getName()->getName();
  4595. switch (lifetime) {
  4596. case Qualifiers::OCL_None:
  4597. case Qualifiers::OCL_ExplicitNone:
  4598. break;
  4599. case Qualifiers::OCL_Strong: name = "__strong"; break;
  4600. case Qualifiers::OCL_Weak: name = "__weak"; break;
  4601. case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
  4602. }
  4603. S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
  4604. << TDS_ObjCObjOrBlock << type;
  4605. }
  4606. // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
  4607. // because having both 'T' and '__unsafe_unretained T' exist in the type
  4608. // system causes unfortunate widespread consistency problems. (For example,
  4609. // they're not considered compatible types, and we mangle them identicially
  4610. // as template arguments.) These problems are all individually fixable,
  4611. // but it's easier to just not add the qualifier and instead sniff it out
  4612. // in specific places using isObjCInertUnsafeUnretainedType().
  4613. //
  4614. // Doing this does means we miss some trivial consistency checks that
  4615. // would've triggered in ARC, but that's better than trying to solve all
  4616. // the coexistence problems with __unsafe_unretained.
  4617. if (!S.getLangOpts().ObjCAutoRefCount &&
  4618. lifetime == Qualifiers::OCL_ExplicitNone) {
  4619. type = S.Context.getAttributedType(
  4620. AttributedType::attr_objc_inert_unsafe_unretained,
  4621. type, type);
  4622. return true;
  4623. }
  4624. QualType origType = type;
  4625. if (!NonObjCPointer)
  4626. type = S.Context.getQualifiedType(underlyingType);
  4627. // If we have a valid source location for the attribute, use an
  4628. // AttributedType instead.
  4629. if (AttrLoc.isValid())
  4630. type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
  4631. origType, type);
  4632. auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
  4633. unsigned diagnostic, QualType type) {
  4634. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
  4635. S.DelayedDiagnostics.add(
  4636. sema::DelayedDiagnostic::makeForbiddenType(
  4637. S.getSourceManager().getExpansionLoc(loc),
  4638. diagnostic, type, /*ignored*/ 0));
  4639. } else {
  4640. S.Diag(loc, diagnostic);
  4641. }
  4642. };
  4643. // Sometimes, __weak isn't allowed.
  4644. if (lifetime == Qualifiers::OCL_Weak &&
  4645. !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
  4646. // Use a specialized diagnostic if the runtime just doesn't support them.
  4647. unsigned diagnostic =
  4648. (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
  4649. : diag::err_arc_weak_no_runtime);
  4650. // In any case, delay the diagnostic until we know what we're parsing.
  4651. diagnoseOrDelay(S, AttrLoc, diagnostic, type);
  4652. attr.setInvalid();
  4653. return true;
  4654. }
  4655. // Forbid __weak for class objects marked as
  4656. // objc_arc_weak_reference_unavailable
  4657. if (lifetime == Qualifiers::OCL_Weak) {
  4658. if (const ObjCObjectPointerType *ObjT =
  4659. type->getAs<ObjCObjectPointerType>()) {
  4660. if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
  4661. if (Class->isArcWeakrefUnavailable()) {
  4662. S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
  4663. S.Diag(ObjT->getInterfaceDecl()->getLocation(),
  4664. diag::note_class_declared);
  4665. }
  4666. }
  4667. }
  4668. }
  4669. return true;
  4670. }
  4671. /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
  4672. /// attribute on the specified type. Returns true to indicate that
  4673. /// the attribute was handled, false to indicate that the type does
  4674. /// not permit the attribute.
  4675. static bool handleObjCGCTypeAttr(TypeProcessingState &state,
  4676. AttributeList &attr,
  4677. QualType &type) {
  4678. Sema &S = state.getSema();
  4679. // Delay if this isn't some kind of pointer.
  4680. if (!type->isPointerType() &&
  4681. !type->isObjCObjectPointerType() &&
  4682. !type->isBlockPointerType())
  4683. return false;
  4684. if (type.getObjCGCAttr() != Qualifiers::GCNone) {
  4685. S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
  4686. attr.setInvalid();
  4687. return true;
  4688. }
  4689. // Check the attribute arguments.
  4690. if (!attr.isArgIdent(0)) {
  4691. S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
  4692. << attr.getName() << AANT_ArgumentString;
  4693. attr.setInvalid();
  4694. return true;
  4695. }
  4696. Qualifiers::GC GCAttr;
  4697. if (attr.getNumArgs() > 1) {
  4698. S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
  4699. << attr.getName() << 1;
  4700. attr.setInvalid();
  4701. return true;
  4702. }
  4703. IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
  4704. if (II->isStr("weak"))
  4705. GCAttr = Qualifiers::Weak;
  4706. else if (II->isStr("strong"))
  4707. GCAttr = Qualifiers::Strong;
  4708. else {
  4709. S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
  4710. << attr.getName() << II;
  4711. attr.setInvalid();
  4712. return true;
  4713. }
  4714. QualType origType = type;
  4715. type = S.Context.getObjCGCQualType(origType, GCAttr);
  4716. // Make an attributed type to preserve the source information.
  4717. if (attr.getLoc().isValid())
  4718. type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
  4719. origType, type);
  4720. return true;
  4721. }
  4722. namespace {
  4723. /// A helper class to unwrap a type down to a function for the
  4724. /// purposes of applying attributes there.
  4725. ///
  4726. /// Use:
  4727. /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
  4728. /// if (unwrapped.isFunctionType()) {
  4729. /// const FunctionType *fn = unwrapped.get();
  4730. /// // change fn somehow
  4731. /// T = unwrapped.wrap(fn);
  4732. /// }
  4733. struct FunctionTypeUnwrapper {
  4734. enum WrapKind {
  4735. Desugar,
  4736. Parens,
  4737. Pointer,
  4738. BlockPointer,
  4739. Reference,
  4740. MemberPointer
  4741. };
  4742. QualType Original;
  4743. const FunctionType *Fn;
  4744. SmallVector<unsigned char /*WrapKind*/, 8> Stack;
  4745. FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
  4746. while (true) {
  4747. const Type *Ty = T.getTypePtr();
  4748. if (isa<FunctionType>(Ty)) {
  4749. Fn = cast<FunctionType>(Ty);
  4750. return;
  4751. } else if (isa<ParenType>(Ty)) {
  4752. T = cast<ParenType>(Ty)->getInnerType();
  4753. Stack.push_back(Parens);
  4754. } else if (isa<PointerType>(Ty)) {
  4755. T = cast<PointerType>(Ty)->getPointeeType();
  4756. Stack.push_back(Pointer);
  4757. } else if (isa<BlockPointerType>(Ty)) {
  4758. T = cast<BlockPointerType>(Ty)->getPointeeType();
  4759. Stack.push_back(BlockPointer);
  4760. } else if (isa<MemberPointerType>(Ty)) {
  4761. T = cast<MemberPointerType>(Ty)->getPointeeType();
  4762. Stack.push_back(MemberPointer);
  4763. } else if (isa<ReferenceType>(Ty)) {
  4764. T = cast<ReferenceType>(Ty)->getPointeeType();
  4765. Stack.push_back(Reference);
  4766. } else {
  4767. const Type *DTy = Ty->getUnqualifiedDesugaredType();
  4768. if (Ty == DTy) {
  4769. Fn = nullptr;
  4770. return;
  4771. }
  4772. T = QualType(DTy, 0);
  4773. Stack.push_back(Desugar);
  4774. }
  4775. }
  4776. }
  4777. bool isFunctionType() const { return (Fn != nullptr); }
  4778. const FunctionType *get() const { return Fn; }
  4779. QualType wrap(Sema &S, const FunctionType *New) {
  4780. // If T wasn't modified from the unwrapped type, do nothing.
  4781. if (New == get()) return Original;
  4782. Fn = New;
  4783. return wrap(S.Context, Original, 0);
  4784. }
  4785. private:
  4786. QualType wrap(ASTContext &C, QualType Old, unsigned I) {
  4787. if (I == Stack.size())
  4788. return C.getQualifiedType(Fn, Old.getQualifiers());
  4789. // Build up the inner type, applying the qualifiers from the old
  4790. // type to the new type.
  4791. SplitQualType SplitOld = Old.split();
  4792. // As a special case, tail-recurse if there are no qualifiers.
  4793. if (SplitOld.Quals.empty())
  4794. return wrap(C, SplitOld.Ty, I);
  4795. return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
  4796. }
  4797. QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
  4798. if (I == Stack.size()) return QualType(Fn, 0);
  4799. switch (static_cast<WrapKind>(Stack[I++])) {
  4800. case Desugar:
  4801. // This is the point at which we potentially lose source
  4802. // information.
  4803. return wrap(C, Old->getUnqualifiedDesugaredType(), I);
  4804. case Parens: {
  4805. QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
  4806. return C.getParenType(New);
  4807. }
  4808. case Pointer: {
  4809. QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
  4810. return C.getPointerType(New);
  4811. }
  4812. case BlockPointer: {
  4813. QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
  4814. return C.getBlockPointerType(New);
  4815. }
  4816. case MemberPointer: {
  4817. const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
  4818. QualType New = wrap(C, OldMPT->getPointeeType(), I);
  4819. return C.getMemberPointerType(New, OldMPT->getClass());
  4820. }
  4821. case Reference: {
  4822. const ReferenceType *OldRef = cast<ReferenceType>(Old);
  4823. QualType New = wrap(C, OldRef->getPointeeType(), I);
  4824. if (isa<LValueReferenceType>(OldRef))
  4825. return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
  4826. else
  4827. return C.getRValueReferenceType(New);
  4828. }
  4829. }
  4830. llvm_unreachable("unknown wrapping kind");
  4831. }
  4832. };
  4833. }
  4834. static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
  4835. AttributeList &Attr,
  4836. QualType &Type) {
  4837. Sema &S = State.getSema();
  4838. AttributeList::Kind Kind = Attr.getKind();
  4839. QualType Desugared = Type;
  4840. const AttributedType *AT = dyn_cast<AttributedType>(Type);
  4841. while (AT) {
  4842. AttributedType::Kind CurAttrKind = AT->getAttrKind();
  4843. // You cannot specify duplicate type attributes, so if the attribute has
  4844. // already been applied, flag it.
  4845. if (getAttrListKind(CurAttrKind) == Kind) {
  4846. S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
  4847. << Attr.getName();
  4848. return true;
  4849. }
  4850. // You cannot have both __sptr and __uptr on the same type, nor can you
  4851. // have __ptr32 and __ptr64.
  4852. if ((CurAttrKind == AttributedType::attr_ptr32 &&
  4853. Kind == AttributeList::AT_Ptr64) ||
  4854. (CurAttrKind == AttributedType::attr_ptr64 &&
  4855. Kind == AttributeList::AT_Ptr32)) {
  4856. S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
  4857. << "'__ptr32'" << "'__ptr64'";
  4858. return true;
  4859. } else if ((CurAttrKind == AttributedType::attr_sptr &&
  4860. Kind == AttributeList::AT_UPtr) ||
  4861. (CurAttrKind == AttributedType::attr_uptr &&
  4862. Kind == AttributeList::AT_SPtr)) {
  4863. S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
  4864. << "'__sptr'" << "'__uptr'";
  4865. return true;
  4866. }
  4867. Desugared = AT->getEquivalentType();
  4868. AT = dyn_cast<AttributedType>(Desugared);
  4869. }
  4870. // Pointer type qualifiers can only operate on pointer types, but not
  4871. // pointer-to-member types.
  4872. if (!isa<PointerType>(Desugared)) {
  4873. if (Type->isMemberPointerType())
  4874. S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers)
  4875. << Attr.getName();
  4876. else
  4877. S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
  4878. << Attr.getName() << 0;
  4879. return true;
  4880. }
  4881. AttributedType::Kind TAK;
  4882. switch (Kind) {
  4883. default: llvm_unreachable("Unknown attribute kind");
  4884. case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
  4885. case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
  4886. case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
  4887. case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
  4888. }
  4889. Type = S.Context.getAttributedType(TAK, Type, Type);
  4890. return false;
  4891. }
  4892. bool Sema::checkNullabilityTypeSpecifier(QualType &type,
  4893. NullabilityKind nullability,
  4894. SourceLocation nullabilityLoc,
  4895. bool isContextSensitive) {
  4896. // We saw a nullability type specifier. If this is the first one for
  4897. // this file, note that.
  4898. FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc);
  4899. if (!file.isInvalid()) {
  4900. FileNullability &fileNullability = NullabilityMap[file];
  4901. if (!fileNullability.SawTypeNullability) {
  4902. // If we have already seen a pointer declarator without a nullability
  4903. // annotation, complain about it.
  4904. if (fileNullability.PointerLoc.isValid()) {
  4905. Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
  4906. << static_cast<unsigned>(fileNullability.PointerKind);
  4907. }
  4908. fileNullability.SawTypeNullability = true;
  4909. }
  4910. }
  4911. // Check for existing nullability attributes on the type.
  4912. QualType desugared = type;
  4913. while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
  4914. // Check whether there is already a null
  4915. if (auto existingNullability = attributed->getImmediateNullability()) {
  4916. // Duplicated nullability.
  4917. if (nullability == *existingNullability) {
  4918. Diag(nullabilityLoc, diag::warn_nullability_duplicate)
  4919. << DiagNullabilityKind(nullability, isContextSensitive)
  4920. << FixItHint::CreateRemoval(nullabilityLoc);
  4921. break;
  4922. }
  4923. // Conflicting nullability.
  4924. Diag(nullabilityLoc, diag::err_nullability_conflicting)
  4925. << DiagNullabilityKind(nullability, isContextSensitive)
  4926. << DiagNullabilityKind(*existingNullability, false);
  4927. return true;
  4928. }
  4929. desugared = attributed->getModifiedType();
  4930. }
  4931. // If there is already a different nullability specifier, complain.
  4932. // This (unlike the code above) looks through typedefs that might
  4933. // have nullability specifiers on them, which means we cannot
  4934. // provide a useful Fix-It.
  4935. if (auto existingNullability = desugared->getNullability(Context)) {
  4936. if (nullability != *existingNullability) {
  4937. Diag(nullabilityLoc, diag::err_nullability_conflicting)
  4938. << DiagNullabilityKind(nullability, isContextSensitive)
  4939. << DiagNullabilityKind(*existingNullability, false);
  4940. // Try to find the typedef with the existing nullability specifier.
  4941. if (auto typedefType = desugared->getAs<TypedefType>()) {
  4942. TypedefNameDecl *typedefDecl = typedefType->getDecl();
  4943. QualType underlyingType = typedefDecl->getUnderlyingType();
  4944. if (auto typedefNullability
  4945. = AttributedType::stripOuterNullability(underlyingType)) {
  4946. if (*typedefNullability == *existingNullability) {
  4947. Diag(typedefDecl->getLocation(), diag::note_nullability_here)
  4948. << DiagNullabilityKind(*existingNullability, false);
  4949. }
  4950. }
  4951. }
  4952. return true;
  4953. }
  4954. }
  4955. // If this definitely isn't a pointer type, reject the specifier.
  4956. if (!desugared->canHaveNullability()) {
  4957. Diag(nullabilityLoc, diag::err_nullability_nonpointer)
  4958. << DiagNullabilityKind(nullability, isContextSensitive) << type;
  4959. return true;
  4960. }
  4961. // For the context-sensitive keywords/Objective-C property
  4962. // attributes, require that the type be a single-level pointer.
  4963. if (isContextSensitive) {
  4964. // Make sure that the pointee isn't itself a pointer type.
  4965. QualType pointeeType = desugared->getPointeeType();
  4966. if (pointeeType->isAnyPointerType() ||
  4967. pointeeType->isObjCObjectPointerType() ||
  4968. pointeeType->isMemberPointerType()) {
  4969. Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
  4970. << DiagNullabilityKind(nullability, true)
  4971. << type;
  4972. Diag(nullabilityLoc, diag::note_nullability_type_specifier)
  4973. << DiagNullabilityKind(nullability, false)
  4974. << type
  4975. << FixItHint::CreateReplacement(nullabilityLoc,
  4976. getNullabilitySpelling(nullability));
  4977. return true;
  4978. }
  4979. }
  4980. // Form the attributed type.
  4981. type = Context.getAttributedType(
  4982. AttributedType::getNullabilityAttrKind(nullability), type, type);
  4983. return false;
  4984. }
  4985. bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
  4986. // Find out if it's an Objective-C object or object pointer type;
  4987. const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
  4988. const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
  4989. : type->getAs<ObjCObjectType>();
  4990. // If not, we can't apply __kindof.
  4991. if (!objType) {
  4992. // FIXME: Handle dependent types that aren't yet object types.
  4993. Diag(loc, diag::err_objc_kindof_nonobject)
  4994. << type;
  4995. return true;
  4996. }
  4997. // Rebuild the "equivalent" type, which pushes __kindof down into
  4998. // the object type.
  4999. QualType equivType = Context.getObjCObjectType(objType->getBaseType(),
  5000. objType->getTypeArgsAsWritten(),
  5001. objType->getProtocols(),
  5002. /*isKindOf=*/true);
  5003. // If we started with an object pointer type, rebuild it.
  5004. if (ptrType) {
  5005. equivType = Context.getObjCObjectPointerType(equivType);
  5006. if (auto nullability = type->getNullability(Context)) {
  5007. auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
  5008. equivType = Context.getAttributedType(attrKind, equivType, equivType);
  5009. }
  5010. }
  5011. // Build the attributed type to record where __kindof occurred.
  5012. type = Context.getAttributedType(AttributedType::attr_objc_kindof,
  5013. type,
  5014. equivType);
  5015. return false;
  5016. }
  5017. /// Map a nullability attribute kind to a nullability kind.
  5018. static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
  5019. switch (kind) {
  5020. case AttributeList::AT_TypeNonNull:
  5021. return NullabilityKind::NonNull;
  5022. case AttributeList::AT_TypeNullable:
  5023. return NullabilityKind::Nullable;
  5024. case AttributeList::AT_TypeNullUnspecified:
  5025. return NullabilityKind::Unspecified;
  5026. default:
  5027. llvm_unreachable("not a nullability attribute kind");
  5028. }
  5029. }
  5030. /// Distribute a nullability type attribute that cannot be applied to
  5031. /// the type specifier to a pointer, block pointer, or member pointer
  5032. /// declarator, complaining if necessary.
  5033. ///
  5034. /// \returns true if the nullability annotation was distributed, false
  5035. /// otherwise.
  5036. static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
  5037. QualType type,
  5038. AttributeList &attr) {
  5039. Declarator &declarator = state.getDeclarator();
  5040. /// Attempt to move the attribute to the specified chunk.
  5041. auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
  5042. // If there is already a nullability attribute there, don't add
  5043. // one.
  5044. if (hasNullabilityAttr(chunk.getAttrListRef()))
  5045. return false;
  5046. // Complain about the nullability qualifier being in the wrong
  5047. // place.
  5048. enum {
  5049. PK_Pointer,
  5050. PK_BlockPointer,
  5051. PK_MemberPointer,
  5052. PK_FunctionPointer,
  5053. PK_MemberFunctionPointer,
  5054. } pointerKind
  5055. = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
  5056. : PK_Pointer)
  5057. : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
  5058. : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
  5059. auto diag = state.getSema().Diag(attr.getLoc(),
  5060. diag::warn_nullability_declspec)
  5061. << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
  5062. attr.isContextSensitiveKeywordAttribute())
  5063. << type
  5064. << static_cast<unsigned>(pointerKind);
  5065. // FIXME: MemberPointer chunks don't carry the location of the *.
  5066. if (chunk.Kind != DeclaratorChunk::MemberPointer) {
  5067. diag << FixItHint::CreateRemoval(attr.getLoc())
  5068. << FixItHint::CreateInsertion(
  5069. state.getSema().getPreprocessor()
  5070. .getLocForEndOfToken(chunk.Loc),
  5071. " " + attr.getName()->getName().str() + " ");
  5072. }
  5073. moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
  5074. chunk.getAttrListRef());
  5075. return true;
  5076. };
  5077. // Move it to the outermost pointer, member pointer, or block
  5078. // pointer declarator.
  5079. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
  5080. DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
  5081. switch (chunk.Kind) {
  5082. case DeclaratorChunk::Pointer:
  5083. case DeclaratorChunk::BlockPointer:
  5084. case DeclaratorChunk::MemberPointer:
  5085. return moveToChunk(chunk, false);
  5086. case DeclaratorChunk::Paren:
  5087. case DeclaratorChunk::Array:
  5088. continue;
  5089. case DeclaratorChunk::Function:
  5090. // Try to move past the return type to a function/block/member
  5091. // function pointer.
  5092. if (DeclaratorChunk *dest = maybeMovePastReturnType(
  5093. declarator, i,
  5094. /*onlyBlockPointers=*/false)) {
  5095. return moveToChunk(*dest, true);
  5096. }
  5097. return false;
  5098. // Don't walk through these.
  5099. case DeclaratorChunk::Reference:
  5100. case DeclaratorChunk::Pipe:
  5101. return false;
  5102. }
  5103. }
  5104. return false;
  5105. }
  5106. static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
  5107. assert(!Attr.isInvalid());
  5108. switch (Attr.getKind()) {
  5109. default:
  5110. llvm_unreachable("not a calling convention attribute");
  5111. case AttributeList::AT_CDecl:
  5112. return AttributedType::attr_cdecl;
  5113. case AttributeList::AT_FastCall:
  5114. return AttributedType::attr_fastcall;
  5115. case AttributeList::AT_StdCall:
  5116. return AttributedType::attr_stdcall;
  5117. case AttributeList::AT_ThisCall:
  5118. return AttributedType::attr_thiscall;
  5119. case AttributeList::AT_Pascal:
  5120. return AttributedType::attr_pascal;
  5121. case AttributeList::AT_VectorCall:
  5122. return AttributedType::attr_vectorcall;
  5123. case AttributeList::AT_Pcs: {
  5124. // The attribute may have had a fixit applied where we treated an
  5125. // identifier as a string literal. The contents of the string are valid,
  5126. // but the form may not be.
  5127. StringRef Str;
  5128. if (Attr.isArgExpr(0))
  5129. Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
  5130. else
  5131. Str = Attr.getArgAsIdent(0)->Ident->getName();
  5132. return llvm::StringSwitch<AttributedType::Kind>(Str)
  5133. .Case("aapcs", AttributedType::attr_pcs)
  5134. .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
  5135. }
  5136. case AttributeList::AT_IntelOclBicc:
  5137. return AttributedType::attr_inteloclbicc;
  5138. case AttributeList::AT_MSABI:
  5139. return AttributedType::attr_ms_abi;
  5140. case AttributeList::AT_SysVABI:
  5141. return AttributedType::attr_sysv_abi;
  5142. }
  5143. llvm_unreachable("unexpected attribute kind!");
  5144. }
  5145. /// Process an individual function attribute. Returns true to
  5146. /// indicate that the attribute was handled, false if it wasn't.
  5147. static bool handleFunctionTypeAttr(TypeProcessingState &state,
  5148. AttributeList &attr,
  5149. QualType &type) {
  5150. Sema &S = state.getSema();
  5151. FunctionTypeUnwrapper unwrapped(S, type);
  5152. if (attr.getKind() == AttributeList::AT_NoReturn) {
  5153. if (S.CheckNoReturnAttr(attr))
  5154. return true;
  5155. // Delay if this is not a function type.
  5156. if (!unwrapped.isFunctionType())
  5157. return false;
  5158. // Otherwise we can process right away.
  5159. FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
  5160. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  5161. return true;
  5162. }
  5163. // ns_returns_retained is not always a type attribute, but if we got
  5164. // here, we're treating it as one right now.
  5165. if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
  5166. assert(S.getLangOpts().ObjCAutoRefCount &&
  5167. "ns_returns_retained treated as type attribute in non-ARC");
  5168. if (attr.getNumArgs()) return true;
  5169. // Delay if this is not a function type.
  5170. if (!unwrapped.isFunctionType())
  5171. return false;
  5172. FunctionType::ExtInfo EI
  5173. = unwrapped.get()->getExtInfo().withProducesResult(true);
  5174. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  5175. return true;
  5176. }
  5177. if (attr.getKind() == AttributeList::AT_Regparm) {
  5178. unsigned value;
  5179. if (S.CheckRegparmAttr(attr, value))
  5180. return true;
  5181. // Delay if this is not a function type.
  5182. if (!unwrapped.isFunctionType())
  5183. return false;
  5184. // Diagnose regparm with fastcall.
  5185. const FunctionType *fn = unwrapped.get();
  5186. CallingConv CC = fn->getCallConv();
  5187. if (CC == CC_X86FastCall) {
  5188. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  5189. << FunctionType::getNameForCallConv(CC)
  5190. << "regparm";
  5191. attr.setInvalid();
  5192. return true;
  5193. }
  5194. FunctionType::ExtInfo EI =
  5195. unwrapped.get()->getExtInfo().withRegParm(value);
  5196. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  5197. return true;
  5198. }
  5199. // Delay if the type didn't work out to a function.
  5200. if (!unwrapped.isFunctionType()) return false;
  5201. // Otherwise, a calling convention.
  5202. CallingConv CC;
  5203. if (S.CheckCallingConvAttr(attr, CC))
  5204. return true;
  5205. const FunctionType *fn = unwrapped.get();
  5206. CallingConv CCOld = fn->getCallConv();
  5207. AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
  5208. if (CCOld != CC) {
  5209. // Error out on when there's already an attribute on the type
  5210. // and the CCs don't match.
  5211. const AttributedType *AT = S.getCallingConvAttributedType(type);
  5212. if (AT && AT->getAttrKind() != CCAttrKind) {
  5213. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  5214. << FunctionType::getNameForCallConv(CC)
  5215. << FunctionType::getNameForCallConv(CCOld);
  5216. attr.setInvalid();
  5217. return true;
  5218. }
  5219. }
  5220. // Diagnose use of callee-cleanup calling convention on variadic functions.
  5221. if (!supportsVariadicCall(CC)) {
  5222. const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
  5223. if (FnP && FnP->isVariadic()) {
  5224. unsigned DiagID = diag::err_cconv_varargs;
  5225. // stdcall and fastcall are ignored with a warning for GCC and MS
  5226. // compatibility.
  5227. if (CC == CC_X86StdCall || CC == CC_X86FastCall)
  5228. DiagID = diag::warn_cconv_varargs;
  5229. S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
  5230. attr.setInvalid();
  5231. return true;
  5232. }
  5233. }
  5234. // Also diagnose fastcall with regparm.
  5235. if (CC == CC_X86FastCall && fn->getHasRegParm()) {
  5236. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  5237. << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
  5238. attr.setInvalid();
  5239. return true;
  5240. }
  5241. // Modify the CC from the wrapped function type, wrap it all back, and then
  5242. // wrap the whole thing in an AttributedType as written. The modified type
  5243. // might have a different CC if we ignored the attribute.
  5244. FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
  5245. QualType Equivalent =
  5246. unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  5247. type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
  5248. return true;
  5249. }
  5250. bool Sema::hasExplicitCallingConv(QualType &T) {
  5251. QualType R = T.IgnoreParens();
  5252. while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
  5253. if (AT->isCallingConv())
  5254. return true;
  5255. R = AT->getModifiedType().IgnoreParens();
  5256. }
  5257. return false;
  5258. }
  5259. void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
  5260. SourceLocation Loc) {
  5261. FunctionTypeUnwrapper Unwrapped(*this, T);
  5262. const FunctionType *FT = Unwrapped.get();
  5263. bool IsVariadic = (isa<FunctionProtoType>(FT) &&
  5264. cast<FunctionProtoType>(FT)->isVariadic());
  5265. CallingConv CurCC = FT->getCallConv();
  5266. CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
  5267. if (CurCC == ToCC)
  5268. return;
  5269. // MS compiler ignores explicit calling convention attributes on structors. We
  5270. // should do the same.
  5271. if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
  5272. // Issue a warning on ignored calling convention -- except of __stdcall.
  5273. // Again, this is what MS compiler does.
  5274. if (CurCC != CC_X86StdCall)
  5275. Diag(Loc, diag::warn_cconv_structors)
  5276. << FunctionType::getNameForCallConv(CurCC);
  5277. // Default adjustment.
  5278. } else {
  5279. // Only adjust types with the default convention. For example, on Windows
  5280. // we should adjust a __cdecl type to __thiscall for instance methods, and a
  5281. // __thiscall type to __cdecl for static methods.
  5282. CallingConv DefaultCC =
  5283. Context.getDefaultCallingConvention(IsVariadic, IsStatic);
  5284. if (CurCC != DefaultCC || DefaultCC == ToCC)
  5285. return;
  5286. if (hasExplicitCallingConv(T))
  5287. return;
  5288. }
  5289. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
  5290. QualType Wrapped = Unwrapped.wrap(*this, FT);
  5291. T = Context.getAdjustedType(T, Wrapped);
  5292. }
  5293. /// HandleVectorSizeAttribute - this attribute is only applicable to integral
  5294. /// and float scalars, although arrays, pointers, and function return values are
  5295. /// allowed in conjunction with this construct. Aggregates with this attribute
  5296. /// are invalid, even if they are of the same size as a corresponding scalar.
  5297. /// The raw attribute should contain precisely 1 argument, the vector size for
  5298. /// the variable, measured in bytes. If curType and rawAttr are well formed,
  5299. /// this routine will return a new vector type.
  5300. static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
  5301. Sema &S) {
  5302. // Check the attribute arguments.
  5303. if (Attr.getNumArgs() != 1) {
  5304. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
  5305. << Attr.getName() << 1;
  5306. Attr.setInvalid();
  5307. return;
  5308. }
  5309. Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
  5310. llvm::APSInt vecSize(32);
  5311. if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
  5312. !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
  5313. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  5314. << Attr.getName() << AANT_ArgumentIntegerConstant
  5315. << sizeExpr->getSourceRange();
  5316. Attr.setInvalid();
  5317. return;
  5318. }
  5319. // The base type must be integer (not Boolean or enumeration) or float, and
  5320. // can't already be a vector.
  5321. if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
  5322. (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
  5323. S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
  5324. Attr.setInvalid();
  5325. return;
  5326. }
  5327. unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
  5328. // vecSize is specified in bytes - convert to bits.
  5329. unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
  5330. // the vector size needs to be an integral multiple of the type size.
  5331. if (vectorSize % typeSize) {
  5332. S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
  5333. << sizeExpr->getSourceRange();
  5334. Attr.setInvalid();
  5335. return;
  5336. }
  5337. if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
  5338. S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
  5339. << sizeExpr->getSourceRange();
  5340. Attr.setInvalid();
  5341. return;
  5342. }
  5343. if (vectorSize == 0) {
  5344. S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
  5345. << sizeExpr->getSourceRange();
  5346. Attr.setInvalid();
  5347. return;
  5348. }
  5349. // Success! Instantiate the vector type, the number of elements is > 0, and
  5350. // not required to be a power of 2, unlike GCC.
  5351. CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
  5352. VectorType::GenericVector);
  5353. }
  5354. /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
  5355. /// a type.
  5356. static void HandleExtVectorTypeAttr(QualType &CurType,
  5357. const AttributeList &Attr,
  5358. Sema &S) {
  5359. // check the attribute arguments.
  5360. if (Attr.getNumArgs() != 1) {
  5361. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
  5362. << Attr.getName() << 1;
  5363. return;
  5364. }
  5365. Expr *sizeExpr;
  5366. // Special case where the argument is a template id.
  5367. if (Attr.isArgIdent(0)) {
  5368. CXXScopeSpec SS;
  5369. SourceLocation TemplateKWLoc;
  5370. UnqualifiedId id;
  5371. id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
  5372. ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
  5373. id, false, false);
  5374. if (Size.isInvalid())
  5375. return;
  5376. sizeExpr = Size.get();
  5377. } else {
  5378. sizeExpr = Attr.getArgAsExpr(0);
  5379. }
  5380. // Create the vector type.
  5381. QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
  5382. if (!T.isNull())
  5383. CurType = T;
  5384. }
  5385. static bool isPermittedNeonBaseType(QualType &Ty,
  5386. VectorType::VectorKind VecKind, Sema &S) {
  5387. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  5388. if (!BTy)
  5389. return false;
  5390. llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
  5391. // Signed poly is mathematically wrong, but has been baked into some ABIs by
  5392. // now.
  5393. bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
  5394. Triple.getArch() == llvm::Triple::aarch64_be;
  5395. if (VecKind == VectorType::NeonPolyVector) {
  5396. if (IsPolyUnsigned) {
  5397. // AArch64 polynomial vectors are unsigned and support poly64.
  5398. return BTy->getKind() == BuiltinType::UChar ||
  5399. BTy->getKind() == BuiltinType::UShort ||
  5400. BTy->getKind() == BuiltinType::ULong ||
  5401. BTy->getKind() == BuiltinType::ULongLong;
  5402. } else {
  5403. // AArch32 polynomial vector are signed.
  5404. return BTy->getKind() == BuiltinType::SChar ||
  5405. BTy->getKind() == BuiltinType::Short;
  5406. }
  5407. }
  5408. // Non-polynomial vector types: the usual suspects are allowed, as well as
  5409. // float64_t on AArch64.
  5410. bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
  5411. Triple.getArch() == llvm::Triple::aarch64_be;
  5412. if (Is64Bit && BTy->getKind() == BuiltinType::Double)
  5413. return true;
  5414. return BTy->getKind() == BuiltinType::SChar ||
  5415. BTy->getKind() == BuiltinType::UChar ||
  5416. BTy->getKind() == BuiltinType::Short ||
  5417. BTy->getKind() == BuiltinType::UShort ||
  5418. BTy->getKind() == BuiltinType::Int ||
  5419. BTy->getKind() == BuiltinType::UInt ||
  5420. BTy->getKind() == BuiltinType::Long ||
  5421. BTy->getKind() == BuiltinType::ULong ||
  5422. BTy->getKind() == BuiltinType::LongLong ||
  5423. BTy->getKind() == BuiltinType::ULongLong ||
  5424. BTy->getKind() == BuiltinType::Float ||
  5425. BTy->getKind() == BuiltinType::Half;
  5426. }
  5427. /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
  5428. /// "neon_polyvector_type" attributes are used to create vector types that
  5429. /// are mangled according to ARM's ABI. Otherwise, these types are identical
  5430. /// to those created with the "vector_size" attribute. Unlike "vector_size"
  5431. /// the argument to these Neon attributes is the number of vector elements,
  5432. /// not the vector size in bytes. The vector width and element type must
  5433. /// match one of the standard Neon vector types.
  5434. static void HandleNeonVectorTypeAttr(QualType& CurType,
  5435. const AttributeList &Attr, Sema &S,
  5436. VectorType::VectorKind VecKind) {
  5437. // Target must have NEON
  5438. if (!S.Context.getTargetInfo().hasFeature("neon")) {
  5439. S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
  5440. Attr.setInvalid();
  5441. return;
  5442. }
  5443. // Check the attribute arguments.
  5444. if (Attr.getNumArgs() != 1) {
  5445. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
  5446. << Attr.getName() << 1;
  5447. Attr.setInvalid();
  5448. return;
  5449. }
  5450. // The number of elements must be an ICE.
  5451. Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
  5452. llvm::APSInt numEltsInt(32);
  5453. if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
  5454. !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
  5455. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  5456. << Attr.getName() << AANT_ArgumentIntegerConstant
  5457. << numEltsExpr->getSourceRange();
  5458. Attr.setInvalid();
  5459. return;
  5460. }
  5461. // Only certain element types are supported for Neon vectors.
  5462. if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
  5463. S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
  5464. Attr.setInvalid();
  5465. return;
  5466. }
  5467. // The total size of the vector must be 64 or 128 bits.
  5468. unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
  5469. unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
  5470. unsigned vecSize = typeSize * numElts;
  5471. if (vecSize != 64 && vecSize != 128) {
  5472. S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
  5473. Attr.setInvalid();
  5474. return;
  5475. }
  5476. CurType = S.Context.getVectorType(CurType, numElts, VecKind);
  5477. }
  5478. static void processTypeAttrs(TypeProcessingState &state, QualType &type,
  5479. TypeAttrLocation TAL, AttributeList *attrs) {
  5480. // Scan through and apply attributes to this type where it makes sense. Some
  5481. // attributes (such as __address_space__, __vector_size__, etc) apply to the
  5482. // type, but others can be present in the type specifiers even though they
  5483. // apply to the decl. Here we apply type attributes and ignore the rest.
  5484. bool hasOpenCLAddressSpace = false;
  5485. while (attrs) {
  5486. AttributeList &attr = *attrs;
  5487. attrs = attr.getNext(); // reset to the next here due to early loop continue
  5488. // stmts
  5489. // Skip attributes that were marked to be invalid.
  5490. if (attr.isInvalid())
  5491. continue;
  5492. if (attr.isCXX11Attribute()) {
  5493. // [[gnu::...]] attributes are treated as declaration attributes, so may
  5494. // not appertain to a DeclaratorChunk, even if we handle them as type
  5495. // attributes.
  5496. if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
  5497. if (TAL == TAL_DeclChunk) {
  5498. state.getSema().Diag(attr.getLoc(),
  5499. diag::warn_cxx11_gnu_attribute_on_type)
  5500. << attr.getName();
  5501. continue;
  5502. }
  5503. } else if (TAL != TAL_DeclChunk) {
  5504. // Otherwise, only consider type processing for a C++11 attribute if
  5505. // it's actually been applied to a type.
  5506. continue;
  5507. }
  5508. }
  5509. // If this is an attribute we can handle, do so now,
  5510. // otherwise, add it to the FnAttrs list for rechaining.
  5511. switch (attr.getKind()) {
  5512. default:
  5513. // A C++11 attribute on a declarator chunk must appertain to a type.
  5514. if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
  5515. state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
  5516. << attr.getName();
  5517. attr.setUsedAsTypeAttr();
  5518. }
  5519. break;
  5520. case AttributeList::UnknownAttribute:
  5521. if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
  5522. state.getSema().Diag(attr.getLoc(),
  5523. diag::warn_unknown_attribute_ignored)
  5524. << attr.getName();
  5525. break;
  5526. case AttributeList::IgnoredAttribute:
  5527. break;
  5528. case AttributeList::AT_MayAlias:
  5529. // FIXME: This attribute needs to actually be handled, but if we ignore
  5530. // it it breaks large amounts of Linux software.
  5531. attr.setUsedAsTypeAttr();
  5532. break;
  5533. case AttributeList::AT_OpenCLPrivateAddressSpace:
  5534. case AttributeList::AT_OpenCLGlobalAddressSpace:
  5535. case AttributeList::AT_OpenCLLocalAddressSpace:
  5536. case AttributeList::AT_OpenCLConstantAddressSpace:
  5537. case AttributeList::AT_OpenCLGenericAddressSpace:
  5538. case AttributeList::AT_AddressSpace:
  5539. HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
  5540. attr.setUsedAsTypeAttr();
  5541. hasOpenCLAddressSpace = true;
  5542. break;
  5543. OBJC_POINTER_TYPE_ATTRS_CASELIST:
  5544. if (!handleObjCPointerTypeAttr(state, attr, type))
  5545. distributeObjCPointerTypeAttr(state, attr, type);
  5546. attr.setUsedAsTypeAttr();
  5547. break;
  5548. case AttributeList::AT_VectorSize:
  5549. HandleVectorSizeAttr(type, attr, state.getSema());
  5550. attr.setUsedAsTypeAttr();
  5551. break;
  5552. case AttributeList::AT_ExtVectorType:
  5553. HandleExtVectorTypeAttr(type, attr, state.getSema());
  5554. attr.setUsedAsTypeAttr();
  5555. break;
  5556. case AttributeList::AT_NeonVectorType:
  5557. HandleNeonVectorTypeAttr(type, attr, state.getSema(),
  5558. VectorType::NeonVector);
  5559. attr.setUsedAsTypeAttr();
  5560. break;
  5561. case AttributeList::AT_NeonPolyVectorType:
  5562. HandleNeonVectorTypeAttr(type, attr, state.getSema(),
  5563. VectorType::NeonPolyVector);
  5564. attr.setUsedAsTypeAttr();
  5565. break;
  5566. case AttributeList::AT_OpenCLImageAccess:
  5567. // FIXME: there should be some type checking happening here, I would
  5568. // imagine, but the original handler's checking was entirely superfluous.
  5569. attr.setUsedAsTypeAttr();
  5570. break;
  5571. MS_TYPE_ATTRS_CASELIST:
  5572. if (!handleMSPointerTypeQualifierAttr(state, attr, type))
  5573. attr.setUsedAsTypeAttr();
  5574. break;
  5575. NULLABILITY_TYPE_ATTRS_CASELIST:
  5576. // Either add nullability here or try to distribute it. We
  5577. // don't want to distribute the nullability specifier past any
  5578. // dependent type, because that complicates the user model.
  5579. if (type->canHaveNullability() || type->isDependentType() ||
  5580. !distributeNullabilityTypeAttr(state, type, attr)) {
  5581. if (state.getSema().checkNullabilityTypeSpecifier(
  5582. type,
  5583. mapNullabilityAttrKind(attr.getKind()),
  5584. attr.getLoc(),
  5585. attr.isContextSensitiveKeywordAttribute())) {
  5586. attr.setInvalid();
  5587. }
  5588. attr.setUsedAsTypeAttr();
  5589. }
  5590. break;
  5591. case AttributeList::AT_ObjCKindOf:
  5592. // '__kindof' must be part of the decl-specifiers.
  5593. switch (TAL) {
  5594. case TAL_DeclSpec:
  5595. break;
  5596. case TAL_DeclChunk:
  5597. case TAL_DeclName:
  5598. state.getSema().Diag(attr.getLoc(),
  5599. diag::err_objc_kindof_wrong_position)
  5600. << FixItHint::CreateRemoval(attr.getLoc())
  5601. << FixItHint::CreateInsertion(
  5602. state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
  5603. break;
  5604. }
  5605. // Apply it regardless.
  5606. if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
  5607. attr.setInvalid();
  5608. attr.setUsedAsTypeAttr();
  5609. break;
  5610. case AttributeList::AT_NSReturnsRetained:
  5611. if (!state.getSema().getLangOpts().ObjCAutoRefCount)
  5612. break;
  5613. // fallthrough into the function attrs
  5614. FUNCTION_TYPE_ATTRS_CASELIST:
  5615. attr.setUsedAsTypeAttr();
  5616. // Never process function type attributes as part of the
  5617. // declaration-specifiers.
  5618. if (TAL == TAL_DeclSpec)
  5619. distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
  5620. // Otherwise, handle the possible delays.
  5621. else if (!handleFunctionTypeAttr(state, attr, type))
  5622. distributeFunctionTypeAttr(state, attr, type);
  5623. break;
  5624. }
  5625. }
  5626. // If address space is not set, OpenCL 2.0 defines non private default
  5627. // address spaces for some cases:
  5628. // OpenCL 2.0, section 6.5:
  5629. // The address space for a variable at program scope or a static variable
  5630. // inside a function can either be __global or __constant, but defaults to
  5631. // __global if not specified.
  5632. // (...)
  5633. // Pointers that are declared without pointing to a named address space point
  5634. // to the generic address space.
  5635. if (state.getSema().getLangOpts().OpenCLVersion >= 200 &&
  5636. !hasOpenCLAddressSpace && type.getAddressSpace() == 0 &&
  5637. (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) {
  5638. Declarator &D = state.getDeclarator();
  5639. if (state.getCurrentChunkIndex() > 0 &&
  5640. D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
  5641. DeclaratorChunk::Pointer) {
  5642. type = state.getSema().Context.getAddrSpaceQualType(
  5643. type, LangAS::opencl_generic);
  5644. } else if (state.getCurrentChunkIndex() == 0 &&
  5645. D.getContext() == Declarator::FileContext &&
  5646. !D.isFunctionDeclarator() && !D.isFunctionDefinition() &&
  5647. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  5648. !type->isSamplerT())
  5649. type = state.getSema().Context.getAddrSpaceQualType(
  5650. type, LangAS::opencl_global);
  5651. else if (state.getCurrentChunkIndex() == 0 &&
  5652. D.getContext() == Declarator::BlockContext &&
  5653. D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
  5654. type = state.getSema().Context.getAddrSpaceQualType(
  5655. type, LangAS::opencl_global);
  5656. }
  5657. }
  5658. void Sema::completeExprArrayBound(Expr *E) {
  5659. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  5660. if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
  5661. if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
  5662. SourceLocation PointOfInstantiation = E->getExprLoc();
  5663. if (MemberSpecializationInfo *MSInfo =
  5664. Var->getMemberSpecializationInfo()) {
  5665. // If we don't already have a point of instantiation, this is it.
  5666. if (MSInfo->getPointOfInstantiation().isInvalid()) {
  5667. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  5668. // This is a modification of an existing AST node. Notify
  5669. // listeners.
  5670. if (ASTMutationListener *L = getASTMutationListener())
  5671. L->StaticDataMemberInstantiated(Var);
  5672. }
  5673. } else {
  5674. VarTemplateSpecializationDecl *VarSpec =
  5675. cast<VarTemplateSpecializationDecl>(Var);
  5676. if (VarSpec->getPointOfInstantiation().isInvalid())
  5677. VarSpec->setPointOfInstantiation(PointOfInstantiation);
  5678. }
  5679. InstantiateVariableDefinition(PointOfInstantiation, Var);
  5680. // Update the type to the newly instantiated definition's type both
  5681. // here and within the expression.
  5682. if (VarDecl *Def = Var->getDefinition()) {
  5683. DRE->setDecl(Def);
  5684. QualType T = Def->getType();
  5685. DRE->setType(T);
  5686. // FIXME: Update the type on all intervening expressions.
  5687. E->setType(T);
  5688. }
  5689. // We still go on to try to complete the type independently, as it
  5690. // may also require instantiations or diagnostics if it remains
  5691. // incomplete.
  5692. }
  5693. }
  5694. }
  5695. }
  5696. /// \brief Ensure that the type of the given expression is complete.
  5697. ///
  5698. /// This routine checks whether the expression \p E has a complete type. If the
  5699. /// expression refers to an instantiable construct, that instantiation is
  5700. /// performed as needed to complete its type. Furthermore
  5701. /// Sema::RequireCompleteType is called for the expression's type (or in the
  5702. /// case of a reference type, the referred-to type).
  5703. ///
  5704. /// \param E The expression whose type is required to be complete.
  5705. /// \param Diagnoser The object that will emit a diagnostic if the type is
  5706. /// incomplete.
  5707. ///
  5708. /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
  5709. /// otherwise.
  5710. bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
  5711. QualType T = E->getType();
  5712. // Incomplete array types may be completed by the initializer attached to
  5713. // their definitions. For static data members of class templates and for
  5714. // variable templates, we need to instantiate the definition to get this
  5715. // initializer and complete the type.
  5716. if (T->isIncompleteArrayType()) {
  5717. completeExprArrayBound(E);
  5718. T = E->getType();
  5719. }
  5720. // FIXME: Are there other cases which require instantiating something other
  5721. // than the type to complete the type of an expression?
  5722. return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
  5723. }
  5724. bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
  5725. BoundTypeDiagnoser<> Diagnoser(DiagID);
  5726. return RequireCompleteExprType(E, Diagnoser);
  5727. }
  5728. /// @brief Ensure that the type T is a complete type.
  5729. ///
  5730. /// This routine checks whether the type @p T is complete in any
  5731. /// context where a complete type is required. If @p T is a complete
  5732. /// type, returns false. If @p T is a class template specialization,
  5733. /// this routine then attempts to perform class template
  5734. /// instantiation. If instantiation fails, or if @p T is incomplete
  5735. /// and cannot be completed, issues the diagnostic @p diag (giving it
  5736. /// the type @p T) and returns true.
  5737. ///
  5738. /// @param Loc The location in the source that the incomplete type
  5739. /// diagnostic should refer to.
  5740. ///
  5741. /// @param T The type that this routine is examining for completeness.
  5742. ///
  5743. /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
  5744. /// @c false otherwise.
  5745. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
  5746. TypeDiagnoser &Diagnoser) {
  5747. if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
  5748. return true;
  5749. if (const TagType *Tag = T->getAs<TagType>()) {
  5750. if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
  5751. Tag->getDecl()->setCompleteDefinitionRequired();
  5752. Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
  5753. }
  5754. }
  5755. return false;
  5756. }
  5757. /// \brief Determine whether there is any declaration of \p D that was ever a
  5758. /// definition (perhaps before module merging) and is currently visible.
  5759. /// \param D The definition of the entity.
  5760. /// \param Suggested Filled in with the declaration that should be made visible
  5761. /// in order to provide a definition of this entity.
  5762. /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
  5763. /// not defined. This only matters for enums with a fixed underlying
  5764. /// type, since in all other cases, a type is complete if and only if it
  5765. /// is defined.
  5766. bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
  5767. bool OnlyNeedComplete) {
  5768. // Easy case: if we don't have modules, all declarations are visible.
  5769. if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
  5770. return true;
  5771. // If this definition was instantiated from a template, map back to the
  5772. // pattern from which it was instantiated.
  5773. if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
  5774. // We're in the middle of defining it; this definition should be treated
  5775. // as visible.
  5776. return true;
  5777. } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  5778. if (auto *Pattern = RD->getTemplateInstantiationPattern())
  5779. RD = Pattern;
  5780. D = RD->getDefinition();
  5781. } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
  5782. while (auto *NewED = ED->getInstantiatedFromMemberEnum())
  5783. ED = NewED;
  5784. if (OnlyNeedComplete && ED->isFixed()) {
  5785. // If the enum has a fixed underlying type, and we're only looking for a
  5786. // complete type (not a definition), any visible declaration of it will
  5787. // do.
  5788. *Suggested = nullptr;
  5789. for (auto *Redecl : ED->redecls()) {
  5790. if (isVisible(Redecl))
  5791. return true;
  5792. if (Redecl->isThisDeclarationADefinition() ||
  5793. (Redecl->isCanonicalDecl() && !*Suggested))
  5794. *Suggested = Redecl;
  5795. }
  5796. return false;
  5797. }
  5798. D = ED->getDefinition();
  5799. }
  5800. assert(D && "missing definition for pattern of instantiated definition");
  5801. *Suggested = D;
  5802. if (isVisible(D))
  5803. return true;
  5804. // The external source may have additional definitions of this type that are
  5805. // visible, so complete the redeclaration chain now and ask again.
  5806. if (auto *Source = Context.getExternalSource()) {
  5807. Source->CompleteRedeclChain(D);
  5808. return isVisible(D);
  5809. }
  5810. return false;
  5811. }
  5812. /// Locks in the inheritance model for the given class and all of its bases.
  5813. static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
  5814. RD = RD->getMostRecentDecl();
  5815. if (!RD->hasAttr<MSInheritanceAttr>()) {
  5816. MSInheritanceAttr::Spelling IM;
  5817. switch (S.MSPointerToMemberRepresentationMethod) {
  5818. case LangOptions::PPTMK_BestCase:
  5819. IM = RD->calculateInheritanceModel();
  5820. break;
  5821. case LangOptions::PPTMK_FullGeneralitySingleInheritance:
  5822. IM = MSInheritanceAttr::Keyword_single_inheritance;
  5823. break;
  5824. case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
  5825. IM = MSInheritanceAttr::Keyword_multiple_inheritance;
  5826. break;
  5827. case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
  5828. IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
  5829. break;
  5830. }
  5831. RD->addAttr(MSInheritanceAttr::CreateImplicit(
  5832. S.getASTContext(), IM,
  5833. /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
  5834. LangOptions::PPTMK_BestCase,
  5835. S.ImplicitMSInheritanceAttrLoc.isValid()
  5836. ? S.ImplicitMSInheritanceAttrLoc
  5837. : RD->getSourceRange()));
  5838. }
  5839. }
  5840. /// \brief The implementation of RequireCompleteType
  5841. bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
  5842. TypeDiagnoser *Diagnoser) {
  5843. // FIXME: Add this assertion to make sure we always get instantiation points.
  5844. // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
  5845. // FIXME: Add this assertion to help us flush out problems with
  5846. // checking for dependent types and type-dependent expressions.
  5847. //
  5848. // assert(!T->isDependentType() &&
  5849. // "Can't ask whether a dependent type is complete");
  5850. // We lock in the inheritance model once somebody has asked us to ensure
  5851. // that a pointer-to-member type is complete.
  5852. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  5853. if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
  5854. if (!MPTy->getClass()->isDependentType()) {
  5855. (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
  5856. assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
  5857. }
  5858. }
  5859. }
  5860. // If we have a complete type, we're done.
  5861. NamedDecl *Def = nullptr;
  5862. if (!T->isIncompleteType(&Def)) {
  5863. // If we know about the definition but it is not visible, complain.
  5864. NamedDecl *SuggestedDef = nullptr;
  5865. if (Def &&
  5866. !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
  5867. // If the user is going to see an error here, recover by making the
  5868. // definition visible.
  5869. bool TreatAsComplete = Diagnoser && !isSFINAEContext();
  5870. if (Diagnoser)
  5871. diagnoseMissingImport(Loc, SuggestedDef, /*NeedDefinition*/true,
  5872. /*Recover*/TreatAsComplete);
  5873. return !TreatAsComplete;
  5874. }
  5875. return false;
  5876. }
  5877. const TagType *Tag = T->getAs<TagType>();
  5878. const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
  5879. // If there's an unimported definition of this type in a module (for
  5880. // instance, because we forward declared it, then imported the definition),
  5881. // import that definition now.
  5882. //
  5883. // FIXME: What about other cases where an import extends a redeclaration
  5884. // chain for a declaration that can be accessed through a mechanism other
  5885. // than name lookup (eg, referenced in a template, or a variable whose type
  5886. // could be completed by the module)?
  5887. //
  5888. // FIXME: Should we map through to the base array element type before
  5889. // checking for a tag type?
  5890. if (Tag || IFace) {
  5891. NamedDecl *D =
  5892. Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
  5893. // Avoid diagnosing invalid decls as incomplete.
  5894. if (D->isInvalidDecl())
  5895. return true;
  5896. // Give the external AST source a chance to complete the type.
  5897. if (auto *Source = Context.getExternalSource()) {
  5898. if (Tag)
  5899. Source->CompleteType(Tag->getDecl());
  5900. else
  5901. Source->CompleteType(IFace->getDecl());
  5902. // If the external source completed the type, go through the motions
  5903. // again to ensure we're allowed to use the completed type.
  5904. if (!T->isIncompleteType())
  5905. return RequireCompleteTypeImpl(Loc, T, Diagnoser);
  5906. }
  5907. }
  5908. // If we have a class template specialization or a class member of a
  5909. // class template specialization, or an array with known size of such,
  5910. // try to instantiate it.
  5911. QualType MaybeTemplate = T;
  5912. while (const ConstantArrayType *Array
  5913. = Context.getAsConstantArrayType(MaybeTemplate))
  5914. MaybeTemplate = Array->getElementType();
  5915. if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
  5916. bool Instantiated = false;
  5917. bool Diagnosed = false;
  5918. if (ClassTemplateSpecializationDecl *ClassTemplateSpec
  5919. = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
  5920. if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
  5921. Diagnosed = InstantiateClassTemplateSpecialization(
  5922. Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
  5923. /*Complain=*/Diagnoser);
  5924. Instantiated = true;
  5925. }
  5926. } else if (CXXRecordDecl *Rec
  5927. = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
  5928. CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
  5929. if (!Rec->isBeingDefined() && Pattern) {
  5930. MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
  5931. assert(MSI && "Missing member specialization information?");
  5932. // This record was instantiated from a class within a template.
  5933. if (MSI->getTemplateSpecializationKind() !=
  5934. TSK_ExplicitSpecialization) {
  5935. Diagnosed = InstantiateClass(Loc, Rec, Pattern,
  5936. getTemplateInstantiationArgs(Rec),
  5937. TSK_ImplicitInstantiation,
  5938. /*Complain=*/Diagnoser);
  5939. Instantiated = true;
  5940. }
  5941. }
  5942. }
  5943. if (Instantiated) {
  5944. // Instantiate* might have already complained that the template is not
  5945. // defined, if we asked it to.
  5946. if (Diagnoser && Diagnosed)
  5947. return true;
  5948. // If we instantiated a definition, check that it's usable, even if
  5949. // instantiation produced an error, so that repeated calls to this
  5950. // function give consistent answers.
  5951. if (!T->isIncompleteType())
  5952. return RequireCompleteTypeImpl(Loc, T, Diagnoser);
  5953. }
  5954. }
  5955. if (!Diagnoser)
  5956. return true;
  5957. // We have an incomplete type. Produce a diagnostic.
  5958. if (Ident___float128 &&
  5959. T == Context.getTypeDeclType(Context.getFloat128StubType())) {
  5960. Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
  5961. return true;
  5962. }
  5963. Diagnoser->diagnose(*this, Loc, T);
  5964. // If the type was a forward declaration of a class/struct/union
  5965. // type, produce a note.
  5966. if (Tag && !Tag->getDecl()->isInvalidDecl())
  5967. Diag(Tag->getDecl()->getLocation(),
  5968. Tag->isBeingDefined() ? diag::note_type_being_defined
  5969. : diag::note_forward_declaration)
  5970. << QualType(Tag, 0);
  5971. // If the Objective-C class was a forward declaration, produce a note.
  5972. if (IFace && !IFace->getDecl()->isInvalidDecl())
  5973. Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
  5974. // If we have external information that we can use to suggest a fix,
  5975. // produce a note.
  5976. if (ExternalSource)
  5977. ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
  5978. return true;
  5979. }
  5980. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
  5981. unsigned DiagID) {
  5982. BoundTypeDiagnoser<> Diagnoser(DiagID);
  5983. return RequireCompleteType(Loc, T, Diagnoser);
  5984. }
  5985. /// \brief Get diagnostic %select index for tag kind for
  5986. /// literal type diagnostic message.
  5987. /// WARNING: Indexes apply to particular diagnostics only!
  5988. ///
  5989. /// \returns diagnostic %select index.
  5990. static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
  5991. switch (Tag) {
  5992. case TTK_Struct: return 0;
  5993. case TTK_Interface: return 1;
  5994. case TTK_Class: return 2;
  5995. default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
  5996. }
  5997. }
  5998. /// @brief Ensure that the type T is a literal type.
  5999. ///
  6000. /// This routine checks whether the type @p T is a literal type. If @p T is an
  6001. /// incomplete type, an attempt is made to complete it. If @p T is a literal
  6002. /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
  6003. /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
  6004. /// it the type @p T), along with notes explaining why the type is not a
  6005. /// literal type, and returns true.
  6006. ///
  6007. /// @param Loc The location in the source that the non-literal type
  6008. /// diagnostic should refer to.
  6009. ///
  6010. /// @param T The type that this routine is examining for literalness.
  6011. ///
  6012. /// @param Diagnoser Emits a diagnostic if T is not a literal type.
  6013. ///
  6014. /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
  6015. /// @c false otherwise.
  6016. bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
  6017. TypeDiagnoser &Diagnoser) {
  6018. assert(!T->isDependentType() && "type should not be dependent");
  6019. QualType ElemType = Context.getBaseElementType(T);
  6020. if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
  6021. T->isLiteralType(Context))
  6022. return false;
  6023. Diagnoser.diagnose(*this, Loc, T);
  6024. if (T->isVariableArrayType())
  6025. return true;
  6026. const RecordType *RT = ElemType->getAs<RecordType>();
  6027. if (!RT)
  6028. return true;
  6029. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  6030. // A partially-defined class type can't be a literal type, because a literal
  6031. // class type must have a trivial destructor (which can't be checked until
  6032. // the class definition is complete).
  6033. if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
  6034. return true;
  6035. // If the class has virtual base classes, then it's not an aggregate, and
  6036. // cannot have any constexpr constructors or a trivial default constructor,
  6037. // so is non-literal. This is better to diagnose than the resulting absence
  6038. // of constexpr constructors.
  6039. if (RD->getNumVBases()) {
  6040. Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
  6041. << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  6042. for (const auto &I : RD->vbases())
  6043. Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
  6044. << I.getSourceRange();
  6045. } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
  6046. !RD->hasTrivialDefaultConstructor()) {
  6047. Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
  6048. } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
  6049. for (const auto &I : RD->bases()) {
  6050. if (!I.getType()->isLiteralType(Context)) {
  6051. Diag(I.getLocStart(),
  6052. diag::note_non_literal_base_class)
  6053. << RD << I.getType() << I.getSourceRange();
  6054. return true;
  6055. }
  6056. }
  6057. for (const auto *I : RD->fields()) {
  6058. if (!I->getType()->isLiteralType(Context) ||
  6059. I->getType().isVolatileQualified()) {
  6060. Diag(I->getLocation(), diag::note_non_literal_field)
  6061. << RD << I << I->getType()
  6062. << I->getType().isVolatileQualified();
  6063. return true;
  6064. }
  6065. }
  6066. } else if (!RD->hasTrivialDestructor()) {
  6067. // All fields and bases are of literal types, so have trivial destructors.
  6068. // If this class's destructor is non-trivial it must be user-declared.
  6069. CXXDestructorDecl *Dtor = RD->getDestructor();
  6070. assert(Dtor && "class has literal fields and bases but no dtor?");
  6071. if (!Dtor)
  6072. return true;
  6073. Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
  6074. diag::note_non_literal_user_provided_dtor :
  6075. diag::note_non_literal_nontrivial_dtor) << RD;
  6076. if (!Dtor->isUserProvided())
  6077. SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
  6078. }
  6079. return true;
  6080. }
  6081. bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
  6082. BoundTypeDiagnoser<> Diagnoser(DiagID);
  6083. return RequireLiteralType(Loc, T, Diagnoser);
  6084. }
  6085. /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
  6086. /// and qualified by the nested-name-specifier contained in SS.
  6087. QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
  6088. const CXXScopeSpec &SS, QualType T) {
  6089. if (T.isNull())
  6090. return T;
  6091. NestedNameSpecifier *NNS;
  6092. if (SS.isValid())
  6093. NNS = SS.getScopeRep();
  6094. else {
  6095. if (Keyword == ETK_None)
  6096. return T;
  6097. NNS = nullptr;
  6098. }
  6099. return Context.getElaboratedType(Keyword, NNS, T);
  6100. }
  6101. QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
  6102. ExprResult ER = CheckPlaceholderExpr(E);
  6103. if (ER.isInvalid()) return QualType();
  6104. E = ER.get();
  6105. if (!getLangOpts().CPlusPlus && E->refersToBitField())
  6106. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
  6107. if (!E->isTypeDependent()) {
  6108. QualType T = E->getType();
  6109. if (const TagType *TT = T->getAs<TagType>())
  6110. DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
  6111. }
  6112. return Context.getTypeOfExprType(E);
  6113. }
  6114. /// getDecltypeForExpr - Given an expr, will return the decltype for
  6115. /// that expression, according to the rules in C++11
  6116. /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
  6117. static QualType getDecltypeForExpr(Sema &S, Expr *E) {
  6118. if (E->isTypeDependent())
  6119. return S.Context.DependentTy;
  6120. // C++11 [dcl.type.simple]p4:
  6121. // The type denoted by decltype(e) is defined as follows:
  6122. //
  6123. // - if e is an unparenthesized id-expression or an unparenthesized class
  6124. // member access (5.2.5), decltype(e) is the type of the entity named
  6125. // by e. If there is no such entity, or if e names a set of overloaded
  6126. // functions, the program is ill-formed;
  6127. //
  6128. // We apply the same rules for Objective-C ivar and property references.
  6129. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  6130. if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
  6131. return VD->getType();
  6132. } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  6133. if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  6134. return FD->getType();
  6135. } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
  6136. return IR->getDecl()->getType();
  6137. } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
  6138. if (PR->isExplicitProperty())
  6139. return PR->getExplicitProperty()->getType();
  6140. } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
  6141. return PE->getType();
  6142. }
  6143. // C++11 [expr.lambda.prim]p18:
  6144. // Every occurrence of decltype((x)) where x is a possibly
  6145. // parenthesized id-expression that names an entity of automatic
  6146. // storage duration is treated as if x were transformed into an
  6147. // access to a corresponding data member of the closure type that
  6148. // would have been declared if x were an odr-use of the denoted
  6149. // entity.
  6150. using namespace sema;
  6151. if (S.getCurLambda()) {
  6152. if (isa<ParenExpr>(E)) {
  6153. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  6154. if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
  6155. QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
  6156. if (!T.isNull())
  6157. return S.Context.getLValueReferenceType(T);
  6158. }
  6159. }
  6160. }
  6161. }
  6162. // C++11 [dcl.type.simple]p4:
  6163. // [...]
  6164. QualType T = E->getType();
  6165. switch (E->getValueKind()) {
  6166. // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
  6167. // type of e;
  6168. case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
  6169. // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
  6170. // type of e;
  6171. case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
  6172. // - otherwise, decltype(e) is the type of e.
  6173. case VK_RValue: break;
  6174. }
  6175. return T;
  6176. }
  6177. QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
  6178. bool AsUnevaluated) {
  6179. ExprResult ER = CheckPlaceholderExpr(E);
  6180. if (ER.isInvalid()) return QualType();
  6181. E = ER.get();
  6182. if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
  6183. E->HasSideEffects(Context, false)) {
  6184. // The expression operand for decltype is in an unevaluated expression
  6185. // context, so side effects could result in unintended consequences.
  6186. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  6187. }
  6188. return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
  6189. }
  6190. QualType Sema::BuildUnaryTransformType(QualType BaseType,
  6191. UnaryTransformType::UTTKind UKind,
  6192. SourceLocation Loc) {
  6193. switch (UKind) {
  6194. case UnaryTransformType::EnumUnderlyingType:
  6195. if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
  6196. Diag(Loc, diag::err_only_enums_have_underlying_types);
  6197. return QualType();
  6198. } else {
  6199. QualType Underlying = BaseType;
  6200. if (!BaseType->isDependentType()) {
  6201. // The enum could be incomplete if we're parsing its definition or
  6202. // recovering from an error.
  6203. NamedDecl *FwdDecl = nullptr;
  6204. if (BaseType->isIncompleteType(&FwdDecl)) {
  6205. Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
  6206. Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
  6207. return QualType();
  6208. }
  6209. EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
  6210. assert(ED && "EnumType has no EnumDecl");
  6211. DiagnoseUseOfDecl(ED, Loc);
  6212. Underlying = ED->getIntegerType();
  6213. assert(!Underlying.isNull());
  6214. }
  6215. return Context.getUnaryTransformType(BaseType, Underlying,
  6216. UnaryTransformType::EnumUnderlyingType);
  6217. }
  6218. }
  6219. llvm_unreachable("unknown unary transform type");
  6220. }
  6221. QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
  6222. if (!T->isDependentType()) {
  6223. // FIXME: It isn't entirely clear whether incomplete atomic types
  6224. // are allowed or not; for simplicity, ban them for the moment.
  6225. if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
  6226. return QualType();
  6227. int DisallowedKind = -1;
  6228. if (T->isArrayType())
  6229. DisallowedKind = 1;
  6230. else if (T->isFunctionType())
  6231. DisallowedKind = 2;
  6232. else if (T->isReferenceType())
  6233. DisallowedKind = 3;
  6234. else if (T->isAtomicType())
  6235. DisallowedKind = 4;
  6236. else if (T.hasQualifiers())
  6237. DisallowedKind = 5;
  6238. else if (!T.isTriviallyCopyableType(Context))
  6239. // Some other non-trivially-copyable type (probably a C++ class)
  6240. DisallowedKind = 6;
  6241. if (DisallowedKind != -1) {
  6242. Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
  6243. return QualType();
  6244. }
  6245. // FIXME: Do we need any handling for ARC here?
  6246. }
  6247. // Build the pointer type.
  6248. return Context.getAtomicType(T);
  6249. }