SemaType.cpp 282 KB

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