SemaType.cpp 282 KB

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