SemaType.cpp 316 KB

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