SemaType.cpp 284 KB

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