SemaDeclAttr.cpp 312 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169
  1. //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements decl-related attribute processing.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTConsumer.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ASTMutationListener.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclObjC.h"
  18. #include "clang/AST/DeclTemplate.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/Mangle.h"
  22. #include "clang/AST/RecursiveASTVisitor.h"
  23. #include "clang/AST/Type.h"
  24. #include "clang/Basic/CharInfo.h"
  25. #include "clang/Basic/DarwinSDKInfo.h"
  26. #include "clang/Basic/SourceLocation.h"
  27. #include "clang/Basic/SourceManager.h"
  28. #include "clang/Basic/TargetBuiltins.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Lex/Preprocessor.h"
  31. #include "clang/Sema/DeclSpec.h"
  32. #include "clang/Sema/DelayedDiagnostic.h"
  33. #include "clang/Sema/Initialization.h"
  34. #include "clang/Sema/Lookup.h"
  35. #include "clang/Sema/ParsedAttr.h"
  36. #include "clang/Sema/Scope.h"
  37. #include "clang/Sema/ScopeInfo.h"
  38. #include "clang/Sema/SemaInternal.h"
  39. #include "llvm/ADT/Optional.h"
  40. #include "llvm/ADT/STLExtras.h"
  41. #include "llvm/ADT/StringExtras.h"
  42. #include "llvm/IR/Assumptions.h"
  43. #include "llvm/MC/MCSectionMachO.h"
  44. #include "llvm/Support/Error.h"
  45. #include "llvm/Support/MathExtras.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. using namespace clang;
  48. using namespace sema;
  49. namespace AttributeLangSupport {
  50. enum LANG {
  51. C,
  52. Cpp,
  53. ObjC
  54. };
  55. } // end namespace AttributeLangSupport
  56. //===----------------------------------------------------------------------===//
  57. // Helper functions
  58. //===----------------------------------------------------------------------===//
  59. /// isFunctionOrMethod - Return true if the given decl has function
  60. /// type (function or function-typed variable) or an Objective-C
  61. /// method.
  62. static bool isFunctionOrMethod(const Decl *D) {
  63. return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
  64. }
  65. /// Return true if the given decl has function type (function or
  66. /// function-typed variable) or an Objective-C method or a block.
  67. static bool isFunctionOrMethodOrBlock(const Decl *D) {
  68. return isFunctionOrMethod(D) || isa<BlockDecl>(D);
  69. }
  70. /// Return true if the given decl has a declarator that should have
  71. /// been processed by Sema::GetTypeForDeclarator.
  72. static bool hasDeclarator(const Decl *D) {
  73. // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
  74. return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
  75. isa<ObjCPropertyDecl>(D);
  76. }
  77. /// hasFunctionProto - Return true if the given decl has a argument
  78. /// information. This decl should have already passed
  79. /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
  80. static bool hasFunctionProto(const Decl *D) {
  81. if (const FunctionType *FnTy = D->getFunctionType())
  82. return isa<FunctionProtoType>(FnTy);
  83. return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
  84. }
  85. /// getFunctionOrMethodNumParams - Return number of function or method
  86. /// parameters. It is an error to call this on a K&R function (use
  87. /// hasFunctionProto first).
  88. static unsigned getFunctionOrMethodNumParams(const Decl *D) {
  89. if (const FunctionType *FnTy = D->getFunctionType())
  90. return cast<FunctionProtoType>(FnTy)->getNumParams();
  91. if (const auto *BD = dyn_cast<BlockDecl>(D))
  92. return BD->getNumParams();
  93. return cast<ObjCMethodDecl>(D)->param_size();
  94. }
  95. static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D,
  96. unsigned Idx) {
  97. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  98. return FD->getParamDecl(Idx);
  99. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  100. return MD->getParamDecl(Idx);
  101. if (const auto *BD = dyn_cast<BlockDecl>(D))
  102. return BD->getParamDecl(Idx);
  103. return nullptr;
  104. }
  105. static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
  106. if (const FunctionType *FnTy = D->getFunctionType())
  107. return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
  108. if (const auto *BD = dyn_cast<BlockDecl>(D))
  109. return BD->getParamDecl(Idx)->getType();
  110. return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
  111. }
  112. static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
  113. if (auto *PVD = getFunctionOrMethodParam(D, Idx))
  114. return PVD->getSourceRange();
  115. return SourceRange();
  116. }
  117. static QualType getFunctionOrMethodResultType(const Decl *D) {
  118. if (const FunctionType *FnTy = D->getFunctionType())
  119. return FnTy->getReturnType();
  120. return cast<ObjCMethodDecl>(D)->getReturnType();
  121. }
  122. static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
  123. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  124. return FD->getReturnTypeSourceRange();
  125. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  126. return MD->getReturnTypeSourceRange();
  127. return SourceRange();
  128. }
  129. static bool isFunctionOrMethodVariadic(const Decl *D) {
  130. if (const FunctionType *FnTy = D->getFunctionType())
  131. return cast<FunctionProtoType>(FnTy)->isVariadic();
  132. if (const auto *BD = dyn_cast<BlockDecl>(D))
  133. return BD->isVariadic();
  134. return cast<ObjCMethodDecl>(D)->isVariadic();
  135. }
  136. static bool isInstanceMethod(const Decl *D) {
  137. if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
  138. return MethodDecl->isInstance();
  139. return false;
  140. }
  141. static inline bool isNSStringType(QualType T, ASTContext &Ctx,
  142. bool AllowNSAttributedString = false) {
  143. const auto *PT = T->getAs<ObjCObjectPointerType>();
  144. if (!PT)
  145. return false;
  146. ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
  147. if (!Cls)
  148. return false;
  149. IdentifierInfo* ClsName = Cls->getIdentifier();
  150. if (AllowNSAttributedString &&
  151. ClsName == &Ctx.Idents.get("NSAttributedString"))
  152. return true;
  153. // FIXME: Should we walk the chain of classes?
  154. return ClsName == &Ctx.Idents.get("NSString") ||
  155. ClsName == &Ctx.Idents.get("NSMutableString");
  156. }
  157. static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
  158. const auto *PT = T->getAs<PointerType>();
  159. if (!PT)
  160. return false;
  161. const auto *RT = PT->getPointeeType()->getAs<RecordType>();
  162. if (!RT)
  163. return false;
  164. const RecordDecl *RD = RT->getDecl();
  165. if (RD->getTagKind() != TTK_Struct)
  166. return false;
  167. return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
  168. }
  169. static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
  170. // FIXME: Include the type in the argument list.
  171. return AL.getNumArgs() + AL.hasParsedType();
  172. }
  173. /// A helper function to provide Attribute Location for the Attr types
  174. /// AND the ParsedAttr.
  175. template <typename AttrInfo>
  176. static std::enable_if_t<std::is_base_of<Attr, AttrInfo>::value, SourceLocation>
  177. getAttrLoc(const AttrInfo &AL) {
  178. return AL.getLocation();
  179. }
  180. static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
  181. /// If Expr is a valid integer constant, get the value of the integer
  182. /// expression and return success or failure. May output an error.
  183. ///
  184. /// Negative argument is implicitly converted to unsigned, unless
  185. /// \p StrictlyUnsigned is true.
  186. template <typename AttrInfo>
  187. static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
  188. uint32_t &Val, unsigned Idx = UINT_MAX,
  189. bool StrictlyUnsigned = false) {
  190. Optional<llvm::APSInt> I = llvm::APSInt(32);
  191. if (Expr->isTypeDependent() ||
  192. !(I = Expr->getIntegerConstantExpr(S.Context))) {
  193. if (Idx != UINT_MAX)
  194. S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
  195. << &AI << Idx << AANT_ArgumentIntegerConstant
  196. << Expr->getSourceRange();
  197. else
  198. S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
  199. << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
  200. return false;
  201. }
  202. if (!I->isIntN(32)) {
  203. S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
  204. << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
  205. return false;
  206. }
  207. if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
  208. S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
  209. << &AI << /*non-negative*/ 1;
  210. return false;
  211. }
  212. Val = (uint32_t)I->getZExtValue();
  213. return true;
  214. }
  215. /// Wrapper around checkUInt32Argument, with an extra check to be sure
  216. /// that the result will fit into a regular (signed) int. All args have the same
  217. /// purpose as they do in checkUInt32Argument.
  218. template <typename AttrInfo>
  219. static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
  220. int &Val, unsigned Idx = UINT_MAX) {
  221. uint32_t UVal;
  222. if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
  223. return false;
  224. if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
  225. llvm::APSInt I(32); // for toString
  226. I = UVal;
  227. S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
  228. << toString(I, 10, false) << 32 << /* Unsigned */ 0;
  229. return false;
  230. }
  231. Val = UVal;
  232. return true;
  233. }
  234. /// Diagnose mutually exclusive attributes when present on a given
  235. /// declaration. Returns true if diagnosed.
  236. template <typename AttrTy>
  237. static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
  238. if (const auto *A = D->getAttr<AttrTy>()) {
  239. S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
  240. S.Diag(A->getLocation(), diag::note_conflicting_attribute);
  241. return true;
  242. }
  243. return false;
  244. }
  245. template <typename AttrTy>
  246. static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
  247. if (const auto *A = D->getAttr<AttrTy>()) {
  248. S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL
  249. << A;
  250. S.Diag(A->getLocation(), diag::note_conflicting_attribute);
  251. return true;
  252. }
  253. return false;
  254. }
  255. /// Check if IdxExpr is a valid parameter index for a function or
  256. /// instance method D. May output an error.
  257. ///
  258. /// \returns true if IdxExpr is a valid index.
  259. template <typename AttrInfo>
  260. static bool checkFunctionOrMethodParameterIndex(
  261. Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
  262. const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
  263. assert(isFunctionOrMethodOrBlock(D));
  264. // In C++ the implicit 'this' function parameter also counts.
  265. // Parameters are counted from one.
  266. bool HP = hasFunctionProto(D);
  267. bool HasImplicitThisParam = isInstanceMethod(D);
  268. bool IV = HP && isFunctionOrMethodVariadic(D);
  269. unsigned NumParams =
  270. (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
  271. Optional<llvm::APSInt> IdxInt;
  272. if (IdxExpr->isTypeDependent() ||
  273. !(IdxInt = IdxExpr->getIntegerConstantExpr(S.Context))) {
  274. S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
  275. << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
  276. << IdxExpr->getSourceRange();
  277. return false;
  278. }
  279. unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX);
  280. if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
  281. S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
  282. << &AI << AttrArgNum << IdxExpr->getSourceRange();
  283. return false;
  284. }
  285. if (HasImplicitThisParam && !CanIndexImplicitThis) {
  286. if (IdxSource == 1) {
  287. S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
  288. << &AI << IdxExpr->getSourceRange();
  289. return false;
  290. }
  291. }
  292. Idx = ParamIdx(IdxSource, D);
  293. return true;
  294. }
  295. /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
  296. /// If not emit an error and return false. If the argument is an identifier it
  297. /// will emit an error with a fixit hint and treat it as if it was a string
  298. /// literal.
  299. bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
  300. StringRef &Str,
  301. SourceLocation *ArgLocation) {
  302. // Look for identifiers. If we have one emit a hint to fix it to a literal.
  303. if (AL.isArgIdent(ArgNum)) {
  304. IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
  305. Diag(Loc->Loc, diag::err_attribute_argument_type)
  306. << AL << AANT_ArgumentString
  307. << FixItHint::CreateInsertion(Loc->Loc, "\"")
  308. << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
  309. Str = Loc->Ident->getName();
  310. if (ArgLocation)
  311. *ArgLocation = Loc->Loc;
  312. return true;
  313. }
  314. // Now check for an actual string literal.
  315. Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
  316. const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
  317. if (ArgLocation)
  318. *ArgLocation = ArgExpr->getBeginLoc();
  319. if (!Literal || !Literal->isAscii()) {
  320. Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
  321. << AL << AANT_ArgumentString;
  322. return false;
  323. }
  324. Str = Literal->getString();
  325. return true;
  326. }
  327. /// Applies the given attribute to the Decl without performing any
  328. /// additional semantic checking.
  329. template <typename AttrType>
  330. static void handleSimpleAttribute(Sema &S, Decl *D,
  331. const AttributeCommonInfo &CI) {
  332. D->addAttr(::new (S.Context) AttrType(S.Context, CI));
  333. }
  334. template <typename... DiagnosticArgs>
  335. static const Sema::SemaDiagnosticBuilder&
  336. appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) {
  337. return Bldr;
  338. }
  339. template <typename T, typename... DiagnosticArgs>
  340. static const Sema::SemaDiagnosticBuilder&
  341. appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg,
  342. DiagnosticArgs &&... ExtraArgs) {
  343. return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
  344. std::forward<DiagnosticArgs>(ExtraArgs)...);
  345. }
  346. /// Add an attribute @c AttrType to declaration @c D, provided that
  347. /// @c PassesCheck is true.
  348. /// Otherwise, emit diagnostic @c DiagID, passing in all parameters
  349. /// specified in @c ExtraArgs.
  350. template <typename AttrType, typename... DiagnosticArgs>
  351. static void handleSimpleAttributeOrDiagnose(Sema &S, Decl *D,
  352. const AttributeCommonInfo &CI,
  353. bool PassesCheck, unsigned DiagID,
  354. DiagnosticArgs &&... ExtraArgs) {
  355. if (!PassesCheck) {
  356. Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
  357. appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
  358. return;
  359. }
  360. handleSimpleAttribute<AttrType>(S, D, CI);
  361. }
  362. /// Check if the passed-in expression is of type int or bool.
  363. static bool isIntOrBool(Expr *Exp) {
  364. QualType QT = Exp->getType();
  365. return QT->isBooleanType() || QT->isIntegerType();
  366. }
  367. // Check to see if the type is a smart pointer of some kind. We assume
  368. // it's a smart pointer if it defines both operator-> and operator*.
  369. static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
  370. auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
  371. OverloadedOperatorKind Op) {
  372. DeclContextLookupResult Result =
  373. Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op));
  374. return !Result.empty();
  375. };
  376. const RecordDecl *Record = RT->getDecl();
  377. bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
  378. bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
  379. if (foundStarOperator && foundArrowOperator)
  380. return true;
  381. const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
  382. if (!CXXRecord)
  383. return false;
  384. for (auto BaseSpecifier : CXXRecord->bases()) {
  385. if (!foundStarOperator)
  386. foundStarOperator = IsOverloadedOperatorPresent(
  387. BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
  388. if (!foundArrowOperator)
  389. foundArrowOperator = IsOverloadedOperatorPresent(
  390. BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
  391. }
  392. if (foundStarOperator && foundArrowOperator)
  393. return true;
  394. return false;
  395. }
  396. /// Check if passed in Decl is a pointer type.
  397. /// Note that this function may produce an error message.
  398. /// \return true if the Decl is a pointer type; false otherwise
  399. static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
  400. const ParsedAttr &AL) {
  401. const auto *VD = cast<ValueDecl>(D);
  402. QualType QT = VD->getType();
  403. if (QT->isAnyPointerType())
  404. return true;
  405. if (const auto *RT = QT->getAs<RecordType>()) {
  406. // If it's an incomplete type, it could be a smart pointer; skip it.
  407. // (We don't want to force template instantiation if we can avoid it,
  408. // since that would alter the order in which templates are instantiated.)
  409. if (RT->isIncompleteType())
  410. return true;
  411. if (threadSafetyCheckIsSmartPointer(S, RT))
  412. return true;
  413. }
  414. S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
  415. return false;
  416. }
  417. /// Checks that the passed in QualType either is of RecordType or points
  418. /// to RecordType. Returns the relevant RecordType, null if it does not exit.
  419. static const RecordType *getRecordType(QualType QT) {
  420. if (const auto *RT = QT->getAs<RecordType>())
  421. return RT;
  422. // Now check if we point to record type.
  423. if (const auto *PT = QT->getAs<PointerType>())
  424. return PT->getPointeeType()->getAs<RecordType>();
  425. return nullptr;
  426. }
  427. template <typename AttrType>
  428. static bool checkRecordDeclForAttr(const RecordDecl *RD) {
  429. // Check if the record itself has the attribute.
  430. if (RD->hasAttr<AttrType>())
  431. return true;
  432. // Else check if any base classes have the attribute.
  433. if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  434. if (!CRD->forallBases([](const CXXRecordDecl *Base) {
  435. return !Base->hasAttr<AttrType>();
  436. }))
  437. return true;
  438. }
  439. return false;
  440. }
  441. static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
  442. const RecordType *RT = getRecordType(Ty);
  443. if (!RT)
  444. return false;
  445. // Don't check for the capability if the class hasn't been defined yet.
  446. if (RT->isIncompleteType())
  447. return true;
  448. // Allow smart pointers to be used as capability objects.
  449. // FIXME -- Check the type that the smart pointer points to.
  450. if (threadSafetyCheckIsSmartPointer(S, RT))
  451. return true;
  452. return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
  453. }
  454. static bool checkTypedefTypeForCapability(QualType Ty) {
  455. const auto *TD = Ty->getAs<TypedefType>();
  456. if (!TD)
  457. return false;
  458. TypedefNameDecl *TN = TD->getDecl();
  459. if (!TN)
  460. return false;
  461. return TN->hasAttr<CapabilityAttr>();
  462. }
  463. static bool typeHasCapability(Sema &S, QualType Ty) {
  464. if (checkTypedefTypeForCapability(Ty))
  465. return true;
  466. if (checkRecordTypeForCapability(S, Ty))
  467. return true;
  468. return false;
  469. }
  470. static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
  471. // Capability expressions are simple expressions involving the boolean logic
  472. // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
  473. // a DeclRefExpr is found, its type should be checked to determine whether it
  474. // is a capability or not.
  475. if (const auto *E = dyn_cast<CastExpr>(Ex))
  476. return isCapabilityExpr(S, E->getSubExpr());
  477. else if (const auto *E = dyn_cast<ParenExpr>(Ex))
  478. return isCapabilityExpr(S, E->getSubExpr());
  479. else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
  480. if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
  481. E->getOpcode() == UO_Deref)
  482. return isCapabilityExpr(S, E->getSubExpr());
  483. return false;
  484. } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
  485. if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
  486. return isCapabilityExpr(S, E->getLHS()) &&
  487. isCapabilityExpr(S, E->getRHS());
  488. return false;
  489. }
  490. return typeHasCapability(S, Ex->getType());
  491. }
  492. /// Checks that all attribute arguments, starting from Sidx, resolve to
  493. /// a capability object.
  494. /// \param Sidx The attribute argument index to start checking with.
  495. /// \param ParamIdxOk Whether an argument can be indexing into a function
  496. /// parameter list.
  497. static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
  498. const ParsedAttr &AL,
  499. SmallVectorImpl<Expr *> &Args,
  500. unsigned Sidx = 0,
  501. bool ParamIdxOk = false) {
  502. if (Sidx == AL.getNumArgs()) {
  503. // If we don't have any capability arguments, the attribute implicitly
  504. // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
  505. // a non-static method, and that the class is a (scoped) capability.
  506. const auto *MD = dyn_cast<const CXXMethodDecl>(D);
  507. if (MD && !MD->isStatic()) {
  508. const CXXRecordDecl *RD = MD->getParent();
  509. // FIXME -- need to check this again on template instantiation
  510. if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
  511. !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
  512. S.Diag(AL.getLoc(),
  513. diag::warn_thread_attribute_not_on_capability_member)
  514. << AL << MD->getParent();
  515. } else {
  516. S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
  517. << AL;
  518. }
  519. }
  520. for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
  521. Expr *ArgExp = AL.getArgAsExpr(Idx);
  522. if (ArgExp->isTypeDependent()) {
  523. // FIXME -- need to check this again on template instantiation
  524. Args.push_back(ArgExp);
  525. continue;
  526. }
  527. if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
  528. if (StrLit->getLength() == 0 ||
  529. (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
  530. // Pass empty strings to the analyzer without warnings.
  531. // Treat "*" as the universal lock.
  532. Args.push_back(ArgExp);
  533. continue;
  534. }
  535. // We allow constant strings to be used as a placeholder for expressions
  536. // that are not valid C++ syntax, but warn that they are ignored.
  537. S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
  538. Args.push_back(ArgExp);
  539. continue;
  540. }
  541. QualType ArgTy = ArgExp->getType();
  542. // A pointer to member expression of the form &MyClass::mu is treated
  543. // specially -- we need to look at the type of the member.
  544. if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
  545. if (UOp->getOpcode() == UO_AddrOf)
  546. if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
  547. if (DRE->getDecl()->isCXXInstanceMember())
  548. ArgTy = DRE->getDecl()->getType();
  549. // First see if we can just cast to record type, or pointer to record type.
  550. const RecordType *RT = getRecordType(ArgTy);
  551. // Now check if we index into a record type function param.
  552. if(!RT && ParamIdxOk) {
  553. const auto *FD = dyn_cast<FunctionDecl>(D);
  554. const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
  555. if(FD && IL) {
  556. unsigned int NumParams = FD->getNumParams();
  557. llvm::APInt ArgValue = IL->getValue();
  558. uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
  559. uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
  560. if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
  561. S.Diag(AL.getLoc(),
  562. diag::err_attribute_argument_out_of_bounds_extra_info)
  563. << AL << Idx + 1 << NumParams;
  564. continue;
  565. }
  566. ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
  567. }
  568. }
  569. // If the type does not have a capability, see if the components of the
  570. // expression have capabilities. This allows for writing C code where the
  571. // capability may be on the type, and the expression is a capability
  572. // boolean logic expression. Eg) requires_capability(A || B && !C)
  573. if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
  574. S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
  575. << AL << ArgTy;
  576. Args.push_back(ArgExp);
  577. }
  578. }
  579. //===----------------------------------------------------------------------===//
  580. // Attribute Implementations
  581. //===----------------------------------------------------------------------===//
  582. static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  583. if (!threadSafetyCheckIsPointer(S, D, AL))
  584. return;
  585. D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL));
  586. }
  587. static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
  588. Expr *&Arg) {
  589. SmallVector<Expr *, 1> Args;
  590. // check that all arguments are lockable objects
  591. checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
  592. unsigned Size = Args.size();
  593. if (Size != 1)
  594. return false;
  595. Arg = Args[0];
  596. return true;
  597. }
  598. static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  599. Expr *Arg = nullptr;
  600. if (!checkGuardedByAttrCommon(S, D, AL, Arg))
  601. return;
  602. D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg));
  603. }
  604. static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  605. Expr *Arg = nullptr;
  606. if (!checkGuardedByAttrCommon(S, D, AL, Arg))
  607. return;
  608. if (!threadSafetyCheckIsPointer(S, D, AL))
  609. return;
  610. D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg));
  611. }
  612. static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
  613. SmallVectorImpl<Expr *> &Args) {
  614. if (!AL.checkAtLeastNumArgs(S, 1))
  615. return false;
  616. // Check that this attribute only applies to lockable types.
  617. QualType QT = cast<ValueDecl>(D)->getType();
  618. if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
  619. S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
  620. return false;
  621. }
  622. // Check that all arguments are lockable objects.
  623. checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
  624. if (Args.empty())
  625. return false;
  626. return true;
  627. }
  628. static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  629. SmallVector<Expr *, 1> Args;
  630. if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
  631. return;
  632. Expr **StartArg = &Args[0];
  633. D->addAttr(::new (S.Context)
  634. AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
  635. }
  636. static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  637. SmallVector<Expr *, 1> Args;
  638. if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
  639. return;
  640. Expr **StartArg = &Args[0];
  641. D->addAttr(::new (S.Context)
  642. AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
  643. }
  644. static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
  645. SmallVectorImpl<Expr *> &Args) {
  646. // zero or more arguments ok
  647. // check that all arguments are lockable objects
  648. checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
  649. return true;
  650. }
  651. static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  652. SmallVector<Expr *, 1> Args;
  653. if (!checkLockFunAttrCommon(S, D, AL, Args))
  654. return;
  655. unsigned Size = Args.size();
  656. Expr **StartArg = Size == 0 ? nullptr : &Args[0];
  657. D->addAttr(::new (S.Context)
  658. AssertSharedLockAttr(S.Context, AL, StartArg, Size));
  659. }
  660. static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
  661. const ParsedAttr &AL) {
  662. SmallVector<Expr *, 1> Args;
  663. if (!checkLockFunAttrCommon(S, D, AL, Args))
  664. return;
  665. unsigned Size = Args.size();
  666. Expr **StartArg = Size == 0 ? nullptr : &Args[0];
  667. D->addAttr(::new (S.Context)
  668. AssertExclusiveLockAttr(S.Context, AL, StartArg, Size));
  669. }
  670. /// Checks to be sure that the given parameter number is in bounds, and
  671. /// is an integral type. Will emit appropriate diagnostics if this returns
  672. /// false.
  673. ///
  674. /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
  675. template <typename AttrInfo>
  676. static bool checkParamIsIntegerType(Sema &S, const Decl *D, const AttrInfo &AI,
  677. unsigned AttrArgNo) {
  678. assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
  679. Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
  680. ParamIdx Idx;
  681. if (!checkFunctionOrMethodParameterIndex(S, D, AI, AttrArgNo + 1, AttrArg,
  682. Idx))
  683. return false;
  684. QualType ParamTy = getFunctionOrMethodParamType(D, Idx.getASTIndex());
  685. if (!ParamTy->isIntegerType() && !ParamTy->isCharType()) {
  686. SourceLocation SrcLoc = AttrArg->getBeginLoc();
  687. S.Diag(SrcLoc, diag::err_attribute_integers_only)
  688. << AI << getFunctionOrMethodParamRange(D, Idx.getASTIndex());
  689. return false;
  690. }
  691. return true;
  692. }
  693. static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  694. if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
  695. return;
  696. assert(isFunctionOrMethod(D) && hasFunctionProto(D));
  697. QualType RetTy = getFunctionOrMethodResultType(D);
  698. if (!RetTy->isPointerType()) {
  699. S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
  700. return;
  701. }
  702. const Expr *SizeExpr = AL.getArgAsExpr(0);
  703. int SizeArgNoVal;
  704. // Parameter indices are 1-indexed, hence Index=1
  705. if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1))
  706. return;
  707. if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/0))
  708. return;
  709. ParamIdx SizeArgNo(SizeArgNoVal, D);
  710. ParamIdx NumberArgNo;
  711. if (AL.getNumArgs() == 2) {
  712. const Expr *NumberExpr = AL.getArgAsExpr(1);
  713. int Val;
  714. // Parameter indices are 1-based, hence Index=2
  715. if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2))
  716. return;
  717. if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/1))
  718. return;
  719. NumberArgNo = ParamIdx(Val, D);
  720. }
  721. D->addAttr(::new (S.Context)
  722. AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
  723. }
  724. static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
  725. SmallVectorImpl<Expr *> &Args) {
  726. if (!AL.checkAtLeastNumArgs(S, 1))
  727. return false;
  728. if (!isIntOrBool(AL.getArgAsExpr(0))) {
  729. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  730. << AL << 1 << AANT_ArgumentIntOrBool;
  731. return false;
  732. }
  733. // check that all arguments are lockable objects
  734. checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
  735. return true;
  736. }
  737. static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
  738. const ParsedAttr &AL) {
  739. SmallVector<Expr*, 2> Args;
  740. if (!checkTryLockFunAttrCommon(S, D, AL, Args))
  741. return;
  742. D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
  743. S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
  744. }
  745. static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
  746. const ParsedAttr &AL) {
  747. SmallVector<Expr*, 2> Args;
  748. if (!checkTryLockFunAttrCommon(S, D, AL, Args))
  749. return;
  750. D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
  751. S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
  752. }
  753. static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  754. // check that the argument is lockable object
  755. SmallVector<Expr*, 1> Args;
  756. checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
  757. unsigned Size = Args.size();
  758. if (Size == 0)
  759. return;
  760. D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
  761. }
  762. static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  763. if (!AL.checkAtLeastNumArgs(S, 1))
  764. return;
  765. // check that all arguments are lockable objects
  766. SmallVector<Expr*, 1> Args;
  767. checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
  768. unsigned Size = Args.size();
  769. if (Size == 0)
  770. return;
  771. Expr **StartArg = &Args[0];
  772. D->addAttr(::new (S.Context)
  773. LocksExcludedAttr(S.Context, AL, StartArg, Size));
  774. }
  775. static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
  776. Expr *&Cond, StringRef &Msg) {
  777. Cond = AL.getArgAsExpr(0);
  778. if (!Cond->isTypeDependent()) {
  779. ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
  780. if (Converted.isInvalid())
  781. return false;
  782. Cond = Converted.get();
  783. }
  784. if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
  785. return false;
  786. if (Msg.empty())
  787. Msg = "<no message provided>";
  788. SmallVector<PartialDiagnosticAt, 8> Diags;
  789. if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
  790. !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
  791. Diags)) {
  792. S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
  793. for (const PartialDiagnosticAt &PDiag : Diags)
  794. S.Diag(PDiag.first, PDiag.second);
  795. return false;
  796. }
  797. return true;
  798. }
  799. static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  800. S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
  801. Expr *Cond;
  802. StringRef Msg;
  803. if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
  804. D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
  805. }
  806. static void handleErrorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  807. StringRef NewUserDiagnostic;
  808. if (!S.checkStringLiteralArgumentAttr(AL, 0, NewUserDiagnostic))
  809. return;
  810. if (ErrorAttr *EA = S.mergeErrorAttr(D, AL, NewUserDiagnostic))
  811. D->addAttr(EA);
  812. }
  813. namespace {
  814. /// Determines if a given Expr references any of the given function's
  815. /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
  816. class ArgumentDependenceChecker
  817. : public RecursiveASTVisitor<ArgumentDependenceChecker> {
  818. #ifndef NDEBUG
  819. const CXXRecordDecl *ClassType;
  820. #endif
  821. llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
  822. bool Result;
  823. public:
  824. ArgumentDependenceChecker(const FunctionDecl *FD) {
  825. #ifndef NDEBUG
  826. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  827. ClassType = MD->getParent();
  828. else
  829. ClassType = nullptr;
  830. #endif
  831. Parms.insert(FD->param_begin(), FD->param_end());
  832. }
  833. bool referencesArgs(Expr *E) {
  834. Result = false;
  835. TraverseStmt(E);
  836. return Result;
  837. }
  838. bool VisitCXXThisExpr(CXXThisExpr *E) {
  839. assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
  840. "`this` doesn't refer to the enclosing class?");
  841. Result = true;
  842. return false;
  843. }
  844. bool VisitDeclRefExpr(DeclRefExpr *DRE) {
  845. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  846. if (Parms.count(PVD)) {
  847. Result = true;
  848. return false;
  849. }
  850. return true;
  851. }
  852. };
  853. }
  854. static void handleDiagnoseAsBuiltinAttr(Sema &S, Decl *D,
  855. const ParsedAttr &AL) {
  856. const auto *DeclFD = cast<FunctionDecl>(D);
  857. if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclFD))
  858. if (!MethodDecl->isStatic()) {
  859. S.Diag(AL.getLoc(), diag::err_attribute_no_member_function) << AL;
  860. return;
  861. }
  862. auto DiagnoseType = [&](unsigned Index, AttributeArgumentNType T) {
  863. SourceLocation Loc = [&]() {
  864. auto Union = AL.getArg(Index - 1);
  865. if (Union.is<Expr *>())
  866. return Union.get<Expr *>()->getBeginLoc();
  867. return Union.get<IdentifierLoc *>()->Loc;
  868. }();
  869. S.Diag(Loc, diag::err_attribute_argument_n_type) << AL << Index << T;
  870. };
  871. FunctionDecl *AttrFD = [&]() -> FunctionDecl * {
  872. if (!AL.isArgExpr(0))
  873. return nullptr;
  874. auto *F = dyn_cast_or_null<DeclRefExpr>(AL.getArgAsExpr(0));
  875. if (!F)
  876. return nullptr;
  877. return dyn_cast_or_null<FunctionDecl>(F->getFoundDecl());
  878. }();
  879. if (!AttrFD || !AttrFD->getBuiltinID(true)) {
  880. DiagnoseType(1, AANT_ArgumentBuiltinFunction);
  881. return;
  882. }
  883. if (AttrFD->getNumParams() != AL.getNumArgs() - 1) {
  884. S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments_for)
  885. << AL << AttrFD << AttrFD->getNumParams();
  886. return;
  887. }
  888. SmallVector<unsigned, 8> Indices;
  889. for (unsigned I = 1; I < AL.getNumArgs(); ++I) {
  890. if (!AL.isArgExpr(I)) {
  891. DiagnoseType(I + 1, AANT_ArgumentIntegerConstant);
  892. return;
  893. }
  894. const Expr *IndexExpr = AL.getArgAsExpr(I);
  895. uint32_t Index;
  896. if (!checkUInt32Argument(S, AL, IndexExpr, Index, I + 1, false))
  897. return;
  898. if (Index > DeclFD->getNumParams()) {
  899. S.Diag(AL.getLoc(), diag::err_attribute_bounds_for_function)
  900. << AL << Index << DeclFD << DeclFD->getNumParams();
  901. return;
  902. }
  903. QualType T1 = AttrFD->getParamDecl(I - 1)->getType();
  904. QualType T2 = DeclFD->getParamDecl(Index - 1)->getType();
  905. if (T1.getCanonicalType().getUnqualifiedType() !=
  906. T2.getCanonicalType().getUnqualifiedType()) {
  907. S.Diag(IndexExpr->getBeginLoc(), diag::err_attribute_parameter_types)
  908. << AL << Index << DeclFD << T2 << I << AttrFD << T1;
  909. return;
  910. }
  911. Indices.push_back(Index - 1);
  912. }
  913. D->addAttr(::new (S.Context) DiagnoseAsBuiltinAttr(
  914. S.Context, AL, AttrFD, Indices.data(), Indices.size()));
  915. }
  916. static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  917. S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
  918. Expr *Cond;
  919. StringRef Msg;
  920. if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
  921. return;
  922. StringRef DiagTypeStr;
  923. if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
  924. return;
  925. DiagnoseIfAttr::DiagnosticType DiagType;
  926. if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
  927. S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
  928. diag::err_diagnose_if_invalid_diagnostic_type);
  929. return;
  930. }
  931. bool ArgDependent = false;
  932. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  933. ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
  934. D->addAttr(::new (S.Context) DiagnoseIfAttr(
  935. S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D)));
  936. }
  937. static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  938. static constexpr const StringRef kWildcard = "*";
  939. llvm::SmallVector<StringRef, 16> Names;
  940. bool HasWildcard = false;
  941. const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) {
  942. if (Name == kWildcard)
  943. HasWildcard = true;
  944. Names.push_back(Name);
  945. };
  946. // Add previously defined attributes.
  947. if (const auto *NBA = D->getAttr<NoBuiltinAttr>())
  948. for (StringRef BuiltinName : NBA->builtinNames())
  949. AddBuiltinName(BuiltinName);
  950. // Add current attributes.
  951. if (AL.getNumArgs() == 0)
  952. AddBuiltinName(kWildcard);
  953. else
  954. for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
  955. StringRef BuiltinName;
  956. SourceLocation LiteralLoc;
  957. if (!S.checkStringLiteralArgumentAttr(AL, I, BuiltinName, &LiteralLoc))
  958. return;
  959. if (Builtin::Context::isBuiltinFunc(BuiltinName))
  960. AddBuiltinName(BuiltinName);
  961. else
  962. S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name)
  963. << BuiltinName << AL;
  964. }
  965. // Repeating the same attribute is fine.
  966. llvm::sort(Names);
  967. Names.erase(std::unique(Names.begin(), Names.end()), Names.end());
  968. // Empty no_builtin must be on its own.
  969. if (HasWildcard && Names.size() > 1)
  970. S.Diag(D->getLocation(),
  971. diag::err_attribute_no_builtin_wildcard_or_builtin_name)
  972. << AL;
  973. if (D->hasAttr<NoBuiltinAttr>())
  974. D->dropAttr<NoBuiltinAttr>();
  975. D->addAttr(::new (S.Context)
  976. NoBuiltinAttr(S.Context, AL, Names.data(), Names.size()));
  977. }
  978. static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  979. if (D->hasAttr<PassObjectSizeAttr>()) {
  980. S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
  981. return;
  982. }
  983. Expr *E = AL.getArgAsExpr(0);
  984. uint32_t Type;
  985. if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
  986. return;
  987. // pass_object_size's argument is passed in as the second argument of
  988. // __builtin_object_size. So, it has the same constraints as that second
  989. // argument; namely, it must be in the range [0, 3].
  990. if (Type > 3) {
  991. S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
  992. << AL << 0 << 3 << E->getSourceRange();
  993. return;
  994. }
  995. // pass_object_size is only supported on constant pointer parameters; as a
  996. // kindness to users, we allow the parameter to be non-const for declarations.
  997. // At this point, we have no clue if `D` belongs to a function declaration or
  998. // definition, so we defer the constness check until later.
  999. if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
  1000. S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
  1001. return;
  1002. }
  1003. D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
  1004. }
  1005. static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1006. ConsumableAttr::ConsumedState DefaultState;
  1007. if (AL.isArgIdent(0)) {
  1008. IdentifierLoc *IL = AL.getArgAsIdent(0);
  1009. if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
  1010. DefaultState)) {
  1011. S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
  1012. << IL->Ident;
  1013. return;
  1014. }
  1015. } else {
  1016. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  1017. << AL << AANT_ArgumentIdentifier;
  1018. return;
  1019. }
  1020. D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
  1021. }
  1022. static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
  1023. const ParsedAttr &AL) {
  1024. QualType ThisType = MD->getThisType()->getPointeeType();
  1025. if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
  1026. if (!RD->hasAttr<ConsumableAttr>()) {
  1027. S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD;
  1028. return false;
  1029. }
  1030. }
  1031. return true;
  1032. }
  1033. static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1034. if (!AL.checkAtLeastNumArgs(S, 1))
  1035. return;
  1036. if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
  1037. return;
  1038. SmallVector<CallableWhenAttr::ConsumedState, 3> States;
  1039. for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
  1040. CallableWhenAttr::ConsumedState CallableState;
  1041. StringRef StateString;
  1042. SourceLocation Loc;
  1043. if (AL.isArgIdent(ArgIndex)) {
  1044. IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
  1045. StateString = Ident->Ident->getName();
  1046. Loc = Ident->Loc;
  1047. } else {
  1048. if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
  1049. return;
  1050. }
  1051. if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
  1052. CallableState)) {
  1053. S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
  1054. return;
  1055. }
  1056. States.push_back(CallableState);
  1057. }
  1058. D->addAttr(::new (S.Context)
  1059. CallableWhenAttr(S.Context, AL, States.data(), States.size()));
  1060. }
  1061. static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1062. ParamTypestateAttr::ConsumedState ParamState;
  1063. if (AL.isArgIdent(0)) {
  1064. IdentifierLoc *Ident = AL.getArgAsIdent(0);
  1065. StringRef StateString = Ident->Ident->getName();
  1066. if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
  1067. ParamState)) {
  1068. S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
  1069. << AL << StateString;
  1070. return;
  1071. }
  1072. } else {
  1073. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  1074. << AL << AANT_ArgumentIdentifier;
  1075. return;
  1076. }
  1077. // FIXME: This check is currently being done in the analysis. It can be
  1078. // enabled here only after the parser propagates attributes at
  1079. // template specialization definition, not declaration.
  1080. //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
  1081. //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
  1082. //
  1083. //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
  1084. // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
  1085. // ReturnType.getAsString();
  1086. // return;
  1087. //}
  1088. D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
  1089. }
  1090. static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1091. ReturnTypestateAttr::ConsumedState ReturnState;
  1092. if (AL.isArgIdent(0)) {
  1093. IdentifierLoc *IL = AL.getArgAsIdent(0);
  1094. if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
  1095. ReturnState)) {
  1096. S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
  1097. << IL->Ident;
  1098. return;
  1099. }
  1100. } else {
  1101. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  1102. << AL << AANT_ArgumentIdentifier;
  1103. return;
  1104. }
  1105. // FIXME: This check is currently being done in the analysis. It can be
  1106. // enabled here only after the parser propagates attributes at
  1107. // template specialization definition, not declaration.
  1108. //QualType ReturnType;
  1109. //
  1110. //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
  1111. // ReturnType = Param->getType();
  1112. //
  1113. //} else if (const CXXConstructorDecl *Constructor =
  1114. // dyn_cast<CXXConstructorDecl>(D)) {
  1115. // ReturnType = Constructor->getThisType()->getPointeeType();
  1116. //
  1117. //} else {
  1118. //
  1119. // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
  1120. //}
  1121. //
  1122. //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
  1123. //
  1124. //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
  1125. // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
  1126. // ReturnType.getAsString();
  1127. // return;
  1128. //}
  1129. D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
  1130. }
  1131. static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1132. if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
  1133. return;
  1134. SetTypestateAttr::ConsumedState NewState;
  1135. if (AL.isArgIdent(0)) {
  1136. IdentifierLoc *Ident = AL.getArgAsIdent(0);
  1137. StringRef Param = Ident->Ident->getName();
  1138. if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
  1139. S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
  1140. << Param;
  1141. return;
  1142. }
  1143. } else {
  1144. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  1145. << AL << AANT_ArgumentIdentifier;
  1146. return;
  1147. }
  1148. D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
  1149. }
  1150. static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1151. if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
  1152. return;
  1153. TestTypestateAttr::ConsumedState TestState;
  1154. if (AL.isArgIdent(0)) {
  1155. IdentifierLoc *Ident = AL.getArgAsIdent(0);
  1156. StringRef Param = Ident->Ident->getName();
  1157. if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
  1158. S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
  1159. << Param;
  1160. return;
  1161. }
  1162. } else {
  1163. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  1164. << AL << AANT_ArgumentIdentifier;
  1165. return;
  1166. }
  1167. D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
  1168. }
  1169. static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1170. // Remember this typedef decl, we will need it later for diagnostics.
  1171. S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
  1172. }
  1173. static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1174. if (auto *TD = dyn_cast<TagDecl>(D))
  1175. TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
  1176. else if (auto *FD = dyn_cast<FieldDecl>(D)) {
  1177. bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
  1178. !FD->getType()->isIncompleteType() &&
  1179. FD->isBitField() &&
  1180. S.Context.getTypeAlign(FD->getType()) <= 8);
  1181. if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
  1182. if (BitfieldByteAligned)
  1183. // The PS4 target needs to maintain ABI backwards compatibility.
  1184. S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
  1185. << AL << FD->getType();
  1186. else
  1187. FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
  1188. } else {
  1189. // Report warning about changed offset in the newer compiler versions.
  1190. if (BitfieldByteAligned)
  1191. S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
  1192. FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
  1193. }
  1194. } else
  1195. S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
  1196. }
  1197. static void handlePreferredName(Sema &S, Decl *D, const ParsedAttr &AL) {
  1198. auto *RD = cast<CXXRecordDecl>(D);
  1199. ClassTemplateDecl *CTD = RD->getDescribedClassTemplate();
  1200. assert(CTD && "attribute does not appertain to this declaration");
  1201. ParsedType PT = AL.getTypeArg();
  1202. TypeSourceInfo *TSI = nullptr;
  1203. QualType T = S.GetTypeFromParser(PT, &TSI);
  1204. if (!TSI)
  1205. TSI = S.Context.getTrivialTypeSourceInfo(T, AL.getLoc());
  1206. if (!T.hasQualifiers() && T->isTypedefNameType()) {
  1207. // Find the template name, if this type names a template specialization.
  1208. const TemplateDecl *Template = nullptr;
  1209. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  1210. T->getAsCXXRecordDecl())) {
  1211. Template = CTSD->getSpecializedTemplate();
  1212. } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
  1213. while (TST && TST->isTypeAlias())
  1214. TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
  1215. if (TST)
  1216. Template = TST->getTemplateName().getAsTemplateDecl();
  1217. }
  1218. if (Template && declaresSameEntity(Template, CTD)) {
  1219. D->addAttr(::new (S.Context) PreferredNameAttr(S.Context, AL, TSI));
  1220. return;
  1221. }
  1222. }
  1223. S.Diag(AL.getLoc(), diag::err_attribute_preferred_name_arg_invalid)
  1224. << T << CTD;
  1225. if (const auto *TT = T->getAs<TypedefType>())
  1226. S.Diag(TT->getDecl()->getLocation(), diag::note_entity_declared_at)
  1227. << TT->getDecl();
  1228. }
  1229. static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
  1230. // The IBOutlet/IBOutletCollection attributes only apply to instance
  1231. // variables or properties of Objective-C classes. The outlet must also
  1232. // have an object reference type.
  1233. if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
  1234. if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
  1235. S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
  1236. << AL << VD->getType() << 0;
  1237. return false;
  1238. }
  1239. }
  1240. else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
  1241. if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
  1242. S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
  1243. << AL << PD->getType() << 1;
  1244. return false;
  1245. }
  1246. }
  1247. else {
  1248. S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
  1249. return false;
  1250. }
  1251. return true;
  1252. }
  1253. static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
  1254. if (!checkIBOutletCommon(S, D, AL))
  1255. return;
  1256. D->addAttr(::new (S.Context) IBOutletAttr(S.Context, AL));
  1257. }
  1258. static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
  1259. // The iboutletcollection attribute can have zero or one arguments.
  1260. if (AL.getNumArgs() > 1) {
  1261. S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
  1262. return;
  1263. }
  1264. if (!checkIBOutletCommon(S, D, AL))
  1265. return;
  1266. ParsedType PT;
  1267. if (AL.hasParsedType())
  1268. PT = AL.getTypeArg();
  1269. else {
  1270. PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
  1271. S.getScopeForContext(D->getDeclContext()->getParent()));
  1272. if (!PT) {
  1273. S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
  1274. return;
  1275. }
  1276. }
  1277. TypeSourceInfo *QTLoc = nullptr;
  1278. QualType QT = S.GetTypeFromParser(PT, &QTLoc);
  1279. if (!QTLoc)
  1280. QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
  1281. // Diagnose use of non-object type in iboutletcollection attribute.
  1282. // FIXME. Gnu attribute extension ignores use of builtin types in
  1283. // attributes. So, __attribute__((iboutletcollection(char))) will be
  1284. // treated as __attribute__((iboutletcollection())).
  1285. if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
  1286. S.Diag(AL.getLoc(),
  1287. QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
  1288. : diag::err_iboutletcollection_type) << QT;
  1289. return;
  1290. }
  1291. D->addAttr(::new (S.Context) IBOutletCollectionAttr(S.Context, AL, QTLoc));
  1292. }
  1293. bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
  1294. if (RefOkay) {
  1295. if (T->isReferenceType())
  1296. return true;
  1297. } else {
  1298. T = T.getNonReferenceType();
  1299. }
  1300. // The nonnull attribute, and other similar attributes, can be applied to a
  1301. // transparent union that contains a pointer type.
  1302. if (const RecordType *UT = T->getAsUnionType()) {
  1303. if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
  1304. RecordDecl *UD = UT->getDecl();
  1305. for (const auto *I : UD->fields()) {
  1306. QualType QT = I->getType();
  1307. if (QT->isAnyPointerType() || QT->isBlockPointerType())
  1308. return true;
  1309. }
  1310. }
  1311. }
  1312. return T->isAnyPointerType() || T->isBlockPointerType();
  1313. }
  1314. static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
  1315. SourceRange AttrParmRange,
  1316. SourceRange TypeRange,
  1317. bool isReturnValue = false) {
  1318. if (!S.isValidPointerAttrType(T)) {
  1319. if (isReturnValue)
  1320. S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
  1321. << AL << AttrParmRange << TypeRange;
  1322. else
  1323. S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
  1324. << AL << AttrParmRange << TypeRange << 0;
  1325. return false;
  1326. }
  1327. return true;
  1328. }
  1329. static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1330. SmallVector<ParamIdx, 8> NonNullArgs;
  1331. for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
  1332. Expr *Ex = AL.getArgAsExpr(I);
  1333. ParamIdx Idx;
  1334. if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
  1335. return;
  1336. // Is the function argument a pointer type?
  1337. if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
  1338. !attrNonNullArgCheck(
  1339. S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
  1340. Ex->getSourceRange(),
  1341. getFunctionOrMethodParamRange(D, Idx.getASTIndex())))
  1342. continue;
  1343. NonNullArgs.push_back(Idx);
  1344. }
  1345. // If no arguments were specified to __attribute__((nonnull)) then all pointer
  1346. // arguments have a nonnull attribute; warn if there aren't any. Skip this
  1347. // check if the attribute came from a macro expansion or a template
  1348. // instantiation.
  1349. if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
  1350. !S.inTemplateInstantiation()) {
  1351. bool AnyPointers = isFunctionOrMethodVariadic(D);
  1352. for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
  1353. I != E && !AnyPointers; ++I) {
  1354. QualType T = getFunctionOrMethodParamType(D, I);
  1355. if (T->isDependentType() || S.isValidPointerAttrType(T))
  1356. AnyPointers = true;
  1357. }
  1358. if (!AnyPointers)
  1359. S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
  1360. }
  1361. ParamIdx *Start = NonNullArgs.data();
  1362. unsigned Size = NonNullArgs.size();
  1363. llvm::array_pod_sort(Start, Start + Size);
  1364. D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
  1365. }
  1366. static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
  1367. const ParsedAttr &AL) {
  1368. if (AL.getNumArgs() > 0) {
  1369. if (D->getFunctionType()) {
  1370. handleNonNullAttr(S, D, AL);
  1371. } else {
  1372. S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
  1373. << D->getSourceRange();
  1374. }
  1375. return;
  1376. }
  1377. // Is the argument a pointer type?
  1378. if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
  1379. D->getSourceRange()))
  1380. return;
  1381. D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
  1382. }
  1383. static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1384. QualType ResultType = getFunctionOrMethodResultType(D);
  1385. SourceRange SR = getFunctionOrMethodResultSourceRange(D);
  1386. if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
  1387. /* isReturnValue */ true))
  1388. return;
  1389. D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
  1390. }
  1391. static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1392. if (D->isInvalidDecl())
  1393. return;
  1394. // noescape only applies to pointer types.
  1395. QualType T = cast<ParmVarDecl>(D)->getType();
  1396. if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
  1397. S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
  1398. << AL << AL.getRange() << 0;
  1399. return;
  1400. }
  1401. D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL));
  1402. }
  1403. static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1404. Expr *E = AL.getArgAsExpr(0),
  1405. *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
  1406. S.AddAssumeAlignedAttr(D, AL, E, OE);
  1407. }
  1408. static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1409. S.AddAllocAlignAttr(D, AL, AL.getArgAsExpr(0));
  1410. }
  1411. void Sema::AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
  1412. Expr *OE) {
  1413. QualType ResultType = getFunctionOrMethodResultType(D);
  1414. SourceRange SR = getFunctionOrMethodResultSourceRange(D);
  1415. AssumeAlignedAttr TmpAttr(Context, CI, E, OE);
  1416. SourceLocation AttrLoc = TmpAttr.getLocation();
  1417. if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
  1418. Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
  1419. << &TmpAttr << TmpAttr.getRange() << SR;
  1420. return;
  1421. }
  1422. if (!E->isValueDependent()) {
  1423. Optional<llvm::APSInt> I = llvm::APSInt(64);
  1424. if (!(I = E->getIntegerConstantExpr(Context))) {
  1425. if (OE)
  1426. Diag(AttrLoc, diag::err_attribute_argument_n_type)
  1427. << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
  1428. << E->getSourceRange();
  1429. else
  1430. Diag(AttrLoc, diag::err_attribute_argument_type)
  1431. << &TmpAttr << AANT_ArgumentIntegerConstant
  1432. << E->getSourceRange();
  1433. return;
  1434. }
  1435. if (!I->isPowerOf2()) {
  1436. Diag(AttrLoc, diag::err_alignment_not_power_of_two)
  1437. << E->getSourceRange();
  1438. return;
  1439. }
  1440. if (*I > Sema::MaximumAlignment)
  1441. Diag(CI.getLoc(), diag::warn_assume_aligned_too_great)
  1442. << CI.getRange() << Sema::MaximumAlignment;
  1443. }
  1444. if (OE && !OE->isValueDependent() && !OE->isIntegerConstantExpr(Context)) {
  1445. Diag(AttrLoc, diag::err_attribute_argument_n_type)
  1446. << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
  1447. << OE->getSourceRange();
  1448. return;
  1449. }
  1450. D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
  1451. }
  1452. void Sema::AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
  1453. Expr *ParamExpr) {
  1454. QualType ResultType = getFunctionOrMethodResultType(D);
  1455. AllocAlignAttr TmpAttr(Context, CI, ParamIdx());
  1456. SourceLocation AttrLoc = CI.getLoc();
  1457. if (!ResultType->isDependentType() &&
  1458. !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
  1459. Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
  1460. << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
  1461. return;
  1462. }
  1463. ParamIdx Idx;
  1464. const auto *FuncDecl = cast<FunctionDecl>(D);
  1465. if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
  1466. /*AttrArgNum=*/1, ParamExpr, Idx))
  1467. return;
  1468. QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
  1469. if (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  1470. !Ty->isAlignValT()) {
  1471. Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
  1472. << &TmpAttr
  1473. << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
  1474. return;
  1475. }
  1476. D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx));
  1477. }
  1478. /// Check if \p AssumptionStr is a known assumption and warn if not.
  1479. static void checkAssumptionAttr(Sema &S, SourceLocation Loc,
  1480. StringRef AssumptionStr) {
  1481. if (llvm::KnownAssumptionStrings.count(AssumptionStr))
  1482. return;
  1483. unsigned BestEditDistance = 3;
  1484. StringRef Suggestion;
  1485. for (const auto &KnownAssumptionIt : llvm::KnownAssumptionStrings) {
  1486. unsigned EditDistance =
  1487. AssumptionStr.edit_distance(KnownAssumptionIt.getKey());
  1488. if (EditDistance < BestEditDistance) {
  1489. Suggestion = KnownAssumptionIt.getKey();
  1490. BestEditDistance = EditDistance;
  1491. }
  1492. }
  1493. if (!Suggestion.empty())
  1494. S.Diag(Loc, diag::warn_assume_attribute_string_unknown_suggested)
  1495. << AssumptionStr << Suggestion;
  1496. else
  1497. S.Diag(Loc, diag::warn_assume_attribute_string_unknown) << AssumptionStr;
  1498. }
  1499. static void handleAssumumptionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1500. // Handle the case where the attribute has a text message.
  1501. StringRef Str;
  1502. SourceLocation AttrStrLoc;
  1503. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &AttrStrLoc))
  1504. return;
  1505. checkAssumptionAttr(S, AttrStrLoc, Str);
  1506. D->addAttr(::new (S.Context) AssumptionAttr(S.Context, AL, Str));
  1507. }
  1508. /// Normalize the attribute, __foo__ becomes foo.
  1509. /// Returns true if normalization was applied.
  1510. static bool normalizeName(StringRef &AttrName) {
  1511. if (AttrName.size() > 4 && AttrName.startswith("__") &&
  1512. AttrName.endswith("__")) {
  1513. AttrName = AttrName.drop_front(2).drop_back(2);
  1514. return true;
  1515. }
  1516. return false;
  1517. }
  1518. static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1519. // This attribute must be applied to a function declaration. The first
  1520. // argument to the attribute must be an identifier, the name of the resource,
  1521. // for example: malloc. The following arguments must be argument indexes, the
  1522. // arguments must be of integer type for Returns, otherwise of pointer type.
  1523. // The difference between Holds and Takes is that a pointer may still be used
  1524. // after being held. free() should be __attribute((ownership_takes)), whereas
  1525. // a list append function may well be __attribute((ownership_holds)).
  1526. if (!AL.isArgIdent(0)) {
  1527. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  1528. << AL << 1 << AANT_ArgumentIdentifier;
  1529. return;
  1530. }
  1531. // Figure out our Kind.
  1532. OwnershipAttr::OwnershipKind K =
  1533. OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
  1534. // Check arguments.
  1535. switch (K) {
  1536. case OwnershipAttr::Takes:
  1537. case OwnershipAttr::Holds:
  1538. if (AL.getNumArgs() < 2) {
  1539. S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
  1540. return;
  1541. }
  1542. break;
  1543. case OwnershipAttr::Returns:
  1544. if (AL.getNumArgs() > 2) {
  1545. S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
  1546. return;
  1547. }
  1548. break;
  1549. }
  1550. IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
  1551. StringRef ModuleName = Module->getName();
  1552. if (normalizeName(ModuleName)) {
  1553. Module = &S.PP.getIdentifierTable().get(ModuleName);
  1554. }
  1555. SmallVector<ParamIdx, 8> OwnershipArgs;
  1556. for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
  1557. Expr *Ex = AL.getArgAsExpr(i);
  1558. ParamIdx Idx;
  1559. if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
  1560. return;
  1561. // Is the function argument a pointer type?
  1562. QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex());
  1563. int Err = -1; // No error
  1564. switch (K) {
  1565. case OwnershipAttr::Takes:
  1566. case OwnershipAttr::Holds:
  1567. if (!T->isAnyPointerType() && !T->isBlockPointerType())
  1568. Err = 0;
  1569. break;
  1570. case OwnershipAttr::Returns:
  1571. if (!T->isIntegerType())
  1572. Err = 1;
  1573. break;
  1574. }
  1575. if (-1 != Err) {
  1576. S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
  1577. << Ex->getSourceRange();
  1578. return;
  1579. }
  1580. // Check we don't have a conflict with another ownership attribute.
  1581. for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
  1582. // Cannot have two ownership attributes of different kinds for the same
  1583. // index.
  1584. if (I->getOwnKind() != K && I->args_end() !=
  1585. std::find(I->args_begin(), I->args_end(), Idx)) {
  1586. S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I;
  1587. return;
  1588. } else if (K == OwnershipAttr::Returns &&
  1589. I->getOwnKind() == OwnershipAttr::Returns) {
  1590. // A returns attribute conflicts with any other returns attribute using
  1591. // a different index.
  1592. if (!llvm::is_contained(I->args(), Idx)) {
  1593. S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
  1594. << I->args_begin()->getSourceIndex();
  1595. if (I->args_size())
  1596. S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
  1597. << Idx.getSourceIndex() << Ex->getSourceRange();
  1598. return;
  1599. }
  1600. }
  1601. }
  1602. OwnershipArgs.push_back(Idx);
  1603. }
  1604. ParamIdx *Start = OwnershipArgs.data();
  1605. unsigned Size = OwnershipArgs.size();
  1606. llvm::array_pod_sort(Start, Start + Size);
  1607. D->addAttr(::new (S.Context)
  1608. OwnershipAttr(S.Context, AL, Module, Start, Size));
  1609. }
  1610. static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1611. // Check the attribute arguments.
  1612. if (AL.getNumArgs() > 1) {
  1613. S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
  1614. return;
  1615. }
  1616. // gcc rejects
  1617. // class c {
  1618. // static int a __attribute__((weakref ("v2")));
  1619. // static int b() __attribute__((weakref ("f3")));
  1620. // };
  1621. // and ignores the attributes of
  1622. // void f(void) {
  1623. // static int a __attribute__((weakref ("v2")));
  1624. // }
  1625. // we reject them
  1626. const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
  1627. if (!Ctx->isFileContext()) {
  1628. S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
  1629. << cast<NamedDecl>(D);
  1630. return;
  1631. }
  1632. // The GCC manual says
  1633. //
  1634. // At present, a declaration to which `weakref' is attached can only
  1635. // be `static'.
  1636. //
  1637. // It also says
  1638. //
  1639. // Without a TARGET,
  1640. // given as an argument to `weakref' or to `alias', `weakref' is
  1641. // equivalent to `weak'.
  1642. //
  1643. // gcc 4.4.1 will accept
  1644. // int a7 __attribute__((weakref));
  1645. // as
  1646. // int a7 __attribute__((weak));
  1647. // This looks like a bug in gcc. We reject that for now. We should revisit
  1648. // it if this behaviour is actually used.
  1649. // GCC rejects
  1650. // static ((alias ("y"), weakref)).
  1651. // Should we? How to check that weakref is before or after alias?
  1652. // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
  1653. // of transforming it into an AliasAttr. The WeakRefAttr never uses the
  1654. // StringRef parameter it was given anyway.
  1655. StringRef Str;
  1656. if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
  1657. // GCC will accept anything as the argument of weakref. Should we
  1658. // check for an existing decl?
  1659. D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
  1660. D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
  1661. }
  1662. static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1663. StringRef Str;
  1664. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
  1665. return;
  1666. // Aliases should be on declarations, not definitions.
  1667. const auto *FD = cast<FunctionDecl>(D);
  1668. if (FD->isThisDeclarationADefinition()) {
  1669. S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
  1670. return;
  1671. }
  1672. D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
  1673. }
  1674. static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1675. StringRef Str;
  1676. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
  1677. return;
  1678. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  1679. S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
  1680. return;
  1681. }
  1682. if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
  1683. S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
  1684. }
  1685. // Aliases should be on declarations, not definitions.
  1686. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  1687. if (FD->isThisDeclarationADefinition()) {
  1688. S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
  1689. return;
  1690. }
  1691. } else {
  1692. const auto *VD = cast<VarDecl>(D);
  1693. if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
  1694. S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
  1695. return;
  1696. }
  1697. }
  1698. // Mark target used to prevent unneeded-internal-declaration warnings.
  1699. if (!S.LangOpts.CPlusPlus) {
  1700. // FIXME: demangle Str for C++, as the attribute refers to the mangled
  1701. // linkage name, not the pre-mangled identifier.
  1702. const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
  1703. LookupResult LR(S, target, Sema::LookupOrdinaryName);
  1704. if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
  1705. for (NamedDecl *ND : LR)
  1706. ND->markUsed(S.Context);
  1707. }
  1708. D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
  1709. }
  1710. static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1711. StringRef Model;
  1712. SourceLocation LiteralLoc;
  1713. // Check that it is a string.
  1714. if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
  1715. return;
  1716. // Check that the value.
  1717. if (Model != "global-dynamic" && Model != "local-dynamic"
  1718. && Model != "initial-exec" && Model != "local-exec") {
  1719. S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
  1720. return;
  1721. }
  1722. if (S.Context.getTargetInfo().getTriple().isOSAIX() &&
  1723. Model != "global-dynamic") {
  1724. S.Diag(LiteralLoc, diag::err_aix_attr_unsupported_tls_model) << Model;
  1725. return;
  1726. }
  1727. D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model));
  1728. }
  1729. static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1730. QualType ResultType = getFunctionOrMethodResultType(D);
  1731. if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
  1732. D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
  1733. return;
  1734. }
  1735. S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
  1736. << AL << getFunctionOrMethodResultSourceRange(D);
  1737. }
  1738. static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1739. // Ensure we don't combine these with themselves, since that causes some
  1740. // confusing behavior.
  1741. if (AL.getParsedKind() == ParsedAttr::AT_CPUDispatch) {
  1742. if (checkAttrMutualExclusion<CPUSpecificAttr>(S, D, AL))
  1743. return;
  1744. if (const auto *Other = D->getAttr<CPUDispatchAttr>()) {
  1745. S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
  1746. S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
  1747. return;
  1748. }
  1749. } else if (AL.getParsedKind() == ParsedAttr::AT_CPUSpecific) {
  1750. if (checkAttrMutualExclusion<CPUDispatchAttr>(S, D, AL))
  1751. return;
  1752. if (const auto *Other = D->getAttr<CPUSpecificAttr>()) {
  1753. S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
  1754. S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
  1755. return;
  1756. }
  1757. }
  1758. FunctionDecl *FD = cast<FunctionDecl>(D);
  1759. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  1760. if (MD->getParent()->isLambda()) {
  1761. S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
  1762. return;
  1763. }
  1764. }
  1765. if (!AL.checkAtLeastNumArgs(S, 1))
  1766. return;
  1767. SmallVector<IdentifierInfo *, 8> CPUs;
  1768. for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
  1769. if (!AL.isArgIdent(ArgNo)) {
  1770. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  1771. << AL << AANT_ArgumentIdentifier;
  1772. return;
  1773. }
  1774. IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
  1775. StringRef CPUName = CPUArg->Ident->getName().trim();
  1776. if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName)) {
  1777. S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
  1778. << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
  1779. return;
  1780. }
  1781. const TargetInfo &Target = S.Context.getTargetInfo();
  1782. if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
  1783. return Target.CPUSpecificManglingCharacter(CPUName) ==
  1784. Target.CPUSpecificManglingCharacter(Cur->getName());
  1785. })) {
  1786. S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
  1787. return;
  1788. }
  1789. CPUs.push_back(CPUArg->Ident);
  1790. }
  1791. FD->setIsMultiVersion(true);
  1792. if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
  1793. D->addAttr(::new (S.Context)
  1794. CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
  1795. else
  1796. D->addAttr(::new (S.Context)
  1797. CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
  1798. }
  1799. static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1800. if (S.LangOpts.CPlusPlus) {
  1801. S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
  1802. << AL << AttributeLangSupport::Cpp;
  1803. return;
  1804. }
  1805. D->addAttr(::new (S.Context) CommonAttr(S.Context, AL));
  1806. }
  1807. static void handleCmseNSEntryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1808. if (S.LangOpts.CPlusPlus && !D->getDeclContext()->isExternCContext()) {
  1809. S.Diag(AL.getLoc(), diag::err_attribute_not_clinkage) << AL;
  1810. return;
  1811. }
  1812. const auto *FD = cast<FunctionDecl>(D);
  1813. if (!FD->isExternallyVisible()) {
  1814. S.Diag(AL.getLoc(), diag::warn_attribute_cmse_entry_static);
  1815. return;
  1816. }
  1817. D->addAttr(::new (S.Context) CmseNSEntryAttr(S.Context, AL));
  1818. }
  1819. static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1820. if (AL.isDeclspecAttribute()) {
  1821. const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
  1822. const auto &Arch = Triple.getArch();
  1823. if (Arch != llvm::Triple::x86 &&
  1824. (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
  1825. S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
  1826. << AL << Triple.getArchName();
  1827. return;
  1828. }
  1829. }
  1830. D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
  1831. }
  1832. static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
  1833. if (hasDeclarator(D)) return;
  1834. if (!isa<ObjCMethodDecl>(D)) {
  1835. S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
  1836. << Attrs << ExpectedFunctionOrMethod;
  1837. return;
  1838. }
  1839. D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
  1840. }
  1841. static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
  1842. if (!S.getLangOpts().CFProtectionBranch)
  1843. S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
  1844. else
  1845. handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
  1846. }
  1847. bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
  1848. if (!Attrs.checkExactlyNumArgs(*this, 0)) {
  1849. Attrs.setInvalid();
  1850. return true;
  1851. }
  1852. return false;
  1853. }
  1854. bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
  1855. // Check whether the attribute is valid on the current target.
  1856. if (!AL.existsInTarget(Context.getTargetInfo())) {
  1857. Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
  1858. << AL << AL.getRange();
  1859. AL.setInvalid();
  1860. return true;
  1861. }
  1862. return false;
  1863. }
  1864. static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1865. // The checking path for 'noreturn' and 'analyzer_noreturn' are different
  1866. // because 'analyzer_noreturn' does not impact the type.
  1867. if (!isFunctionOrMethodOrBlock(D)) {
  1868. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  1869. if (!VD || (!VD->getType()->isBlockPointerType() &&
  1870. !VD->getType()->isFunctionPointerType())) {
  1871. S.Diag(AL.getLoc(), AL.isStandardAttributeSyntax()
  1872. ? diag::err_attribute_wrong_decl_type
  1873. : diag::warn_attribute_wrong_decl_type)
  1874. << AL << ExpectedFunctionMethodOrBlock;
  1875. return;
  1876. }
  1877. }
  1878. D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
  1879. }
  1880. // PS3 PPU-specific.
  1881. static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1882. /*
  1883. Returning a Vector Class in Registers
  1884. According to the PPU ABI specifications, a class with a single member of
  1885. vector type is returned in memory when used as the return value of a
  1886. function.
  1887. This results in inefficient code when implementing vector classes. To return
  1888. the value in a single vector register, add the vecreturn attribute to the
  1889. class definition. This attribute is also applicable to struct types.
  1890. Example:
  1891. struct Vector
  1892. {
  1893. __vector float xyzw;
  1894. } __attribute__((vecreturn));
  1895. Vector Add(Vector lhs, Vector rhs)
  1896. {
  1897. Vector result;
  1898. result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
  1899. return result; // This will be returned in a register
  1900. }
  1901. */
  1902. if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
  1903. S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
  1904. return;
  1905. }
  1906. const auto *R = cast<RecordDecl>(D);
  1907. int count = 0;
  1908. if (!isa<CXXRecordDecl>(R)) {
  1909. S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
  1910. return;
  1911. }
  1912. if (!cast<CXXRecordDecl>(R)->isPOD()) {
  1913. S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
  1914. return;
  1915. }
  1916. for (const auto *I : R->fields()) {
  1917. if ((count == 1) || !I->getType()->isVectorType()) {
  1918. S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
  1919. return;
  1920. }
  1921. count++;
  1922. }
  1923. D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
  1924. }
  1925. static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
  1926. const ParsedAttr &AL) {
  1927. if (isa<ParmVarDecl>(D)) {
  1928. // [[carries_dependency]] can only be applied to a parameter if it is a
  1929. // parameter of a function declaration or lambda.
  1930. if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
  1931. S.Diag(AL.getLoc(),
  1932. diag::err_carries_dependency_param_not_function_decl);
  1933. return;
  1934. }
  1935. }
  1936. D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
  1937. }
  1938. static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1939. bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
  1940. // If this is spelled as the standard C++17 attribute, but not in C++17, warn
  1941. // about using it as an extension.
  1942. if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
  1943. S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
  1944. D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
  1945. }
  1946. static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1947. uint32_t priority = ConstructorAttr::DefaultPriority;
  1948. if (AL.getNumArgs() &&
  1949. !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
  1950. return;
  1951. D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
  1952. }
  1953. static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1954. uint32_t priority = DestructorAttr::DefaultPriority;
  1955. if (AL.getNumArgs() &&
  1956. !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
  1957. return;
  1958. D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
  1959. }
  1960. template <typename AttrTy>
  1961. static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
  1962. // Handle the case where the attribute has a text message.
  1963. StringRef Str;
  1964. if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
  1965. return;
  1966. D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str));
  1967. }
  1968. static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
  1969. const ParsedAttr &AL) {
  1970. if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
  1971. S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
  1972. << AL << AL.getRange();
  1973. return;
  1974. }
  1975. D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL));
  1976. }
  1977. static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
  1978. IdentifierInfo *Platform,
  1979. VersionTuple Introduced,
  1980. VersionTuple Deprecated,
  1981. VersionTuple Obsoleted) {
  1982. StringRef PlatformName
  1983. = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
  1984. if (PlatformName.empty())
  1985. PlatformName = Platform->getName();
  1986. // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
  1987. // of these steps are needed).
  1988. if (!Introduced.empty() && !Deprecated.empty() &&
  1989. !(Introduced <= Deprecated)) {
  1990. S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
  1991. << 1 << PlatformName << Deprecated.getAsString()
  1992. << 0 << Introduced.getAsString();
  1993. return true;
  1994. }
  1995. if (!Introduced.empty() && !Obsoleted.empty() &&
  1996. !(Introduced <= Obsoleted)) {
  1997. S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
  1998. << 2 << PlatformName << Obsoleted.getAsString()
  1999. << 0 << Introduced.getAsString();
  2000. return true;
  2001. }
  2002. if (!Deprecated.empty() && !Obsoleted.empty() &&
  2003. !(Deprecated <= Obsoleted)) {
  2004. S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
  2005. << 2 << PlatformName << Obsoleted.getAsString()
  2006. << 1 << Deprecated.getAsString();
  2007. return true;
  2008. }
  2009. return false;
  2010. }
  2011. /// Check whether the two versions match.
  2012. ///
  2013. /// If either version tuple is empty, then they are assumed to match. If
  2014. /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
  2015. static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
  2016. bool BeforeIsOkay) {
  2017. if (X.empty() || Y.empty())
  2018. return true;
  2019. if (X == Y)
  2020. return true;
  2021. if (BeforeIsOkay && X < Y)
  2022. return true;
  2023. return false;
  2024. }
  2025. AvailabilityAttr *Sema::mergeAvailabilityAttr(
  2026. NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
  2027. bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
  2028. VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
  2029. bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
  2030. int Priority) {
  2031. VersionTuple MergedIntroduced = Introduced;
  2032. VersionTuple MergedDeprecated = Deprecated;
  2033. VersionTuple MergedObsoleted = Obsoleted;
  2034. bool FoundAny = false;
  2035. bool OverrideOrImpl = false;
  2036. switch (AMK) {
  2037. case AMK_None:
  2038. case AMK_Redeclaration:
  2039. OverrideOrImpl = false;
  2040. break;
  2041. case AMK_Override:
  2042. case AMK_ProtocolImplementation:
  2043. case AMK_OptionalProtocolImplementation:
  2044. OverrideOrImpl = true;
  2045. break;
  2046. }
  2047. if (D->hasAttrs()) {
  2048. AttrVec &Attrs = D->getAttrs();
  2049. for (unsigned i = 0, e = Attrs.size(); i != e;) {
  2050. const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
  2051. if (!OldAA) {
  2052. ++i;
  2053. continue;
  2054. }
  2055. IdentifierInfo *OldPlatform = OldAA->getPlatform();
  2056. if (OldPlatform != Platform) {
  2057. ++i;
  2058. continue;
  2059. }
  2060. // If there is an existing availability attribute for this platform that
  2061. // has a lower priority use the existing one and discard the new
  2062. // attribute.
  2063. if (OldAA->getPriority() < Priority)
  2064. return nullptr;
  2065. // If there is an existing attribute for this platform that has a higher
  2066. // priority than the new attribute then erase the old one and continue
  2067. // processing the attributes.
  2068. if (OldAA->getPriority() > Priority) {
  2069. Attrs.erase(Attrs.begin() + i);
  2070. --e;
  2071. continue;
  2072. }
  2073. FoundAny = true;
  2074. VersionTuple OldIntroduced = OldAA->getIntroduced();
  2075. VersionTuple OldDeprecated = OldAA->getDeprecated();
  2076. VersionTuple OldObsoleted = OldAA->getObsoleted();
  2077. bool OldIsUnavailable = OldAA->getUnavailable();
  2078. if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
  2079. !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
  2080. !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
  2081. !(OldIsUnavailable == IsUnavailable ||
  2082. (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
  2083. if (OverrideOrImpl) {
  2084. int Which = -1;
  2085. VersionTuple FirstVersion;
  2086. VersionTuple SecondVersion;
  2087. if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
  2088. Which = 0;
  2089. FirstVersion = OldIntroduced;
  2090. SecondVersion = Introduced;
  2091. } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
  2092. Which = 1;
  2093. FirstVersion = Deprecated;
  2094. SecondVersion = OldDeprecated;
  2095. } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
  2096. Which = 2;
  2097. FirstVersion = Obsoleted;
  2098. SecondVersion = OldObsoleted;
  2099. }
  2100. if (Which == -1) {
  2101. Diag(OldAA->getLocation(),
  2102. diag::warn_mismatched_availability_override_unavail)
  2103. << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
  2104. << (AMK == AMK_Override);
  2105. } else if (Which != 1 && AMK == AMK_OptionalProtocolImplementation) {
  2106. // Allow different 'introduced' / 'obsoleted' availability versions
  2107. // on a method that implements an optional protocol requirement. It
  2108. // makes less sense to allow this for 'deprecated' as the user can't
  2109. // see if the method is 'deprecated' as 'respondsToSelector' will
  2110. // still return true when the method is deprecated.
  2111. ++i;
  2112. continue;
  2113. } else {
  2114. Diag(OldAA->getLocation(),
  2115. diag::warn_mismatched_availability_override)
  2116. << Which
  2117. << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
  2118. << FirstVersion.getAsString() << SecondVersion.getAsString()
  2119. << (AMK == AMK_Override);
  2120. }
  2121. if (AMK == AMK_Override)
  2122. Diag(CI.getLoc(), diag::note_overridden_method);
  2123. else
  2124. Diag(CI.getLoc(), diag::note_protocol_method);
  2125. } else {
  2126. Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
  2127. Diag(CI.getLoc(), diag::note_previous_attribute);
  2128. }
  2129. Attrs.erase(Attrs.begin() + i);
  2130. --e;
  2131. continue;
  2132. }
  2133. VersionTuple MergedIntroduced2 = MergedIntroduced;
  2134. VersionTuple MergedDeprecated2 = MergedDeprecated;
  2135. VersionTuple MergedObsoleted2 = MergedObsoleted;
  2136. if (MergedIntroduced2.empty())
  2137. MergedIntroduced2 = OldIntroduced;
  2138. if (MergedDeprecated2.empty())
  2139. MergedDeprecated2 = OldDeprecated;
  2140. if (MergedObsoleted2.empty())
  2141. MergedObsoleted2 = OldObsoleted;
  2142. if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
  2143. MergedIntroduced2, MergedDeprecated2,
  2144. MergedObsoleted2)) {
  2145. Attrs.erase(Attrs.begin() + i);
  2146. --e;
  2147. continue;
  2148. }
  2149. MergedIntroduced = MergedIntroduced2;
  2150. MergedDeprecated = MergedDeprecated2;
  2151. MergedObsoleted = MergedObsoleted2;
  2152. ++i;
  2153. }
  2154. }
  2155. if (FoundAny &&
  2156. MergedIntroduced == Introduced &&
  2157. MergedDeprecated == Deprecated &&
  2158. MergedObsoleted == Obsoleted)
  2159. return nullptr;
  2160. // Only create a new attribute if !OverrideOrImpl, but we want to do
  2161. // the checking.
  2162. if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced,
  2163. MergedDeprecated, MergedObsoleted) &&
  2164. !OverrideOrImpl) {
  2165. auto *Avail = ::new (Context) AvailabilityAttr(
  2166. Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
  2167. Message, IsStrict, Replacement, Priority);
  2168. Avail->setImplicit(Implicit);
  2169. return Avail;
  2170. }
  2171. return nullptr;
  2172. }
  2173. static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2174. if (isa<UsingDecl, UnresolvedUsingTypenameDecl, UnresolvedUsingValueDecl>(
  2175. D)) {
  2176. S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
  2177. << AL;
  2178. return;
  2179. }
  2180. if (!AL.checkExactlyNumArgs(S, 1))
  2181. return;
  2182. IdentifierLoc *Platform = AL.getArgAsIdent(0);
  2183. IdentifierInfo *II = Platform->Ident;
  2184. if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
  2185. S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
  2186. << Platform->Ident;
  2187. auto *ND = dyn_cast<NamedDecl>(D);
  2188. if (!ND) // We warned about this already, so just return.
  2189. return;
  2190. AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
  2191. AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
  2192. AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
  2193. bool IsUnavailable = AL.getUnavailableLoc().isValid();
  2194. bool IsStrict = AL.getStrictLoc().isValid();
  2195. StringRef Str;
  2196. if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
  2197. Str = SE->getString();
  2198. StringRef Replacement;
  2199. if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
  2200. Replacement = SE->getString();
  2201. if (II->isStr("swift")) {
  2202. if (Introduced.isValid() || Obsoleted.isValid() ||
  2203. (!IsUnavailable && !Deprecated.isValid())) {
  2204. S.Diag(AL.getLoc(),
  2205. diag::warn_availability_swift_unavailable_deprecated_only);
  2206. return;
  2207. }
  2208. }
  2209. if (II->isStr("fuchsia")) {
  2210. Optional<unsigned> Min, Sub;
  2211. if ((Min = Introduced.Version.getMinor()) ||
  2212. (Sub = Introduced.Version.getSubminor())) {
  2213. S.Diag(AL.getLoc(), diag::warn_availability_fuchsia_unavailable_minor);
  2214. return;
  2215. }
  2216. }
  2217. int PriorityModifier = AL.isPragmaClangAttribute()
  2218. ? Sema::AP_PragmaClangAttribute
  2219. : Sema::AP_Explicit;
  2220. AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
  2221. ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
  2222. Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
  2223. Sema::AMK_None, PriorityModifier);
  2224. if (NewAttr)
  2225. D->addAttr(NewAttr);
  2226. // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
  2227. // matches before the start of the watchOS platform.
  2228. if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
  2229. IdentifierInfo *NewII = nullptr;
  2230. if (II->getName() == "ios")
  2231. NewII = &S.Context.Idents.get("watchos");
  2232. else if (II->getName() == "ios_app_extension")
  2233. NewII = &S.Context.Idents.get("watchos_app_extension");
  2234. if (NewII) {
  2235. const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
  2236. const auto *IOSToWatchOSMapping =
  2237. SDKInfo ? SDKInfo->getVersionMapping(
  2238. DarwinSDKInfo::OSEnvPair::iOStoWatchOSPair())
  2239. : nullptr;
  2240. auto adjustWatchOSVersion =
  2241. [IOSToWatchOSMapping](VersionTuple Version) -> VersionTuple {
  2242. if (Version.empty())
  2243. return Version;
  2244. auto MinimumWatchOSVersion = VersionTuple(2, 0);
  2245. if (IOSToWatchOSMapping) {
  2246. if (auto MappedVersion = IOSToWatchOSMapping->map(
  2247. Version, MinimumWatchOSVersion, None)) {
  2248. return MappedVersion.getValue();
  2249. }
  2250. }
  2251. auto Major = Version.getMajor();
  2252. auto NewMajor = Major >= 9 ? Major - 7 : 0;
  2253. if (NewMajor >= 2) {
  2254. if (Version.getMinor().hasValue()) {
  2255. if (Version.getSubminor().hasValue())
  2256. return VersionTuple(NewMajor, Version.getMinor().getValue(),
  2257. Version.getSubminor().getValue());
  2258. else
  2259. return VersionTuple(NewMajor, Version.getMinor().getValue());
  2260. }
  2261. return VersionTuple(NewMajor);
  2262. }
  2263. return MinimumWatchOSVersion;
  2264. };
  2265. auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
  2266. auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
  2267. auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
  2268. AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
  2269. ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
  2270. NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
  2271. Sema::AMK_None,
  2272. PriorityModifier + Sema::AP_InferredFromOtherPlatform);
  2273. if (NewAttr)
  2274. D->addAttr(NewAttr);
  2275. }
  2276. } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
  2277. // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
  2278. // matches before the start of the tvOS platform.
  2279. IdentifierInfo *NewII = nullptr;
  2280. if (II->getName() == "ios")
  2281. NewII = &S.Context.Idents.get("tvos");
  2282. else if (II->getName() == "ios_app_extension")
  2283. NewII = &S.Context.Idents.get("tvos_app_extension");
  2284. if (NewII) {
  2285. const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
  2286. const auto *IOSToTvOSMapping =
  2287. SDKInfo ? SDKInfo->getVersionMapping(
  2288. DarwinSDKInfo::OSEnvPair::iOStoTvOSPair())
  2289. : nullptr;
  2290. auto AdjustTvOSVersion =
  2291. [IOSToTvOSMapping](VersionTuple Version) -> VersionTuple {
  2292. if (Version.empty())
  2293. return Version;
  2294. if (IOSToTvOSMapping) {
  2295. if (auto MappedVersion =
  2296. IOSToTvOSMapping->map(Version, VersionTuple(0, 0), None)) {
  2297. return MappedVersion.getValue();
  2298. }
  2299. }
  2300. return Version;
  2301. };
  2302. auto NewIntroduced = AdjustTvOSVersion(Introduced.Version);
  2303. auto NewDeprecated = AdjustTvOSVersion(Deprecated.Version);
  2304. auto NewObsoleted = AdjustTvOSVersion(Obsoleted.Version);
  2305. AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
  2306. ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
  2307. NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
  2308. Sema::AMK_None,
  2309. PriorityModifier + Sema::AP_InferredFromOtherPlatform);
  2310. if (NewAttr)
  2311. D->addAttr(NewAttr);
  2312. }
  2313. } else if (S.Context.getTargetInfo().getTriple().getOS() ==
  2314. llvm::Triple::IOS &&
  2315. S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) {
  2316. auto GetSDKInfo = [&]() {
  2317. return S.getDarwinSDKInfoForAvailabilityChecking(AL.getRange().getBegin(),
  2318. "macOS");
  2319. };
  2320. // Transcribe "ios" to "maccatalyst" (and add a new attribute).
  2321. IdentifierInfo *NewII = nullptr;
  2322. if (II->getName() == "ios")
  2323. NewII = &S.Context.Idents.get("maccatalyst");
  2324. else if (II->getName() == "ios_app_extension")
  2325. NewII = &S.Context.Idents.get("maccatalyst_app_extension");
  2326. if (NewII) {
  2327. auto MinMacCatalystVersion = [](const VersionTuple &V) {
  2328. if (V.empty())
  2329. return V;
  2330. if (V.getMajor() < 13 ||
  2331. (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1))
  2332. return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1.
  2333. return V;
  2334. };
  2335. AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
  2336. ND, AL.getRange(), NewII, true /*Implicit*/,
  2337. MinMacCatalystVersion(Introduced.Version),
  2338. MinMacCatalystVersion(Deprecated.Version),
  2339. MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str,
  2340. IsStrict, Replacement, Sema::AMK_None,
  2341. PriorityModifier + Sema::AP_InferredFromOtherPlatform);
  2342. if (NewAttr)
  2343. D->addAttr(NewAttr);
  2344. } else if (II->getName() == "macos" && GetSDKInfo() &&
  2345. (!Introduced.Version.empty() || !Deprecated.Version.empty() ||
  2346. !Obsoleted.Version.empty())) {
  2347. if (const auto *MacOStoMacCatalystMapping =
  2348. GetSDKInfo()->getVersionMapping(
  2349. DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
  2350. // Infer Mac Catalyst availability from the macOS availability attribute
  2351. // if it has versioned availability. Don't infer 'unavailable'. This
  2352. // inferred availability has lower priority than the other availability
  2353. // attributes that are inferred from 'ios'.
  2354. NewII = &S.Context.Idents.get("maccatalyst");
  2355. auto RemapMacOSVersion =
  2356. [&](const VersionTuple &V) -> Optional<VersionTuple> {
  2357. if (V.empty())
  2358. return None;
  2359. // API_TO_BE_DEPRECATED is 100000.
  2360. if (V.getMajor() == 100000)
  2361. return VersionTuple(100000);
  2362. // The minimum iosmac version is 13.1
  2363. return MacOStoMacCatalystMapping->map(V, VersionTuple(13, 1), None);
  2364. };
  2365. Optional<VersionTuple> NewIntroduced =
  2366. RemapMacOSVersion(Introduced.Version),
  2367. NewDeprecated =
  2368. RemapMacOSVersion(Deprecated.Version),
  2369. NewObsoleted =
  2370. RemapMacOSVersion(Obsoleted.Version);
  2371. if (NewIntroduced || NewDeprecated || NewObsoleted) {
  2372. auto VersionOrEmptyVersion =
  2373. [](const Optional<VersionTuple> &V) -> VersionTuple {
  2374. return V ? *V : VersionTuple();
  2375. };
  2376. AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
  2377. ND, AL.getRange(), NewII, true /*Implicit*/,
  2378. VersionOrEmptyVersion(NewIntroduced),
  2379. VersionOrEmptyVersion(NewDeprecated),
  2380. VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str,
  2381. IsStrict, Replacement, Sema::AMK_None,
  2382. PriorityModifier + Sema::AP_InferredFromOtherPlatform +
  2383. Sema::AP_InferredFromOtherPlatform);
  2384. if (NewAttr)
  2385. D->addAttr(NewAttr);
  2386. }
  2387. }
  2388. }
  2389. }
  2390. }
  2391. static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
  2392. const ParsedAttr &AL) {
  2393. if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 3))
  2394. return;
  2395. StringRef Language;
  2396. if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
  2397. Language = SE->getString();
  2398. StringRef DefinedIn;
  2399. if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
  2400. DefinedIn = SE->getString();
  2401. bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
  2402. D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
  2403. S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration));
  2404. }
  2405. template <class T>
  2406. static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
  2407. typename T::VisibilityType value) {
  2408. T *existingAttr = D->getAttr<T>();
  2409. if (existingAttr) {
  2410. typename T::VisibilityType existingValue = existingAttr->getVisibility();
  2411. if (existingValue == value)
  2412. return nullptr;
  2413. S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
  2414. S.Diag(CI.getLoc(), diag::note_previous_attribute);
  2415. D->dropAttr<T>();
  2416. }
  2417. return ::new (S.Context) T(S.Context, CI, value);
  2418. }
  2419. VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
  2420. const AttributeCommonInfo &CI,
  2421. VisibilityAttr::VisibilityType Vis) {
  2422. return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
  2423. }
  2424. TypeVisibilityAttr *
  2425. Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
  2426. TypeVisibilityAttr::VisibilityType Vis) {
  2427. return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
  2428. }
  2429. static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
  2430. bool isTypeVisibility) {
  2431. // Visibility attributes don't mean anything on a typedef.
  2432. if (isa<TypedefNameDecl>(D)) {
  2433. S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
  2434. return;
  2435. }
  2436. // 'type_visibility' can only go on a type or namespace.
  2437. if (isTypeVisibility &&
  2438. !(isa<TagDecl>(D) ||
  2439. isa<ObjCInterfaceDecl>(D) ||
  2440. isa<NamespaceDecl>(D))) {
  2441. S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
  2442. << AL << ExpectedTypeOrNamespace;
  2443. return;
  2444. }
  2445. // Check that the argument is a string literal.
  2446. StringRef TypeStr;
  2447. SourceLocation LiteralLoc;
  2448. if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
  2449. return;
  2450. VisibilityAttr::VisibilityType type;
  2451. if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
  2452. S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
  2453. << TypeStr;
  2454. return;
  2455. }
  2456. // Complain about attempts to use protected visibility on targets
  2457. // (like Darwin) that don't support it.
  2458. if (type == VisibilityAttr::Protected &&
  2459. !S.Context.getTargetInfo().hasProtectedVisibility()) {
  2460. S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
  2461. type = VisibilityAttr::Default;
  2462. }
  2463. Attr *newAttr;
  2464. if (isTypeVisibility) {
  2465. newAttr = S.mergeTypeVisibilityAttr(
  2466. D, AL, (TypeVisibilityAttr::VisibilityType)type);
  2467. } else {
  2468. newAttr = S.mergeVisibilityAttr(D, AL, type);
  2469. }
  2470. if (newAttr)
  2471. D->addAttr(newAttr);
  2472. }
  2473. static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2474. // objc_direct cannot be set on methods declared in the context of a protocol
  2475. if (isa<ObjCProtocolDecl>(D->getDeclContext())) {
  2476. S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
  2477. return;
  2478. }
  2479. if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
  2480. handleSimpleAttribute<ObjCDirectAttr>(S, D, AL);
  2481. } else {
  2482. S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
  2483. }
  2484. }
  2485. static void handleObjCDirectMembersAttr(Sema &S, Decl *D,
  2486. const ParsedAttr &AL) {
  2487. if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
  2488. handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
  2489. } else {
  2490. S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
  2491. }
  2492. }
  2493. static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2494. const auto *M = cast<ObjCMethodDecl>(D);
  2495. if (!AL.isArgIdent(0)) {
  2496. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  2497. << AL << 1 << AANT_ArgumentIdentifier;
  2498. return;
  2499. }
  2500. IdentifierLoc *IL = AL.getArgAsIdent(0);
  2501. ObjCMethodFamilyAttr::FamilyKind F;
  2502. if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
  2503. S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
  2504. return;
  2505. }
  2506. if (F == ObjCMethodFamilyAttr::OMF_init &&
  2507. !M->getReturnType()->isObjCObjectPointerType()) {
  2508. S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
  2509. << M->getReturnType();
  2510. // Ignore the attribute.
  2511. return;
  2512. }
  2513. D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F));
  2514. }
  2515. static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
  2516. if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  2517. QualType T = TD->getUnderlyingType();
  2518. if (!T->isCARCBridgableType()) {
  2519. S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
  2520. return;
  2521. }
  2522. }
  2523. else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
  2524. QualType T = PD->getType();
  2525. if (!T->isCARCBridgableType()) {
  2526. S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
  2527. return;
  2528. }
  2529. }
  2530. else {
  2531. // It is okay to include this attribute on properties, e.g.:
  2532. //
  2533. // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
  2534. //
  2535. // In this case it follows tradition and suppresses an error in the above
  2536. // case.
  2537. S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
  2538. }
  2539. D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL));
  2540. }
  2541. static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
  2542. if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  2543. QualType T = TD->getUnderlyingType();
  2544. if (!T->isObjCObjectPointerType()) {
  2545. S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
  2546. return;
  2547. }
  2548. } else {
  2549. S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
  2550. return;
  2551. }
  2552. D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL));
  2553. }
  2554. static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2555. if (!AL.isArgIdent(0)) {
  2556. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  2557. << AL << 1 << AANT_ArgumentIdentifier;
  2558. return;
  2559. }
  2560. IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
  2561. BlocksAttr::BlockType type;
  2562. if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
  2563. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
  2564. return;
  2565. }
  2566. D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type));
  2567. }
  2568. static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2569. unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
  2570. if (AL.getNumArgs() > 0) {
  2571. Expr *E = AL.getArgAsExpr(0);
  2572. Optional<llvm::APSInt> Idx = llvm::APSInt(32);
  2573. if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
  2574. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  2575. << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
  2576. return;
  2577. }
  2578. if (Idx->isSigned() && Idx->isNegative()) {
  2579. S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
  2580. << E->getSourceRange();
  2581. return;
  2582. }
  2583. sentinel = Idx->getZExtValue();
  2584. }
  2585. unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
  2586. if (AL.getNumArgs() > 1) {
  2587. Expr *E = AL.getArgAsExpr(1);
  2588. Optional<llvm::APSInt> Idx = llvm::APSInt(32);
  2589. if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
  2590. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  2591. << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
  2592. return;
  2593. }
  2594. nullPos = Idx->getZExtValue();
  2595. if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) {
  2596. // FIXME: This error message could be improved, it would be nice
  2597. // to say what the bounds actually are.
  2598. S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
  2599. << E->getSourceRange();
  2600. return;
  2601. }
  2602. }
  2603. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2604. const FunctionType *FT = FD->getType()->castAs<FunctionType>();
  2605. if (isa<FunctionNoProtoType>(FT)) {
  2606. S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
  2607. return;
  2608. }
  2609. if (!cast<FunctionProtoType>(FT)->isVariadic()) {
  2610. S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
  2611. return;
  2612. }
  2613. } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  2614. if (!MD->isVariadic()) {
  2615. S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
  2616. return;
  2617. }
  2618. } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
  2619. if (!BD->isVariadic()) {
  2620. S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
  2621. return;
  2622. }
  2623. } else if (const auto *V = dyn_cast<VarDecl>(D)) {
  2624. QualType Ty = V->getType();
  2625. if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
  2626. const FunctionType *FT = Ty->isFunctionPointerType()
  2627. ? D->getFunctionType()
  2628. : Ty->castAs<BlockPointerType>()
  2629. ->getPointeeType()
  2630. ->castAs<FunctionType>();
  2631. if (!cast<FunctionProtoType>(FT)->isVariadic()) {
  2632. int m = Ty->isFunctionPointerType() ? 0 : 1;
  2633. S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
  2634. return;
  2635. }
  2636. } else {
  2637. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  2638. << AL << ExpectedFunctionMethodOrBlock;
  2639. return;
  2640. }
  2641. } else {
  2642. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  2643. << AL << ExpectedFunctionMethodOrBlock;
  2644. return;
  2645. }
  2646. D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
  2647. }
  2648. static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
  2649. if (D->getFunctionType() &&
  2650. D->getFunctionType()->getReturnType()->isVoidType() &&
  2651. !isa<CXXConstructorDecl>(D)) {
  2652. S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
  2653. return;
  2654. }
  2655. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  2656. if (MD->getReturnType()->isVoidType()) {
  2657. S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
  2658. return;
  2659. }
  2660. StringRef Str;
  2661. if (AL.isStandardAttributeSyntax() && !AL.getScopeName()) {
  2662. // The standard attribute cannot be applied to variable declarations such
  2663. // as a function pointer.
  2664. if (isa<VarDecl>(D))
  2665. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
  2666. << AL << "functions, classes, or enumerations";
  2667. // If this is spelled as the standard C++17 attribute, but not in C++17,
  2668. // warn about using it as an extension. If there are attribute arguments,
  2669. // then claim it's a C++2a extension instead.
  2670. // FIXME: If WG14 does not seem likely to adopt the same feature, add an
  2671. // extension warning for C2x mode.
  2672. const LangOptions &LO = S.getLangOpts();
  2673. if (AL.getNumArgs() == 1) {
  2674. if (LO.CPlusPlus && !LO.CPlusPlus20)
  2675. S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL;
  2676. // Since this this is spelled [[nodiscard]], get the optional string
  2677. // literal. If in C++ mode, but not in C++2a mode, diagnose as an
  2678. // extension.
  2679. // FIXME: C2x should support this feature as well, even as an extension.
  2680. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
  2681. return;
  2682. } else if (LO.CPlusPlus && !LO.CPlusPlus17)
  2683. S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
  2684. }
  2685. D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
  2686. }
  2687. static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2688. // weak_import only applies to variable & function declarations.
  2689. bool isDef = false;
  2690. if (!D->canBeWeakImported(isDef)) {
  2691. if (isDef)
  2692. S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
  2693. << "weak_import";
  2694. else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
  2695. (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
  2696. (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
  2697. // Nothing to warn about here.
  2698. } else
  2699. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  2700. << AL << ExpectedVariableOrFunction;
  2701. return;
  2702. }
  2703. D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
  2704. }
  2705. // Handles reqd_work_group_size and work_group_size_hint.
  2706. template <typename WorkGroupAttr>
  2707. static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
  2708. uint32_t WGSize[3];
  2709. for (unsigned i = 0; i < 3; ++i) {
  2710. const Expr *E = AL.getArgAsExpr(i);
  2711. if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
  2712. /*StrictlyUnsigned=*/true))
  2713. return;
  2714. if (WGSize[i] == 0) {
  2715. S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
  2716. << AL << E->getSourceRange();
  2717. return;
  2718. }
  2719. }
  2720. WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
  2721. if (Existing && !(Existing->getXDim() == WGSize[0] &&
  2722. Existing->getYDim() == WGSize[1] &&
  2723. Existing->getZDim() == WGSize[2]))
  2724. S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
  2725. D->addAttr(::new (S.Context)
  2726. WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
  2727. }
  2728. // Handles intel_reqd_sub_group_size.
  2729. static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
  2730. uint32_t SGSize;
  2731. const Expr *E = AL.getArgAsExpr(0);
  2732. if (!checkUInt32Argument(S, AL, E, SGSize))
  2733. return;
  2734. if (SGSize == 0) {
  2735. S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
  2736. << AL << E->getSourceRange();
  2737. return;
  2738. }
  2739. OpenCLIntelReqdSubGroupSizeAttr *Existing =
  2740. D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
  2741. if (Existing && Existing->getSubGroupSize() != SGSize)
  2742. S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
  2743. D->addAttr(::new (S.Context)
  2744. OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize));
  2745. }
  2746. static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
  2747. if (!AL.hasParsedType()) {
  2748. S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
  2749. return;
  2750. }
  2751. TypeSourceInfo *ParmTSI = nullptr;
  2752. QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
  2753. assert(ParmTSI && "no type source info for attribute argument");
  2754. if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
  2755. (ParmType->isBooleanType() ||
  2756. !ParmType->isIntegralType(S.getASTContext()))) {
  2757. S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
  2758. return;
  2759. }
  2760. if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
  2761. if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
  2762. S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
  2763. return;
  2764. }
  2765. }
  2766. D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
  2767. }
  2768. SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
  2769. StringRef Name) {
  2770. // Explicit or partial specializations do not inherit
  2771. // the section attribute from the primary template.
  2772. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2773. if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
  2774. FD->isFunctionTemplateSpecialization())
  2775. return nullptr;
  2776. }
  2777. if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
  2778. if (ExistingAttr->getName() == Name)
  2779. return nullptr;
  2780. Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
  2781. << 1 /*section*/;
  2782. Diag(CI.getLoc(), diag::note_previous_attribute);
  2783. return nullptr;
  2784. }
  2785. return ::new (Context) SectionAttr(Context, CI, Name);
  2786. }
  2787. /// Used to implement to perform semantic checking on
  2788. /// attribute((section("foo"))) specifiers.
  2789. ///
  2790. /// In this case, "foo" is passed in to be checked. If the section
  2791. /// specifier is invalid, return an Error that indicates the problem.
  2792. ///
  2793. /// This is a simple quality of implementation feature to catch errors
  2794. /// and give good diagnostics in cases when the assembler or code generator
  2795. /// would otherwise reject the section specifier.
  2796. llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) {
  2797. if (!Context.getTargetInfo().getTriple().isOSDarwin())
  2798. return llvm::Error::success();
  2799. // Let MCSectionMachO validate this.
  2800. StringRef Segment, Section;
  2801. unsigned TAA, StubSize;
  2802. bool HasTAA;
  2803. return llvm::MCSectionMachO::ParseSectionSpecifier(SecName, Segment, Section,
  2804. TAA, HasTAA, StubSize);
  2805. }
  2806. bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
  2807. if (llvm::Error E = isValidSectionSpecifier(SecName)) {
  2808. Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
  2809. << toString(std::move(E)) << 1 /*'section'*/;
  2810. return false;
  2811. }
  2812. return true;
  2813. }
  2814. static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2815. // Make sure that there is a string literal as the sections's single
  2816. // argument.
  2817. StringRef Str;
  2818. SourceLocation LiteralLoc;
  2819. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
  2820. return;
  2821. if (!S.checkSectionName(LiteralLoc, Str))
  2822. return;
  2823. SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
  2824. if (NewAttr) {
  2825. D->addAttr(NewAttr);
  2826. if (isa<FunctionDecl, FunctionTemplateDecl, ObjCMethodDecl,
  2827. ObjCPropertyDecl>(D))
  2828. S.UnifySection(NewAttr->getName(),
  2829. ASTContext::PSF_Execute | ASTContext::PSF_Read,
  2830. cast<NamedDecl>(D));
  2831. }
  2832. }
  2833. // This is used for `__declspec(code_seg("segname"))` on a decl.
  2834. // `#pragma code_seg("segname")` uses checkSectionName() instead.
  2835. static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
  2836. StringRef CodeSegName) {
  2837. if (llvm::Error E = S.isValidSectionSpecifier(CodeSegName)) {
  2838. S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
  2839. << toString(std::move(E)) << 0 /*'code-seg'*/;
  2840. return false;
  2841. }
  2842. return true;
  2843. }
  2844. CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
  2845. StringRef Name) {
  2846. // Explicit or partial specializations do not inherit
  2847. // the code_seg attribute from the primary template.
  2848. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2849. if (FD->isFunctionTemplateSpecialization())
  2850. return nullptr;
  2851. }
  2852. if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
  2853. if (ExistingAttr->getName() == Name)
  2854. return nullptr;
  2855. Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
  2856. << 0 /*codeseg*/;
  2857. Diag(CI.getLoc(), diag::note_previous_attribute);
  2858. return nullptr;
  2859. }
  2860. return ::new (Context) CodeSegAttr(Context, CI, Name);
  2861. }
  2862. static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2863. StringRef Str;
  2864. SourceLocation LiteralLoc;
  2865. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
  2866. return;
  2867. if (!checkCodeSegName(S, LiteralLoc, Str))
  2868. return;
  2869. if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
  2870. if (!ExistingAttr->isImplicit()) {
  2871. S.Diag(AL.getLoc(),
  2872. ExistingAttr->getName() == Str
  2873. ? diag::warn_duplicate_codeseg_attribute
  2874. : diag::err_conflicting_codeseg_attribute);
  2875. return;
  2876. }
  2877. D->dropAttr<CodeSegAttr>();
  2878. }
  2879. if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
  2880. D->addAttr(CSA);
  2881. }
  2882. // Check for things we'd like to warn about. Multiversioning issues are
  2883. // handled later in the process, once we know how many exist.
  2884. bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
  2885. enum FirstParam { Unsupported, Duplicate, Unknown };
  2886. enum SecondParam { None, Architecture, Tune };
  2887. enum ThirdParam { Target, TargetClones };
  2888. if (AttrStr.contains("fpmath="))
  2889. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2890. << Unsupported << None << "fpmath=" << Target;
  2891. // Diagnose use of tune if target doesn't support it.
  2892. if (!Context.getTargetInfo().supportsTargetAttributeTune() &&
  2893. AttrStr.contains("tune="))
  2894. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2895. << Unsupported << None << "tune=" << Target;
  2896. ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
  2897. if (!ParsedAttrs.Architecture.empty() &&
  2898. !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
  2899. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2900. << Unknown << Architecture << ParsedAttrs.Architecture << Target;
  2901. if (!ParsedAttrs.Tune.empty() &&
  2902. !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune))
  2903. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2904. << Unknown << Tune << ParsedAttrs.Tune << Target;
  2905. if (ParsedAttrs.DuplicateArchitecture)
  2906. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2907. << Duplicate << None << "arch=" << Target;
  2908. if (ParsedAttrs.DuplicateTune)
  2909. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2910. << Duplicate << None << "tune=" << Target;
  2911. for (const auto &Feature : ParsedAttrs.Features) {
  2912. auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
  2913. if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
  2914. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2915. << Unsupported << None << CurFeature << Target;
  2916. }
  2917. TargetInfo::BranchProtectionInfo BPI;
  2918. StringRef DiagMsg;
  2919. if (ParsedAttrs.BranchProtection.empty())
  2920. return false;
  2921. if (!Context.getTargetInfo().validateBranchProtection(
  2922. ParsedAttrs.BranchProtection, ParsedAttrs.Architecture, BPI,
  2923. DiagMsg)) {
  2924. if (DiagMsg.empty())
  2925. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2926. << Unsupported << None << "branch-protection" << Target;
  2927. return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
  2928. << DiagMsg;
  2929. }
  2930. if (!DiagMsg.empty())
  2931. Diag(LiteralLoc, diag::warn_unsupported_branch_protection_spec) << DiagMsg;
  2932. return false;
  2933. }
  2934. static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2935. StringRef Str;
  2936. SourceLocation LiteralLoc;
  2937. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
  2938. S.checkTargetAttr(LiteralLoc, Str))
  2939. return;
  2940. TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
  2941. D->addAttr(NewAttr);
  2942. }
  2943. bool Sema::checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str,
  2944. const StringLiteral *Literal,
  2945. bool &HasDefault, bool &HasCommas,
  2946. SmallVectorImpl<StringRef> &Strings) {
  2947. enum FirstParam { Unsupported, Duplicate, Unknown };
  2948. enum SecondParam { None, Architecture, Tune };
  2949. enum ThirdParam { Target, TargetClones };
  2950. HasCommas = HasCommas || Str.contains(',');
  2951. // Warn on empty at the beginning of a string.
  2952. if (Str.size() == 0)
  2953. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2954. << Unsupported << None << "" << TargetClones;
  2955. std::pair<StringRef, StringRef> Parts = {{}, Str};
  2956. while (!Parts.second.empty()) {
  2957. Parts = Parts.second.split(',');
  2958. StringRef Cur = Parts.first.trim();
  2959. SourceLocation CurLoc = Literal->getLocationOfByte(
  2960. Cur.data() - Literal->getString().data(), getSourceManager(),
  2961. getLangOpts(), Context.getTargetInfo());
  2962. bool DefaultIsDupe = false;
  2963. if (Cur.empty())
  2964. return Diag(CurLoc, diag::warn_unsupported_target_attribute)
  2965. << Unsupported << None << "" << TargetClones;
  2966. if (Cur.startswith("arch=")) {
  2967. if (!Context.getTargetInfo().isValidCPUName(
  2968. Cur.drop_front(sizeof("arch=") - 1)))
  2969. return Diag(CurLoc, diag::warn_unsupported_target_attribute)
  2970. << Unsupported << Architecture
  2971. << Cur.drop_front(sizeof("arch=") - 1) << TargetClones;
  2972. } else if (Cur == "default") {
  2973. DefaultIsDupe = HasDefault;
  2974. HasDefault = true;
  2975. } else if (!Context.getTargetInfo().isValidFeatureName(Cur))
  2976. return Diag(CurLoc, diag::warn_unsupported_target_attribute)
  2977. << Unsupported << None << Cur << TargetClones;
  2978. if (llvm::find(Strings, Cur) != Strings.end() || DefaultIsDupe)
  2979. Diag(CurLoc, diag::warn_target_clone_duplicate_options);
  2980. // Note: Add even if there are duplicates, since it changes name mangling.
  2981. Strings.push_back(Cur);
  2982. }
  2983. if (Str.rtrim().endswith(","))
  2984. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2985. << Unsupported << None << "" << TargetClones;
  2986. return false;
  2987. }
  2988. static void handleTargetClonesAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2989. // Ensure we don't combine these with themselves, since that causes some
  2990. // confusing behavior.
  2991. if (const auto *Other = D->getAttr<TargetClonesAttr>()) {
  2992. S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
  2993. S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
  2994. return;
  2995. }
  2996. if (checkAttrMutualExclusion<TargetClonesAttr>(S, D, AL))
  2997. return;
  2998. SmallVector<StringRef, 2> Strings;
  2999. bool HasCommas = false, HasDefault = false;
  3000. for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
  3001. StringRef CurStr;
  3002. SourceLocation LiteralLoc;
  3003. if (!S.checkStringLiteralArgumentAttr(AL, I, CurStr, &LiteralLoc) ||
  3004. S.checkTargetClonesAttrString(
  3005. LiteralLoc, CurStr,
  3006. cast<StringLiteral>(AL.getArgAsExpr(I)->IgnoreParenCasts()),
  3007. HasDefault, HasCommas, Strings))
  3008. return;
  3009. }
  3010. if (HasCommas && AL.getNumArgs() > 1)
  3011. S.Diag(AL.getLoc(), diag::warn_target_clone_mixed_values);
  3012. if (!HasDefault) {
  3013. S.Diag(AL.getLoc(), diag::err_target_clone_must_have_default);
  3014. return;
  3015. }
  3016. // FIXME: We could probably figure out how to get this to work for lambdas
  3017. // someday.
  3018. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  3019. if (MD->getParent()->isLambda()) {
  3020. S.Diag(D->getLocation(), diag::err_multiversion_doesnt_support)
  3021. << static_cast<unsigned>(MultiVersionKind::TargetClones)
  3022. << /*Lambda*/ 9;
  3023. return;
  3024. }
  3025. }
  3026. cast<FunctionDecl>(D)->setIsMultiVersion();
  3027. TargetClonesAttr *NewAttr = ::new (S.Context)
  3028. TargetClonesAttr(S.Context, AL, Strings.data(), Strings.size());
  3029. D->addAttr(NewAttr);
  3030. }
  3031. static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3032. Expr *E = AL.getArgAsExpr(0);
  3033. uint32_t VecWidth;
  3034. if (!checkUInt32Argument(S, AL, E, VecWidth)) {
  3035. AL.setInvalid();
  3036. return;
  3037. }
  3038. MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
  3039. if (Existing && Existing->getVectorWidth() != VecWidth) {
  3040. S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
  3041. return;
  3042. }
  3043. D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
  3044. }
  3045. static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3046. Expr *E = AL.getArgAsExpr(0);
  3047. SourceLocation Loc = E->getExprLoc();
  3048. FunctionDecl *FD = nullptr;
  3049. DeclarationNameInfo NI;
  3050. // gcc only allows for simple identifiers. Since we support more than gcc, we
  3051. // will warn the user.
  3052. if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  3053. if (DRE->hasQualifier())
  3054. S.Diag(Loc, diag::warn_cleanup_ext);
  3055. FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  3056. NI = DRE->getNameInfo();
  3057. if (!FD) {
  3058. S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
  3059. << NI.getName();
  3060. return;
  3061. }
  3062. } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  3063. if (ULE->hasExplicitTemplateArgs())
  3064. S.Diag(Loc, diag::warn_cleanup_ext);
  3065. FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
  3066. NI = ULE->getNameInfo();
  3067. if (!FD) {
  3068. S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
  3069. << NI.getName();
  3070. if (ULE->getType() == S.Context.OverloadTy)
  3071. S.NoteAllOverloadCandidates(ULE);
  3072. return;
  3073. }
  3074. } else {
  3075. S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
  3076. return;
  3077. }
  3078. if (FD->getNumParams() != 1) {
  3079. S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
  3080. << NI.getName();
  3081. return;
  3082. }
  3083. // We're currently more strict than GCC about what function types we accept.
  3084. // If this ever proves to be a problem it should be easy to fix.
  3085. QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
  3086. QualType ParamTy = FD->getParamDecl(0)->getType();
  3087. if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
  3088. ParamTy, Ty) != Sema::Compatible) {
  3089. S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
  3090. << NI.getName() << ParamTy << Ty;
  3091. return;
  3092. }
  3093. D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
  3094. }
  3095. static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
  3096. const ParsedAttr &AL) {
  3097. if (!AL.isArgIdent(0)) {
  3098. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  3099. << AL << 0 << AANT_ArgumentIdentifier;
  3100. return;
  3101. }
  3102. EnumExtensibilityAttr::Kind ExtensibilityKind;
  3103. IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
  3104. if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
  3105. ExtensibilityKind)) {
  3106. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
  3107. return;
  3108. }
  3109. D->addAttr(::new (S.Context)
  3110. EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
  3111. }
  3112. /// Handle __attribute__((format_arg((idx)))) attribute based on
  3113. /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
  3114. static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3115. Expr *IdxExpr = AL.getArgAsExpr(0);
  3116. ParamIdx Idx;
  3117. if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
  3118. return;
  3119. // Make sure the format string is really a string.
  3120. QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
  3121. bool NotNSStringTy = !isNSStringType(Ty, S.Context);
  3122. if (NotNSStringTy &&
  3123. !isCFStringType(Ty, S.Context) &&
  3124. (!Ty->isPointerType() ||
  3125. !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
  3126. S.Diag(AL.getLoc(), diag::err_format_attribute_not)
  3127. << "a string type" << IdxExpr->getSourceRange()
  3128. << getFunctionOrMethodParamRange(D, 0);
  3129. return;
  3130. }
  3131. Ty = getFunctionOrMethodResultType(D);
  3132. // replace instancetype with the class type
  3133. auto Instancetype = S.Context.getObjCInstanceTypeDecl()->getTypeForDecl();
  3134. if (Ty->getAs<TypedefType>() == Instancetype)
  3135. if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
  3136. if (auto *Interface = OMD->getClassInterface())
  3137. Ty = S.Context.getObjCObjectPointerType(
  3138. QualType(Interface->getTypeForDecl(), 0));
  3139. if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true) &&
  3140. !isCFStringType(Ty, S.Context) &&
  3141. (!Ty->isPointerType() ||
  3142. !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
  3143. S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
  3144. << (NotNSStringTy ? "string type" : "NSString")
  3145. << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
  3146. return;
  3147. }
  3148. D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
  3149. }
  3150. enum FormatAttrKind {
  3151. CFStringFormat,
  3152. NSStringFormat,
  3153. StrftimeFormat,
  3154. SupportedFormat,
  3155. IgnoredFormat,
  3156. InvalidFormat
  3157. };
  3158. /// getFormatAttrKind - Map from format attribute names to supported format
  3159. /// types.
  3160. static FormatAttrKind getFormatAttrKind(StringRef Format) {
  3161. return llvm::StringSwitch<FormatAttrKind>(Format)
  3162. // Check for formats that get handled specially.
  3163. .Case("NSString", NSStringFormat)
  3164. .Case("CFString", CFStringFormat)
  3165. .Case("strftime", StrftimeFormat)
  3166. // Otherwise, check for supported formats.
  3167. .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
  3168. .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
  3169. .Case("kprintf", SupportedFormat) // OpenBSD.
  3170. .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
  3171. .Case("os_trace", SupportedFormat)
  3172. .Case("os_log", SupportedFormat)
  3173. .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
  3174. .Default(InvalidFormat);
  3175. }
  3176. /// Handle __attribute__((init_priority(priority))) attributes based on
  3177. /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
  3178. static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3179. if (!S.getLangOpts().CPlusPlus) {
  3180. S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
  3181. return;
  3182. }
  3183. if (S.getCurFunctionOrMethodDecl()) {
  3184. S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
  3185. AL.setInvalid();
  3186. return;
  3187. }
  3188. QualType T = cast<VarDecl>(D)->getType();
  3189. if (S.Context.getAsArrayType(T))
  3190. T = S.Context.getBaseElementType(T);
  3191. if (!T->getAs<RecordType>()) {
  3192. S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
  3193. AL.setInvalid();
  3194. return;
  3195. }
  3196. Expr *E = AL.getArgAsExpr(0);
  3197. uint32_t prioritynum;
  3198. if (!checkUInt32Argument(S, AL, E, prioritynum)) {
  3199. AL.setInvalid();
  3200. return;
  3201. }
  3202. // Only perform the priority check if the attribute is outside of a system
  3203. // header. Values <= 100 are reserved for the implementation, and libc++
  3204. // benefits from being able to specify values in that range.
  3205. if ((prioritynum < 101 || prioritynum > 65535) &&
  3206. !S.getSourceManager().isInSystemHeader(AL.getLoc())) {
  3207. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
  3208. << E->getSourceRange() << AL << 101 << 65535;
  3209. AL.setInvalid();
  3210. return;
  3211. }
  3212. D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
  3213. }
  3214. ErrorAttr *Sema::mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
  3215. StringRef NewUserDiagnostic) {
  3216. if (const auto *EA = D->getAttr<ErrorAttr>()) {
  3217. std::string NewAttr = CI.getNormalizedFullName();
  3218. assert((NewAttr == "error" || NewAttr == "warning") &&
  3219. "unexpected normalized full name");
  3220. bool Match = (EA->isError() && NewAttr == "error") ||
  3221. (EA->isWarning() && NewAttr == "warning");
  3222. if (!Match) {
  3223. Diag(EA->getLocation(), diag::err_attributes_are_not_compatible)
  3224. << CI << EA;
  3225. Diag(CI.getLoc(), diag::note_conflicting_attribute);
  3226. return nullptr;
  3227. }
  3228. if (EA->getUserDiagnostic() != NewUserDiagnostic) {
  3229. Diag(CI.getLoc(), diag::warn_duplicate_attribute) << EA;
  3230. Diag(EA->getLoc(), diag::note_previous_attribute);
  3231. }
  3232. D->dropAttr<ErrorAttr>();
  3233. }
  3234. return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic);
  3235. }
  3236. FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
  3237. IdentifierInfo *Format, int FormatIdx,
  3238. int FirstArg) {
  3239. // Check whether we already have an equivalent format attribute.
  3240. for (auto *F : D->specific_attrs<FormatAttr>()) {
  3241. if (F->getType() == Format &&
  3242. F->getFormatIdx() == FormatIdx &&
  3243. F->getFirstArg() == FirstArg) {
  3244. // If we don't have a valid location for this attribute, adopt the
  3245. // location.
  3246. if (F->getLocation().isInvalid())
  3247. F->setRange(CI.getRange());
  3248. return nullptr;
  3249. }
  3250. }
  3251. return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
  3252. }
  3253. /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
  3254. /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
  3255. static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3256. if (!AL.isArgIdent(0)) {
  3257. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  3258. << AL << 1 << AANT_ArgumentIdentifier;
  3259. return;
  3260. }
  3261. // In C++ the implicit 'this' function parameter also counts, and they are
  3262. // counted from one.
  3263. bool HasImplicitThisParam = isInstanceMethod(D);
  3264. unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
  3265. IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
  3266. StringRef Format = II->getName();
  3267. if (normalizeName(Format)) {
  3268. // If we've modified the string name, we need a new identifier for it.
  3269. II = &S.Context.Idents.get(Format);
  3270. }
  3271. // Check for supported formats.
  3272. FormatAttrKind Kind = getFormatAttrKind(Format);
  3273. if (Kind == IgnoredFormat)
  3274. return;
  3275. if (Kind == InvalidFormat) {
  3276. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
  3277. << AL << II->getName();
  3278. return;
  3279. }
  3280. // checks for the 2nd argument
  3281. Expr *IdxExpr = AL.getArgAsExpr(1);
  3282. uint32_t Idx;
  3283. if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
  3284. return;
  3285. if (Idx < 1 || Idx > NumArgs) {
  3286. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
  3287. << AL << 2 << IdxExpr->getSourceRange();
  3288. return;
  3289. }
  3290. // FIXME: Do we need to bounds check?
  3291. unsigned ArgIdx = Idx - 1;
  3292. if (HasImplicitThisParam) {
  3293. if (ArgIdx == 0) {
  3294. S.Diag(AL.getLoc(),
  3295. diag::err_format_attribute_implicit_this_format_string)
  3296. << IdxExpr->getSourceRange();
  3297. return;
  3298. }
  3299. ArgIdx--;
  3300. }
  3301. // make sure the format string is really a string
  3302. QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
  3303. if (Kind == CFStringFormat) {
  3304. if (!isCFStringType(Ty, S.Context)) {
  3305. S.Diag(AL.getLoc(), diag::err_format_attribute_not)
  3306. << "a CFString" << IdxExpr->getSourceRange()
  3307. << getFunctionOrMethodParamRange(D, ArgIdx);
  3308. return;
  3309. }
  3310. } else if (Kind == NSStringFormat) {
  3311. // FIXME: do we need to check if the type is NSString*? What are the
  3312. // semantics?
  3313. if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true)) {
  3314. S.Diag(AL.getLoc(), diag::err_format_attribute_not)
  3315. << "an NSString" << IdxExpr->getSourceRange()
  3316. << getFunctionOrMethodParamRange(D, ArgIdx);
  3317. return;
  3318. }
  3319. } else if (!Ty->isPointerType() ||
  3320. !Ty->castAs<PointerType>()->getPointeeType()->isCharType()) {
  3321. S.Diag(AL.getLoc(), diag::err_format_attribute_not)
  3322. << "a string type" << IdxExpr->getSourceRange()
  3323. << getFunctionOrMethodParamRange(D, ArgIdx);
  3324. return;
  3325. }
  3326. // check the 3rd argument
  3327. Expr *FirstArgExpr = AL.getArgAsExpr(2);
  3328. uint32_t FirstArg;
  3329. if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
  3330. return;
  3331. // check if the function is variadic if the 3rd argument non-zero
  3332. if (FirstArg != 0) {
  3333. if (isFunctionOrMethodVariadic(D)) {
  3334. ++NumArgs; // +1 for ...
  3335. } else {
  3336. S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
  3337. return;
  3338. }
  3339. }
  3340. // strftime requires FirstArg to be 0 because it doesn't read from any
  3341. // variable the input is just the current time + the format string.
  3342. if (Kind == StrftimeFormat) {
  3343. if (FirstArg != 0) {
  3344. S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
  3345. << FirstArgExpr->getSourceRange();
  3346. return;
  3347. }
  3348. // if 0 it disables parameter checking (to use with e.g. va_list)
  3349. } else if (FirstArg != 0 && FirstArg != NumArgs) {
  3350. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
  3351. << AL << 3 << FirstArgExpr->getSourceRange();
  3352. return;
  3353. }
  3354. FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
  3355. if (NewAttr)
  3356. D->addAttr(NewAttr);
  3357. }
  3358. /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
  3359. static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3360. // The index that identifies the callback callee is mandatory.
  3361. if (AL.getNumArgs() == 0) {
  3362. S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
  3363. << AL.getRange();
  3364. return;
  3365. }
  3366. bool HasImplicitThisParam = isInstanceMethod(D);
  3367. int32_t NumArgs = getFunctionOrMethodNumParams(D);
  3368. FunctionDecl *FD = D->getAsFunction();
  3369. assert(FD && "Expected a function declaration!");
  3370. llvm::StringMap<int> NameIdxMapping;
  3371. NameIdxMapping["__"] = -1;
  3372. NameIdxMapping["this"] = 0;
  3373. int Idx = 1;
  3374. for (const ParmVarDecl *PVD : FD->parameters())
  3375. NameIdxMapping[PVD->getName()] = Idx++;
  3376. auto UnknownName = NameIdxMapping.end();
  3377. SmallVector<int, 8> EncodingIndices;
  3378. for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
  3379. SourceRange SR;
  3380. int32_t ArgIdx;
  3381. if (AL.isArgIdent(I)) {
  3382. IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
  3383. auto It = NameIdxMapping.find(IdLoc->Ident->getName());
  3384. if (It == UnknownName) {
  3385. S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
  3386. << IdLoc->Ident << IdLoc->Loc;
  3387. return;
  3388. }
  3389. SR = SourceRange(IdLoc->Loc);
  3390. ArgIdx = It->second;
  3391. } else if (AL.isArgExpr(I)) {
  3392. Expr *IdxExpr = AL.getArgAsExpr(I);
  3393. // If the expression is not parseable as an int32_t we have a problem.
  3394. if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
  3395. false)) {
  3396. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
  3397. << AL << (I + 1) << IdxExpr->getSourceRange();
  3398. return;
  3399. }
  3400. // Check oob, excluding the special values, 0 and -1.
  3401. if (ArgIdx < -1 || ArgIdx > NumArgs) {
  3402. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
  3403. << AL << (I + 1) << IdxExpr->getSourceRange();
  3404. return;
  3405. }
  3406. SR = IdxExpr->getSourceRange();
  3407. } else {
  3408. llvm_unreachable("Unexpected ParsedAttr argument type!");
  3409. }
  3410. if (ArgIdx == 0 && !HasImplicitThisParam) {
  3411. S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
  3412. << (I + 1) << SR;
  3413. return;
  3414. }
  3415. // Adjust for the case we do not have an implicit "this" parameter. In this
  3416. // case we decrease all positive values by 1 to get LLVM argument indices.
  3417. if (!HasImplicitThisParam && ArgIdx > 0)
  3418. ArgIdx -= 1;
  3419. EncodingIndices.push_back(ArgIdx);
  3420. }
  3421. int CalleeIdx = EncodingIndices.front();
  3422. // Check if the callee index is proper, thus not "this" and not "unknown".
  3423. // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
  3424. // is false and positive if "HasImplicitThisParam" is true.
  3425. if (CalleeIdx < (int)HasImplicitThisParam) {
  3426. S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
  3427. << AL.getRange();
  3428. return;
  3429. }
  3430. // Get the callee type, note the index adjustment as the AST doesn't contain
  3431. // the this type (which the callee cannot reference anyway!).
  3432. const Type *CalleeType =
  3433. getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
  3434. .getTypePtr();
  3435. if (!CalleeType || !CalleeType->isFunctionPointerType()) {
  3436. S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
  3437. << AL.getRange();
  3438. return;
  3439. }
  3440. const Type *CalleeFnType =
  3441. CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
  3442. // TODO: Check the type of the callee arguments.
  3443. const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
  3444. if (!CalleeFnProtoType) {
  3445. S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
  3446. << AL.getRange();
  3447. return;
  3448. }
  3449. if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
  3450. S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
  3451. << AL << (unsigned)(EncodingIndices.size() - 1);
  3452. return;
  3453. }
  3454. if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
  3455. S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
  3456. << AL << (unsigned)(EncodingIndices.size() - 1);
  3457. return;
  3458. }
  3459. if (CalleeFnProtoType->isVariadic()) {
  3460. S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
  3461. return;
  3462. }
  3463. // Do not allow multiple callback attributes.
  3464. if (D->hasAttr<CallbackAttr>()) {
  3465. S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
  3466. return;
  3467. }
  3468. D->addAttr(::new (S.Context) CallbackAttr(
  3469. S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
  3470. }
  3471. static bool isFunctionLike(const Type &T) {
  3472. // Check for explicit function types.
  3473. // 'called_once' is only supported in Objective-C and it has
  3474. // function pointers and block pointers.
  3475. return T.isFunctionPointerType() || T.isBlockPointerType();
  3476. }
  3477. /// Handle 'called_once' attribute.
  3478. static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3479. // 'called_once' only applies to parameters representing functions.
  3480. QualType T = cast<ParmVarDecl>(D)->getType();
  3481. if (!isFunctionLike(*T)) {
  3482. S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type);
  3483. return;
  3484. }
  3485. D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL));
  3486. }
  3487. static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3488. // Try to find the underlying union declaration.
  3489. RecordDecl *RD = nullptr;
  3490. const auto *TD = dyn_cast<TypedefNameDecl>(D);
  3491. if (TD && TD->getUnderlyingType()->isUnionType())
  3492. RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
  3493. else
  3494. RD = dyn_cast<RecordDecl>(D);
  3495. if (!RD || !RD->isUnion()) {
  3496. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
  3497. << ExpectedUnion;
  3498. return;
  3499. }
  3500. if (!RD->isCompleteDefinition()) {
  3501. if (!RD->isBeingDefined())
  3502. S.Diag(AL.getLoc(),
  3503. diag::warn_transparent_union_attribute_not_definition);
  3504. return;
  3505. }
  3506. RecordDecl::field_iterator Field = RD->field_begin(),
  3507. FieldEnd = RD->field_end();
  3508. if (Field == FieldEnd) {
  3509. S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
  3510. return;
  3511. }
  3512. FieldDecl *FirstField = *Field;
  3513. QualType FirstType = FirstField->getType();
  3514. if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
  3515. S.Diag(FirstField->getLocation(),
  3516. diag::warn_transparent_union_attribute_floating)
  3517. << FirstType->isVectorType() << FirstType;
  3518. return;
  3519. }
  3520. if (FirstType->isIncompleteType())
  3521. return;
  3522. uint64_t FirstSize = S.Context.getTypeSize(FirstType);
  3523. uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
  3524. for (; Field != FieldEnd; ++Field) {
  3525. QualType FieldType = Field->getType();
  3526. if (FieldType->isIncompleteType())
  3527. return;
  3528. // FIXME: this isn't fully correct; we also need to test whether the
  3529. // members of the union would all have the same calling convention as the
  3530. // first member of the union. Checking just the size and alignment isn't
  3531. // sufficient (consider structs passed on the stack instead of in registers
  3532. // as an example).
  3533. if (S.Context.getTypeSize(FieldType) != FirstSize ||
  3534. S.Context.getTypeAlign(FieldType) > FirstAlign) {
  3535. // Warn if we drop the attribute.
  3536. bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
  3537. unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType)
  3538. : S.Context.getTypeAlign(FieldType);
  3539. S.Diag(Field->getLocation(),
  3540. diag::warn_transparent_union_attribute_field_size_align)
  3541. << isSize << *Field << FieldBits;
  3542. unsigned FirstBits = isSize ? FirstSize : FirstAlign;
  3543. S.Diag(FirstField->getLocation(),
  3544. diag::note_transparent_union_first_field_size_align)
  3545. << isSize << FirstBits;
  3546. return;
  3547. }
  3548. }
  3549. RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
  3550. }
  3551. void Sema::AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
  3552. StringRef Str, MutableArrayRef<Expr *> Args) {
  3553. auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI);
  3554. llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
  3555. for (unsigned Idx = 0; Idx < Attr->args_size(); Idx++) {
  3556. Expr *&E = Attr->args_begin()[Idx];
  3557. assert(E && "error are handled before");
  3558. if (E->isValueDependent() || E->isTypeDependent())
  3559. continue;
  3560. if (E->getType()->isArrayType())
  3561. E = ImpCastExprToType(E, Context.getPointerType(E->getType()),
  3562. clang::CK_ArrayToPointerDecay)
  3563. .get();
  3564. if (E->getType()->isFunctionType())
  3565. E = ImplicitCastExpr::Create(Context,
  3566. Context.getPointerType(E->getType()),
  3567. clang::CK_FunctionToPointerDecay, E, nullptr,
  3568. VK_PRValue, FPOptionsOverride());
  3569. if (E->isLValue())
  3570. E = ImplicitCastExpr::Create(Context, E->getType().getNonReferenceType(),
  3571. clang::CK_LValueToRValue, E, nullptr,
  3572. VK_PRValue, FPOptionsOverride());
  3573. Expr::EvalResult Eval;
  3574. Notes.clear();
  3575. Eval.Diag = &Notes;
  3576. bool Result =
  3577. E->EvaluateAsConstantExpr(Eval, Context);
  3578. /// Result means the expression can be folded to a constant.
  3579. /// Note.empty() means the expression is a valid constant expression in the
  3580. /// current language mode.
  3581. if (!Result || !Notes.empty()) {
  3582. Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type)
  3583. << CI << (Idx + 1) << AANT_ArgumentConstantExpr;
  3584. for (auto &Note : Notes)
  3585. Diag(Note.first, Note.second);
  3586. return;
  3587. }
  3588. assert(Eval.Val.hasValue());
  3589. E = ConstantExpr::Create(Context, E, Eval.Val);
  3590. }
  3591. D->addAttr(Attr);
  3592. }
  3593. static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3594. // Make sure that there is a string literal as the annotation's first
  3595. // argument.
  3596. StringRef Str;
  3597. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
  3598. return;
  3599. llvm::SmallVector<Expr *, 4> Args;
  3600. Args.reserve(AL.getNumArgs() - 1);
  3601. for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
  3602. assert(!AL.isArgIdent(Idx));
  3603. Args.push_back(AL.getArgAsExpr(Idx));
  3604. }
  3605. S.AddAnnotationAttr(D, AL, Str, Args);
  3606. }
  3607. static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3608. S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
  3609. }
  3610. void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) {
  3611. AlignValueAttr TmpAttr(Context, CI, E);
  3612. SourceLocation AttrLoc = CI.getLoc();
  3613. QualType T;
  3614. if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
  3615. T = TD->getUnderlyingType();
  3616. else if (const auto *VD = dyn_cast<ValueDecl>(D))
  3617. T = VD->getType();
  3618. else
  3619. llvm_unreachable("Unknown decl type for align_value");
  3620. if (!T->isDependentType() && !T->isAnyPointerType() &&
  3621. !T->isReferenceType() && !T->isMemberPointerType()) {
  3622. Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
  3623. << &TmpAttr << T << D->getSourceRange();
  3624. return;
  3625. }
  3626. if (!E->isValueDependent()) {
  3627. llvm::APSInt Alignment;
  3628. ExprResult ICE = VerifyIntegerConstantExpression(
  3629. E, &Alignment, diag::err_align_value_attribute_argument_not_int);
  3630. if (ICE.isInvalid())
  3631. return;
  3632. if (!Alignment.isPowerOf2()) {
  3633. Diag(AttrLoc, diag::err_alignment_not_power_of_two)
  3634. << E->getSourceRange();
  3635. return;
  3636. }
  3637. D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
  3638. return;
  3639. }
  3640. // Save dependent expressions in the AST to be instantiated.
  3641. D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
  3642. }
  3643. static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3644. // check the attribute arguments.
  3645. if (AL.getNumArgs() > 1) {
  3646. S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
  3647. return;
  3648. }
  3649. if (AL.getNumArgs() == 0) {
  3650. D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
  3651. return;
  3652. }
  3653. Expr *E = AL.getArgAsExpr(0);
  3654. if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
  3655. S.Diag(AL.getEllipsisLoc(),
  3656. diag::err_pack_expansion_without_parameter_packs);
  3657. return;
  3658. }
  3659. if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
  3660. return;
  3661. S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
  3662. }
  3663. void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
  3664. bool IsPackExpansion) {
  3665. AlignedAttr TmpAttr(Context, CI, true, E);
  3666. SourceLocation AttrLoc = CI.getLoc();
  3667. // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
  3668. if (TmpAttr.isAlignas()) {
  3669. // C++11 [dcl.align]p1:
  3670. // An alignment-specifier may be applied to a variable or to a class
  3671. // data member, but it shall not be applied to a bit-field, a function
  3672. // parameter, the formal parameter of a catch clause, or a variable
  3673. // declared with the register storage class specifier. An
  3674. // alignment-specifier may also be applied to the declaration of a class
  3675. // or enumeration type.
  3676. // C11 6.7.5/2:
  3677. // An alignment attribute shall not be specified in a declaration of
  3678. // a typedef, or a bit-field, or a function, or a parameter, or an
  3679. // object declared with the register storage-class specifier.
  3680. int DiagKind = -1;
  3681. if (isa<ParmVarDecl>(D)) {
  3682. DiagKind = 0;
  3683. } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
  3684. if (VD->getStorageClass() == SC_Register)
  3685. DiagKind = 1;
  3686. if (VD->isExceptionVariable())
  3687. DiagKind = 2;
  3688. } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
  3689. if (FD->isBitField())
  3690. DiagKind = 3;
  3691. } else if (!isa<TagDecl>(D)) {
  3692. Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
  3693. << (TmpAttr.isC11() ? ExpectedVariableOrField
  3694. : ExpectedVariableFieldOrTag);
  3695. return;
  3696. }
  3697. if (DiagKind != -1) {
  3698. Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
  3699. << &TmpAttr << DiagKind;
  3700. return;
  3701. }
  3702. }
  3703. if (E->isValueDependent()) {
  3704. // We can't support a dependent alignment on a non-dependent type,
  3705. // because we have no way to model that a type is "alignment-dependent"
  3706. // but not dependent in any other way.
  3707. if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
  3708. if (!TND->getUnderlyingType()->isDependentType()) {
  3709. Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
  3710. << E->getSourceRange();
  3711. return;
  3712. }
  3713. }
  3714. // Save dependent expressions in the AST to be instantiated.
  3715. AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
  3716. AA->setPackExpansion(IsPackExpansion);
  3717. D->addAttr(AA);
  3718. return;
  3719. }
  3720. // FIXME: Cache the number on the AL object?
  3721. llvm::APSInt Alignment;
  3722. ExprResult ICE = VerifyIntegerConstantExpression(
  3723. E, &Alignment, diag::err_aligned_attribute_argument_not_int);
  3724. if (ICE.isInvalid())
  3725. return;
  3726. uint64_t AlignVal = Alignment.getZExtValue();
  3727. // 16 byte ByVal alignment not due to a vector member is not honoured by XL
  3728. // on AIX. Emit a warning here that users are generating binary incompatible
  3729. // code to be safe.
  3730. if (AlignVal >= 16 && isa<FieldDecl>(D) &&
  3731. Context.getTargetInfo().getTriple().isOSAIX())
  3732. Diag(AttrLoc, diag::warn_not_xl_compatible) << E->getSourceRange();
  3733. // C++11 [dcl.align]p2:
  3734. // -- if the constant expression evaluates to zero, the alignment
  3735. // specifier shall have no effect
  3736. // C11 6.7.5p6:
  3737. // An alignment specification of zero has no effect.
  3738. if (!(TmpAttr.isAlignas() && !Alignment)) {
  3739. if (!llvm::isPowerOf2_64(AlignVal)) {
  3740. Diag(AttrLoc, diag::err_alignment_not_power_of_two)
  3741. << E->getSourceRange();
  3742. return;
  3743. }
  3744. }
  3745. uint64_t MaximumAlignment = Sema::MaximumAlignment;
  3746. if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
  3747. MaximumAlignment = std::min(MaximumAlignment, uint64_t(8192));
  3748. if (AlignVal > MaximumAlignment) {
  3749. Diag(AttrLoc, diag::err_attribute_aligned_too_great)
  3750. << MaximumAlignment << E->getSourceRange();
  3751. return;
  3752. }
  3753. const auto *VD = dyn_cast<VarDecl>(D);
  3754. if (VD && Context.getTargetInfo().isTLSSupported()) {
  3755. unsigned MaxTLSAlign =
  3756. Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
  3757. .getQuantity();
  3758. if (MaxTLSAlign && AlignVal > MaxTLSAlign &&
  3759. VD->getTLSKind() != VarDecl::TLS_None) {
  3760. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  3761. << (unsigned)AlignVal << VD << MaxTLSAlign;
  3762. return;
  3763. }
  3764. }
  3765. // On AIX, an aligned attribute can not decrease the alignment when applied
  3766. // to a variable declaration with vector type.
  3767. if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
  3768. const Type *Ty = VD->getType().getTypePtr();
  3769. if (Ty->isVectorType() && AlignVal < 16) {
  3770. Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
  3771. << VD->getType() << 16;
  3772. return;
  3773. }
  3774. }
  3775. AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
  3776. AA->setPackExpansion(IsPackExpansion);
  3777. D->addAttr(AA);
  3778. }
  3779. void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI,
  3780. TypeSourceInfo *TS, bool IsPackExpansion) {
  3781. // FIXME: Cache the number on the AL object if non-dependent?
  3782. // FIXME: Perform checking of type validity
  3783. AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
  3784. AA->setPackExpansion(IsPackExpansion);
  3785. D->addAttr(AA);
  3786. }
  3787. void Sema::CheckAlignasUnderalignment(Decl *D) {
  3788. assert(D->hasAttrs() && "no attributes on decl");
  3789. QualType UnderlyingTy, DiagTy;
  3790. if (const auto *VD = dyn_cast<ValueDecl>(D)) {
  3791. UnderlyingTy = DiagTy = VD->getType();
  3792. } else {
  3793. UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
  3794. if (const auto *ED = dyn_cast<EnumDecl>(D))
  3795. UnderlyingTy = ED->getIntegerType();
  3796. }
  3797. if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
  3798. return;
  3799. // C++11 [dcl.align]p5, C11 6.7.5/4:
  3800. // The combined effect of all alignment attributes in a declaration shall
  3801. // not specify an alignment that is less strict than the alignment that
  3802. // would otherwise be required for the entity being declared.
  3803. AlignedAttr *AlignasAttr = nullptr;
  3804. AlignedAttr *LastAlignedAttr = nullptr;
  3805. unsigned Align = 0;
  3806. for (auto *I : D->specific_attrs<AlignedAttr>()) {
  3807. if (I->isAlignmentDependent())
  3808. return;
  3809. if (I->isAlignas())
  3810. AlignasAttr = I;
  3811. Align = std::max(Align, I->getAlignment(Context));
  3812. LastAlignedAttr = I;
  3813. }
  3814. if (Align && DiagTy->isSizelessType()) {
  3815. Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
  3816. << LastAlignedAttr << DiagTy;
  3817. } else if (AlignasAttr && Align) {
  3818. CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
  3819. CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
  3820. if (NaturalAlign > RequestedAlign)
  3821. Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
  3822. << DiagTy << (unsigned)NaturalAlign.getQuantity();
  3823. }
  3824. }
  3825. bool Sema::checkMSInheritanceAttrOnDefinition(
  3826. CXXRecordDecl *RD, SourceRange Range, bool BestCase,
  3827. MSInheritanceModel ExplicitModel) {
  3828. assert(RD->hasDefinition() && "RD has no definition!");
  3829. // We may not have seen base specifiers or any virtual methods yet. We will
  3830. // have to wait until the record is defined to catch any mismatches.
  3831. if (!RD->getDefinition()->isCompleteDefinition())
  3832. return false;
  3833. // The unspecified model never matches what a definition could need.
  3834. if (ExplicitModel == MSInheritanceModel::Unspecified)
  3835. return false;
  3836. if (BestCase) {
  3837. if (RD->calculateInheritanceModel() == ExplicitModel)
  3838. return false;
  3839. } else {
  3840. if (RD->calculateInheritanceModel() <= ExplicitModel)
  3841. return false;
  3842. }
  3843. Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
  3844. << 0 /*definition*/;
  3845. Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
  3846. return true;
  3847. }
  3848. /// parseModeAttrArg - Parses attribute mode string and returns parsed type
  3849. /// attribute.
  3850. static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
  3851. bool &IntegerMode, bool &ComplexMode,
  3852. FloatModeKind &ExplicitType) {
  3853. IntegerMode = true;
  3854. ComplexMode = false;
  3855. ExplicitType = FloatModeKind::NoFloat;
  3856. switch (Str.size()) {
  3857. case 2:
  3858. switch (Str[0]) {
  3859. case 'Q':
  3860. DestWidth = 8;
  3861. break;
  3862. case 'H':
  3863. DestWidth = 16;
  3864. break;
  3865. case 'S':
  3866. DestWidth = 32;
  3867. break;
  3868. case 'D':
  3869. DestWidth = 64;
  3870. break;
  3871. case 'X':
  3872. DestWidth = 96;
  3873. break;
  3874. case 'K': // KFmode - IEEE quad precision (__float128)
  3875. ExplicitType = FloatModeKind::Float128;
  3876. DestWidth = Str[1] == 'I' ? 0 : 128;
  3877. break;
  3878. case 'T':
  3879. ExplicitType = FloatModeKind::LongDouble;
  3880. DestWidth = 128;
  3881. break;
  3882. case 'I':
  3883. ExplicitType = FloatModeKind::Ibm128;
  3884. DestWidth = Str[1] == 'I' ? 0 : 128;
  3885. break;
  3886. }
  3887. if (Str[1] == 'F') {
  3888. IntegerMode = false;
  3889. } else if (Str[1] == 'C') {
  3890. IntegerMode = false;
  3891. ComplexMode = true;
  3892. } else if (Str[1] != 'I') {
  3893. DestWidth = 0;
  3894. }
  3895. break;
  3896. case 4:
  3897. // FIXME: glibc uses 'word' to define register_t; this is narrower than a
  3898. // pointer on PIC16 and other embedded platforms.
  3899. if (Str == "word")
  3900. DestWidth = S.Context.getTargetInfo().getRegisterWidth();
  3901. else if (Str == "byte")
  3902. DestWidth = S.Context.getTargetInfo().getCharWidth();
  3903. break;
  3904. case 7:
  3905. if (Str == "pointer")
  3906. DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
  3907. break;
  3908. case 11:
  3909. if (Str == "unwind_word")
  3910. DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
  3911. break;
  3912. }
  3913. }
  3914. /// handleModeAttr - This attribute modifies the width of a decl with primitive
  3915. /// type.
  3916. ///
  3917. /// Despite what would be logical, the mode attribute is a decl attribute, not a
  3918. /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
  3919. /// HImode, not an intermediate pointer.
  3920. static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3921. // This attribute isn't documented, but glibc uses it. It changes
  3922. // the width of an int or unsigned int to the specified size.
  3923. if (!AL.isArgIdent(0)) {
  3924. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  3925. << AL << AANT_ArgumentIdentifier;
  3926. return;
  3927. }
  3928. IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
  3929. S.AddModeAttr(D, AL, Name);
  3930. }
  3931. void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
  3932. IdentifierInfo *Name, bool InInstantiation) {
  3933. StringRef Str = Name->getName();
  3934. normalizeName(Str);
  3935. SourceLocation AttrLoc = CI.getLoc();
  3936. unsigned DestWidth = 0;
  3937. bool IntegerMode = true;
  3938. bool ComplexMode = false;
  3939. FloatModeKind ExplicitType = FloatModeKind::NoFloat;
  3940. llvm::APInt VectorSize(64, 0);
  3941. if (Str.size() >= 4 && Str[0] == 'V') {
  3942. // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
  3943. size_t StrSize = Str.size();
  3944. size_t VectorStringLength = 0;
  3945. while ((VectorStringLength + 1) < StrSize &&
  3946. isdigit(Str[VectorStringLength + 1]))
  3947. ++VectorStringLength;
  3948. if (VectorStringLength &&
  3949. !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
  3950. VectorSize.isPowerOf2()) {
  3951. parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
  3952. IntegerMode, ComplexMode, ExplicitType);
  3953. // Avoid duplicate warning from template instantiation.
  3954. if (!InInstantiation)
  3955. Diag(AttrLoc, diag::warn_vector_mode_deprecated);
  3956. } else {
  3957. VectorSize = 0;
  3958. }
  3959. }
  3960. if (!VectorSize)
  3961. parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode,
  3962. ExplicitType);
  3963. // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
  3964. // and friends, at least with glibc.
  3965. // FIXME: Make sure floating-point mappings are accurate
  3966. // FIXME: Support XF and TF types
  3967. if (!DestWidth) {
  3968. Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
  3969. return;
  3970. }
  3971. QualType OldTy;
  3972. if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
  3973. OldTy = TD->getUnderlyingType();
  3974. else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
  3975. // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
  3976. // Try to get type from enum declaration, default to int.
  3977. OldTy = ED->getIntegerType();
  3978. if (OldTy.isNull())
  3979. OldTy = Context.IntTy;
  3980. } else
  3981. OldTy = cast<ValueDecl>(D)->getType();
  3982. if (OldTy->isDependentType()) {
  3983. D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
  3984. return;
  3985. }
  3986. // Base type can also be a vector type (see PR17453).
  3987. // Distinguish between base type and base element type.
  3988. QualType OldElemTy = OldTy;
  3989. if (const auto *VT = OldTy->getAs<VectorType>())
  3990. OldElemTy = VT->getElementType();
  3991. // GCC allows 'mode' attribute on enumeration types (even incomplete), except
  3992. // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
  3993. // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
  3994. if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
  3995. VectorSize.getBoolValue()) {
  3996. Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
  3997. return;
  3998. }
  3999. bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
  4000. !OldElemTy->isBitIntType()) ||
  4001. OldElemTy->getAs<EnumType>();
  4002. if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
  4003. !IntegralOrAnyEnumType)
  4004. Diag(AttrLoc, diag::err_mode_not_primitive);
  4005. else if (IntegerMode) {
  4006. if (!IntegralOrAnyEnumType)
  4007. Diag(AttrLoc, diag::err_mode_wrong_type);
  4008. } else if (ComplexMode) {
  4009. if (!OldElemTy->isComplexType())
  4010. Diag(AttrLoc, diag::err_mode_wrong_type);
  4011. } else {
  4012. if (!OldElemTy->isFloatingType())
  4013. Diag(AttrLoc, diag::err_mode_wrong_type);
  4014. }
  4015. QualType NewElemTy;
  4016. if (IntegerMode)
  4017. NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
  4018. OldElemTy->isSignedIntegerType());
  4019. else
  4020. NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitType);
  4021. if (NewElemTy.isNull()) {
  4022. Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
  4023. return;
  4024. }
  4025. if (ComplexMode) {
  4026. NewElemTy = Context.getComplexType(NewElemTy);
  4027. }
  4028. QualType NewTy = NewElemTy;
  4029. if (VectorSize.getBoolValue()) {
  4030. NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
  4031. VectorType::GenericVector);
  4032. } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
  4033. // Complex machine mode does not support base vector types.
  4034. if (ComplexMode) {
  4035. Diag(AttrLoc, diag::err_complex_mode_vector_type);
  4036. return;
  4037. }
  4038. unsigned NumElements = Context.getTypeSize(OldElemTy) *
  4039. OldVT->getNumElements() /
  4040. Context.getTypeSize(NewElemTy);
  4041. NewTy =
  4042. Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
  4043. }
  4044. if (NewTy.isNull()) {
  4045. Diag(AttrLoc, diag::err_mode_wrong_type);
  4046. return;
  4047. }
  4048. // Install the new type.
  4049. if (auto *TD = dyn_cast<TypedefNameDecl>(D))
  4050. TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
  4051. else if (auto *ED = dyn_cast<EnumDecl>(D))
  4052. ED->setIntegerType(NewTy);
  4053. else
  4054. cast<ValueDecl>(D)->setType(NewTy);
  4055. D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
  4056. }
  4057. static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4058. D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
  4059. }
  4060. AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
  4061. const AttributeCommonInfo &CI,
  4062. const IdentifierInfo *Ident) {
  4063. if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
  4064. Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
  4065. Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
  4066. return nullptr;
  4067. }
  4068. if (D->hasAttr<AlwaysInlineAttr>())
  4069. return nullptr;
  4070. return ::new (Context) AlwaysInlineAttr(Context, CI);
  4071. }
  4072. InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
  4073. const ParsedAttr &AL) {
  4074. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  4075. // Attribute applies to Var but not any subclass of it (like ParmVar,
  4076. // ImplicitParm or VarTemplateSpecialization).
  4077. if (VD->getKind() != Decl::Var) {
  4078. Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  4079. << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
  4080. : ExpectedVariableOrFunction);
  4081. return nullptr;
  4082. }
  4083. // Attribute does not apply to non-static local variables.
  4084. if (VD->hasLocalStorage()) {
  4085. Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
  4086. return nullptr;
  4087. }
  4088. }
  4089. return ::new (Context) InternalLinkageAttr(Context, AL);
  4090. }
  4091. InternalLinkageAttr *
  4092. Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
  4093. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  4094. // Attribute applies to Var but not any subclass of it (like ParmVar,
  4095. // ImplicitParm or VarTemplateSpecialization).
  4096. if (VD->getKind() != Decl::Var) {
  4097. Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
  4098. << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
  4099. : ExpectedVariableOrFunction);
  4100. return nullptr;
  4101. }
  4102. // Attribute does not apply to non-static local variables.
  4103. if (VD->hasLocalStorage()) {
  4104. Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
  4105. return nullptr;
  4106. }
  4107. }
  4108. return ::new (Context) InternalLinkageAttr(Context, AL);
  4109. }
  4110. MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
  4111. if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
  4112. Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
  4113. Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
  4114. return nullptr;
  4115. }
  4116. if (D->hasAttr<MinSizeAttr>())
  4117. return nullptr;
  4118. return ::new (Context) MinSizeAttr(Context, CI);
  4119. }
  4120. SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
  4121. StringRef Name) {
  4122. if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) {
  4123. if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
  4124. Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
  4125. << PrevSNA << &SNA;
  4126. Diag(SNA.getLoc(), diag::note_conflicting_attribute);
  4127. }
  4128. D->dropAttr<SwiftNameAttr>();
  4129. }
  4130. return ::new (Context) SwiftNameAttr(Context, SNA, Name);
  4131. }
  4132. OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
  4133. const AttributeCommonInfo &CI) {
  4134. if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
  4135. Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
  4136. Diag(CI.getLoc(), diag::note_conflicting_attribute);
  4137. D->dropAttr<AlwaysInlineAttr>();
  4138. }
  4139. if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
  4140. Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
  4141. Diag(CI.getLoc(), diag::note_conflicting_attribute);
  4142. D->dropAttr<MinSizeAttr>();
  4143. }
  4144. if (D->hasAttr<OptimizeNoneAttr>())
  4145. return nullptr;
  4146. return ::new (Context) OptimizeNoneAttr(Context, CI);
  4147. }
  4148. static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4149. if (AlwaysInlineAttr *Inline =
  4150. S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
  4151. D->addAttr(Inline);
  4152. }
  4153. static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4154. if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
  4155. D->addAttr(MinSize);
  4156. }
  4157. static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4158. if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
  4159. D->addAttr(Optnone);
  4160. }
  4161. static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4162. const auto *VD = cast<VarDecl>(D);
  4163. if (VD->hasLocalStorage()) {
  4164. S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
  4165. return;
  4166. }
  4167. // constexpr variable may already get an implicit constant attr, which should
  4168. // be replaced by the explicit constant attr.
  4169. if (auto *A = D->getAttr<CUDAConstantAttr>()) {
  4170. if (!A->isImplicit())
  4171. return;
  4172. D->dropAttr<CUDAConstantAttr>();
  4173. }
  4174. D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
  4175. }
  4176. static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4177. const auto *VD = cast<VarDecl>(D);
  4178. // extern __shared__ is only allowed on arrays with no length (e.g.
  4179. // "int x[]").
  4180. if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
  4181. !isa<IncompleteArrayType>(VD->getType())) {
  4182. S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
  4183. return;
  4184. }
  4185. if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
  4186. S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
  4187. << S.CurrentCUDATarget())
  4188. return;
  4189. D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
  4190. }
  4191. static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4192. const auto *FD = cast<FunctionDecl>(D);
  4193. if (!FD->getReturnType()->isVoidType() &&
  4194. !FD->getReturnType()->getAs<AutoType>() &&
  4195. !FD->getReturnType()->isInstantiationDependentType()) {
  4196. SourceRange RTRange = FD->getReturnTypeSourceRange();
  4197. S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
  4198. << FD->getType()
  4199. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  4200. : FixItHint());
  4201. return;
  4202. }
  4203. if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
  4204. if (Method->isInstance()) {
  4205. S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
  4206. << Method;
  4207. return;
  4208. }
  4209. S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
  4210. }
  4211. // Only warn for "inline" when compiling for host, to cut down on noise.
  4212. if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
  4213. S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
  4214. D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
  4215. // In host compilation the kernel is emitted as a stub function, which is
  4216. // a helper function for launching the kernel. The instructions in the helper
  4217. // function has nothing to do with the source code of the kernel. Do not emit
  4218. // debug info for the stub function to avoid confusing the debugger.
  4219. if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice)
  4220. D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
  4221. }
  4222. static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4223. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  4224. if (VD->hasLocalStorage()) {
  4225. S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
  4226. return;
  4227. }
  4228. }
  4229. if (auto *A = D->getAttr<CUDADeviceAttr>()) {
  4230. if (!A->isImplicit())
  4231. return;
  4232. D->dropAttr<CUDADeviceAttr>();
  4233. }
  4234. D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL));
  4235. }
  4236. static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4237. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  4238. if (VD->hasLocalStorage()) {
  4239. S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
  4240. return;
  4241. }
  4242. }
  4243. if (!D->hasAttr<HIPManagedAttr>())
  4244. D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL));
  4245. if (!D->hasAttr<CUDADeviceAttr>())
  4246. D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context));
  4247. }
  4248. static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4249. const auto *Fn = cast<FunctionDecl>(D);
  4250. if (!Fn->isInlineSpecified()) {
  4251. S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
  4252. return;
  4253. }
  4254. if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
  4255. S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
  4256. D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
  4257. }
  4258. static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4259. if (hasDeclarator(D)) return;
  4260. // Diagnostic is emitted elsewhere: here we store the (valid) AL
  4261. // in the Decl node for syntactic reasoning, e.g., pretty-printing.
  4262. CallingConv CC;
  4263. if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
  4264. return;
  4265. if (!isa<ObjCMethodDecl>(D)) {
  4266. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  4267. << AL << ExpectedFunctionOrMethod;
  4268. return;
  4269. }
  4270. switch (AL.getKind()) {
  4271. case ParsedAttr::AT_FastCall:
  4272. D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
  4273. return;
  4274. case ParsedAttr::AT_StdCall:
  4275. D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
  4276. return;
  4277. case ParsedAttr::AT_ThisCall:
  4278. D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
  4279. return;
  4280. case ParsedAttr::AT_CDecl:
  4281. D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
  4282. return;
  4283. case ParsedAttr::AT_Pascal:
  4284. D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
  4285. return;
  4286. case ParsedAttr::AT_SwiftCall:
  4287. D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
  4288. return;
  4289. case ParsedAttr::AT_SwiftAsyncCall:
  4290. D->addAttr(::new (S.Context) SwiftAsyncCallAttr(S.Context, AL));
  4291. return;
  4292. case ParsedAttr::AT_VectorCall:
  4293. D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
  4294. return;
  4295. case ParsedAttr::AT_MSABI:
  4296. D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
  4297. return;
  4298. case ParsedAttr::AT_SysVABI:
  4299. D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
  4300. return;
  4301. case ParsedAttr::AT_RegCall:
  4302. D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
  4303. return;
  4304. case ParsedAttr::AT_Pcs: {
  4305. PcsAttr::PCSType PCS;
  4306. switch (CC) {
  4307. case CC_AAPCS:
  4308. PCS = PcsAttr::AAPCS;
  4309. break;
  4310. case CC_AAPCS_VFP:
  4311. PCS = PcsAttr::AAPCS_VFP;
  4312. break;
  4313. default:
  4314. llvm_unreachable("unexpected calling convention in pcs attribute");
  4315. }
  4316. D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
  4317. return;
  4318. }
  4319. case ParsedAttr::AT_AArch64VectorPcs:
  4320. D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
  4321. return;
  4322. case ParsedAttr::AT_IntelOclBicc:
  4323. D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
  4324. return;
  4325. case ParsedAttr::AT_PreserveMost:
  4326. D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
  4327. return;
  4328. case ParsedAttr::AT_PreserveAll:
  4329. D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
  4330. return;
  4331. default:
  4332. llvm_unreachable("unexpected attribute kind");
  4333. }
  4334. }
  4335. static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4336. if (!AL.checkAtLeastNumArgs(S, 1))
  4337. return;
  4338. std::vector<StringRef> DiagnosticIdentifiers;
  4339. for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
  4340. StringRef RuleName;
  4341. if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
  4342. return;
  4343. // FIXME: Warn if the rule name is unknown. This is tricky because only
  4344. // clang-tidy knows about available rules.
  4345. DiagnosticIdentifiers.push_back(RuleName);
  4346. }
  4347. D->addAttr(::new (S.Context)
  4348. SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
  4349. DiagnosticIdentifiers.size()));
  4350. }
  4351. static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4352. TypeSourceInfo *DerefTypeLoc = nullptr;
  4353. QualType ParmType;
  4354. if (AL.hasParsedType()) {
  4355. ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc);
  4356. unsigned SelectIdx = ~0U;
  4357. if (ParmType->isReferenceType())
  4358. SelectIdx = 0;
  4359. else if (ParmType->isArrayType())
  4360. SelectIdx = 1;
  4361. if (SelectIdx != ~0U) {
  4362. S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
  4363. << SelectIdx << AL;
  4364. return;
  4365. }
  4366. }
  4367. // To check if earlier decl attributes do not conflict the newly parsed ones
  4368. // we always add (and check) the attribute to the canonical decl. We need
  4369. // to repeat the check for attribute mutual exclusion because we're attaching
  4370. // all of the attributes to the canonical declaration rather than the current
  4371. // declaration.
  4372. D = D->getCanonicalDecl();
  4373. if (AL.getKind() == ParsedAttr::AT_Owner) {
  4374. if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
  4375. return;
  4376. if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
  4377. const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
  4378. ? OAttr->getDerefType().getTypePtr()
  4379. : nullptr;
  4380. if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
  4381. S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
  4382. << AL << OAttr;
  4383. S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
  4384. }
  4385. return;
  4386. }
  4387. for (Decl *Redecl : D->redecls()) {
  4388. Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
  4389. }
  4390. } else {
  4391. if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
  4392. return;
  4393. if (const auto *PAttr = D->getAttr<PointerAttr>()) {
  4394. const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
  4395. ? PAttr->getDerefType().getTypePtr()
  4396. : nullptr;
  4397. if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
  4398. S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
  4399. << AL << PAttr;
  4400. S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
  4401. }
  4402. return;
  4403. }
  4404. for (Decl *Redecl : D->redecls()) {
  4405. Redecl->addAttr(::new (S.Context)
  4406. PointerAttr(S.Context, AL, DerefTypeLoc));
  4407. }
  4408. }
  4409. }
  4410. bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
  4411. const FunctionDecl *FD) {
  4412. if (Attrs.isInvalid())
  4413. return true;
  4414. if (Attrs.hasProcessingCache()) {
  4415. CC = (CallingConv) Attrs.getProcessingCache();
  4416. return false;
  4417. }
  4418. unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
  4419. if (!Attrs.checkExactlyNumArgs(*this, ReqArgs)) {
  4420. Attrs.setInvalid();
  4421. return true;
  4422. }
  4423. // TODO: diagnose uses of these conventions on the wrong target.
  4424. switch (Attrs.getKind()) {
  4425. case ParsedAttr::AT_CDecl:
  4426. CC = CC_C;
  4427. break;
  4428. case ParsedAttr::AT_FastCall:
  4429. CC = CC_X86FastCall;
  4430. break;
  4431. case ParsedAttr::AT_StdCall:
  4432. CC = CC_X86StdCall;
  4433. break;
  4434. case ParsedAttr::AT_ThisCall:
  4435. CC = CC_X86ThisCall;
  4436. break;
  4437. case ParsedAttr::AT_Pascal:
  4438. CC = CC_X86Pascal;
  4439. break;
  4440. case ParsedAttr::AT_SwiftCall:
  4441. CC = CC_Swift;
  4442. break;
  4443. case ParsedAttr::AT_SwiftAsyncCall:
  4444. CC = CC_SwiftAsync;
  4445. break;
  4446. case ParsedAttr::AT_VectorCall:
  4447. CC = CC_X86VectorCall;
  4448. break;
  4449. case ParsedAttr::AT_AArch64VectorPcs:
  4450. CC = CC_AArch64VectorCall;
  4451. break;
  4452. case ParsedAttr::AT_RegCall:
  4453. CC = CC_X86RegCall;
  4454. break;
  4455. case ParsedAttr::AT_MSABI:
  4456. CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
  4457. CC_Win64;
  4458. break;
  4459. case ParsedAttr::AT_SysVABI:
  4460. CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
  4461. CC_C;
  4462. break;
  4463. case ParsedAttr::AT_Pcs: {
  4464. StringRef StrRef;
  4465. if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
  4466. Attrs.setInvalid();
  4467. return true;
  4468. }
  4469. if (StrRef == "aapcs") {
  4470. CC = CC_AAPCS;
  4471. break;
  4472. } else if (StrRef == "aapcs-vfp") {
  4473. CC = CC_AAPCS_VFP;
  4474. break;
  4475. }
  4476. Attrs.setInvalid();
  4477. Diag(Attrs.getLoc(), diag::err_invalid_pcs);
  4478. return true;
  4479. }
  4480. case ParsedAttr::AT_IntelOclBicc:
  4481. CC = CC_IntelOclBicc;
  4482. break;
  4483. case ParsedAttr::AT_PreserveMost:
  4484. CC = CC_PreserveMost;
  4485. break;
  4486. case ParsedAttr::AT_PreserveAll:
  4487. CC = CC_PreserveAll;
  4488. break;
  4489. default: llvm_unreachable("unexpected attribute kind");
  4490. }
  4491. TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK;
  4492. const TargetInfo &TI = Context.getTargetInfo();
  4493. // CUDA functions may have host and/or device attributes which indicate
  4494. // their targeted execution environment, therefore the calling convention
  4495. // of functions in CUDA should be checked against the target deduced based
  4496. // on their host/device attributes.
  4497. if (LangOpts.CUDA) {
  4498. auto *Aux = Context.getAuxTargetInfo();
  4499. auto CudaTarget = IdentifyCUDATarget(FD);
  4500. bool CheckHost = false, CheckDevice = false;
  4501. switch (CudaTarget) {
  4502. case CFT_HostDevice:
  4503. CheckHost = true;
  4504. CheckDevice = true;
  4505. break;
  4506. case CFT_Host:
  4507. CheckHost = true;
  4508. break;
  4509. case CFT_Device:
  4510. case CFT_Global:
  4511. CheckDevice = true;
  4512. break;
  4513. case CFT_InvalidTarget:
  4514. llvm_unreachable("unexpected cuda target");
  4515. }
  4516. auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
  4517. auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
  4518. if (CheckHost && HostTI)
  4519. A = HostTI->checkCallingConvention(CC);
  4520. if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
  4521. A = DeviceTI->checkCallingConvention(CC);
  4522. } else {
  4523. A = TI.checkCallingConvention(CC);
  4524. }
  4525. switch (A) {
  4526. case TargetInfo::CCCR_OK:
  4527. break;
  4528. case TargetInfo::CCCR_Ignore:
  4529. // Treat an ignored convention as if it was an explicit C calling convention
  4530. // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
  4531. // that command line flags that change the default convention to
  4532. // __vectorcall don't affect declarations marked __stdcall.
  4533. CC = CC_C;
  4534. break;
  4535. case TargetInfo::CCCR_Error:
  4536. Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
  4537. << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
  4538. break;
  4539. case TargetInfo::CCCR_Warning: {
  4540. Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
  4541. << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
  4542. // This convention is not valid for the target. Use the default function or
  4543. // method calling convention.
  4544. bool IsCXXMethod = false, IsVariadic = false;
  4545. if (FD) {
  4546. IsCXXMethod = FD->isCXXInstanceMember();
  4547. IsVariadic = FD->isVariadic();
  4548. }
  4549. CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
  4550. break;
  4551. }
  4552. }
  4553. Attrs.setProcessingCache((unsigned) CC);
  4554. return false;
  4555. }
  4556. /// Pointer-like types in the default address space.
  4557. static bool isValidSwiftContextType(QualType Ty) {
  4558. if (!Ty->hasPointerRepresentation())
  4559. return Ty->isDependentType();
  4560. return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
  4561. }
  4562. /// Pointers and references in the default address space.
  4563. static bool isValidSwiftIndirectResultType(QualType Ty) {
  4564. if (const auto *PtrType = Ty->getAs<PointerType>()) {
  4565. Ty = PtrType->getPointeeType();
  4566. } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
  4567. Ty = RefType->getPointeeType();
  4568. } else {
  4569. return Ty->isDependentType();
  4570. }
  4571. return Ty.getAddressSpace() == LangAS::Default;
  4572. }
  4573. /// Pointers and references to pointers in the default address space.
  4574. static bool isValidSwiftErrorResultType(QualType Ty) {
  4575. if (const auto *PtrType = Ty->getAs<PointerType>()) {
  4576. Ty = PtrType->getPointeeType();
  4577. } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
  4578. Ty = RefType->getPointeeType();
  4579. } else {
  4580. return Ty->isDependentType();
  4581. }
  4582. if (!Ty.getQualifiers().empty())
  4583. return false;
  4584. return isValidSwiftContextType(Ty);
  4585. }
  4586. void Sema::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
  4587. ParameterABI abi) {
  4588. QualType type = cast<ParmVarDecl>(D)->getType();
  4589. if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
  4590. if (existingAttr->getABI() != abi) {
  4591. Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
  4592. << getParameterABISpelling(abi) << existingAttr;
  4593. Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
  4594. return;
  4595. }
  4596. }
  4597. switch (abi) {
  4598. case ParameterABI::Ordinary:
  4599. llvm_unreachable("explicit attribute for ordinary parameter ABI?");
  4600. case ParameterABI::SwiftContext:
  4601. if (!isValidSwiftContextType(type)) {
  4602. Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
  4603. << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
  4604. }
  4605. D->addAttr(::new (Context) SwiftContextAttr(Context, CI));
  4606. return;
  4607. case ParameterABI::SwiftAsyncContext:
  4608. if (!isValidSwiftContextType(type)) {
  4609. Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
  4610. << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
  4611. }
  4612. D->addAttr(::new (Context) SwiftAsyncContextAttr(Context, CI));
  4613. return;
  4614. case ParameterABI::SwiftErrorResult:
  4615. if (!isValidSwiftErrorResultType(type)) {
  4616. Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
  4617. << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type;
  4618. }
  4619. D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI));
  4620. return;
  4621. case ParameterABI::SwiftIndirectResult:
  4622. if (!isValidSwiftIndirectResultType(type)) {
  4623. Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
  4624. << getParameterABISpelling(abi) << /*pointer*/ 0 << type;
  4625. }
  4626. D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI));
  4627. return;
  4628. }
  4629. llvm_unreachable("bad parameter ABI attribute");
  4630. }
  4631. /// Checks a regparm attribute, returning true if it is ill-formed and
  4632. /// otherwise setting numParams to the appropriate value.
  4633. bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
  4634. if (AL.isInvalid())
  4635. return true;
  4636. if (!AL.checkExactlyNumArgs(*this, 1)) {
  4637. AL.setInvalid();
  4638. return true;
  4639. }
  4640. uint32_t NP;
  4641. Expr *NumParamsExpr = AL.getArgAsExpr(0);
  4642. if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
  4643. AL.setInvalid();
  4644. return true;
  4645. }
  4646. if (Context.getTargetInfo().getRegParmMax() == 0) {
  4647. Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
  4648. << NumParamsExpr->getSourceRange();
  4649. AL.setInvalid();
  4650. return true;
  4651. }
  4652. numParams = NP;
  4653. if (numParams > Context.getTargetInfo().getRegParmMax()) {
  4654. Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
  4655. << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
  4656. AL.setInvalid();
  4657. return true;
  4658. }
  4659. return false;
  4660. }
  4661. // Checks whether an argument of launch_bounds attribute is
  4662. // acceptable, performs implicit conversion to Rvalue, and returns
  4663. // non-nullptr Expr result on success. Otherwise, it returns nullptr
  4664. // and may output an error.
  4665. static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
  4666. const CUDALaunchBoundsAttr &AL,
  4667. const unsigned Idx) {
  4668. if (S.DiagnoseUnexpandedParameterPack(E))
  4669. return nullptr;
  4670. // Accept template arguments for now as they depend on something else.
  4671. // We'll get to check them when they eventually get instantiated.
  4672. if (E->isValueDependent())
  4673. return E;
  4674. Optional<llvm::APSInt> I = llvm::APSInt(64);
  4675. if (!(I = E->getIntegerConstantExpr(S.Context))) {
  4676. S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
  4677. << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
  4678. return nullptr;
  4679. }
  4680. // Make sure we can fit it in 32 bits.
  4681. if (!I->isIntN(32)) {
  4682. S.Diag(E->getExprLoc(), diag::err_ice_too_large)
  4683. << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
  4684. return nullptr;
  4685. }
  4686. if (*I < 0)
  4687. S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
  4688. << &AL << Idx << E->getSourceRange();
  4689. // We may need to perform implicit conversion of the argument.
  4690. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4691. S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
  4692. ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
  4693. assert(!ValArg.isInvalid() &&
  4694. "Unexpected PerformCopyInitialization() failure.");
  4695. return ValArg.getAs<Expr>();
  4696. }
  4697. void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
  4698. Expr *MaxThreads, Expr *MinBlocks) {
  4699. CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks);
  4700. MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
  4701. if (MaxThreads == nullptr)
  4702. return;
  4703. if (MinBlocks) {
  4704. MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
  4705. if (MinBlocks == nullptr)
  4706. return;
  4707. }
  4708. D->addAttr(::new (Context)
  4709. CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks));
  4710. }
  4711. static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4712. if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
  4713. return;
  4714. S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0),
  4715. AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr);
  4716. }
  4717. static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
  4718. const ParsedAttr &AL) {
  4719. if (!AL.isArgIdent(0)) {
  4720. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  4721. << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
  4722. return;
  4723. }
  4724. ParamIdx ArgumentIdx;
  4725. if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
  4726. ArgumentIdx))
  4727. return;
  4728. ParamIdx TypeTagIdx;
  4729. if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
  4730. TypeTagIdx))
  4731. return;
  4732. bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag";
  4733. if (IsPointer) {
  4734. // Ensure that buffer has a pointer type.
  4735. unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
  4736. if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
  4737. !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
  4738. S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
  4739. }
  4740. D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
  4741. S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx,
  4742. IsPointer));
  4743. }
  4744. static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
  4745. const ParsedAttr &AL) {
  4746. if (!AL.isArgIdent(0)) {
  4747. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  4748. << AL << 1 << AANT_ArgumentIdentifier;
  4749. return;
  4750. }
  4751. if (!AL.checkExactlyNumArgs(S, 1))
  4752. return;
  4753. if (!isa<VarDecl>(D)) {
  4754. S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
  4755. << AL << ExpectedVariable;
  4756. return;
  4757. }
  4758. IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
  4759. TypeSourceInfo *MatchingCTypeLoc = nullptr;
  4760. S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
  4761. assert(MatchingCTypeLoc && "no type source info for attribute argument");
  4762. D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(
  4763. S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(),
  4764. AL.getMustBeNull()));
  4765. }
  4766. static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4767. ParamIdx ArgCount;
  4768. if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
  4769. ArgCount,
  4770. true /* CanIndexImplicitThis */))
  4771. return;
  4772. // ArgCount isn't a parameter index [0;n), it's a count [1;n]
  4773. D->addAttr(::new (S.Context)
  4774. XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
  4775. }
  4776. static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D,
  4777. const ParsedAttr &AL) {
  4778. uint32_t Count = 0, Offset = 0;
  4779. if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Count, 0, true))
  4780. return;
  4781. if (AL.getNumArgs() == 2) {
  4782. Expr *Arg = AL.getArgAsExpr(1);
  4783. if (!checkUInt32Argument(S, AL, Arg, Offset, 1, true))
  4784. return;
  4785. if (Count < Offset) {
  4786. S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range)
  4787. << &AL << 0 << Count << Arg->getBeginLoc();
  4788. return;
  4789. }
  4790. }
  4791. D->addAttr(::new (S.Context)
  4792. PatchableFunctionEntryAttr(S.Context, AL, Count, Offset));
  4793. }
  4794. namespace {
  4795. struct IntrinToName {
  4796. uint32_t Id;
  4797. int32_t FullName;
  4798. int32_t ShortName;
  4799. };
  4800. } // unnamed namespace
  4801. static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName,
  4802. ArrayRef<IntrinToName> Map,
  4803. const char *IntrinNames) {
  4804. if (AliasName.startswith("__arm_"))
  4805. AliasName = AliasName.substr(6);
  4806. const IntrinToName *It = std::lower_bound(
  4807. Map.begin(), Map.end(), BuiltinID,
  4808. [](const IntrinToName &L, unsigned Id) { return L.Id < Id; });
  4809. if (It == Map.end() || It->Id != BuiltinID)
  4810. return false;
  4811. StringRef FullName(&IntrinNames[It->FullName]);
  4812. if (AliasName == FullName)
  4813. return true;
  4814. if (It->ShortName == -1)
  4815. return false;
  4816. StringRef ShortName(&IntrinNames[It->ShortName]);
  4817. return AliasName == ShortName;
  4818. }
  4819. static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) {
  4820. #include "clang/Basic/arm_mve_builtin_aliases.inc"
  4821. // The included file defines:
  4822. // - ArrayRef<IntrinToName> Map
  4823. // - const char IntrinNames[]
  4824. return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
  4825. }
  4826. static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) {
  4827. #include "clang/Basic/arm_cde_builtin_aliases.inc"
  4828. return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
  4829. }
  4830. static bool ArmSveAliasValid(ASTContext &Context, unsigned BuiltinID,
  4831. StringRef AliasName) {
  4832. if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  4833. BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(BuiltinID);
  4834. return BuiltinID >= AArch64::FirstSVEBuiltin &&
  4835. BuiltinID <= AArch64::LastSVEBuiltin;
  4836. }
  4837. static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4838. if (!AL.isArgIdent(0)) {
  4839. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  4840. << AL << 1 << AANT_ArgumentIdentifier;
  4841. return;
  4842. }
  4843. IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
  4844. unsigned BuiltinID = Ident->getBuiltinID();
  4845. StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
  4846. bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
  4847. if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) ||
  4848. (!IsAArch64 && !ArmMveAliasValid(BuiltinID, AliasName) &&
  4849. !ArmCdeAliasValid(BuiltinID, AliasName))) {
  4850. S.Diag(AL.getLoc(), diag::err_attribute_arm_builtin_alias);
  4851. return;
  4852. }
  4853. D->addAttr(::new (S.Context) ArmBuiltinAliasAttr(S.Context, AL, Ident));
  4854. }
  4855. static bool RISCVAliasValid(unsigned BuiltinID, StringRef AliasName) {
  4856. return BuiltinID >= RISCV::FirstRVVBuiltin &&
  4857. BuiltinID <= RISCV::LastRVVBuiltin;
  4858. }
  4859. static void handleBuiltinAliasAttr(Sema &S, Decl *D,
  4860. const ParsedAttr &AL) {
  4861. if (!AL.isArgIdent(0)) {
  4862. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  4863. << AL << 1 << AANT_ArgumentIdentifier;
  4864. return;
  4865. }
  4866. IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
  4867. unsigned BuiltinID = Ident->getBuiltinID();
  4868. StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
  4869. bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
  4870. bool IsARM = S.Context.getTargetInfo().getTriple().isARM();
  4871. bool IsRISCV = S.Context.getTargetInfo().getTriple().isRISCV();
  4872. if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) ||
  4873. (IsARM && !ArmMveAliasValid(BuiltinID, AliasName) &&
  4874. !ArmCdeAliasValid(BuiltinID, AliasName)) ||
  4875. (IsRISCV && !RISCVAliasValid(BuiltinID, AliasName)) ||
  4876. (!IsAArch64 && !IsARM && !IsRISCV)) {
  4877. S.Diag(AL.getLoc(), diag::err_attribute_builtin_alias) << AL;
  4878. return;
  4879. }
  4880. D->addAttr(::new (S.Context) BuiltinAliasAttr(S.Context, AL, Ident));
  4881. }
  4882. //===----------------------------------------------------------------------===//
  4883. // Checker-specific attribute handlers.
  4884. //===----------------------------------------------------------------------===//
  4885. static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
  4886. return QT->isDependentType() || QT->isObjCRetainableType();
  4887. }
  4888. static bool isValidSubjectOfNSAttribute(QualType QT) {
  4889. return QT->isDependentType() || QT->isObjCObjectPointerType() ||
  4890. QT->isObjCNSObjectType();
  4891. }
  4892. static bool isValidSubjectOfCFAttribute(QualType QT) {
  4893. return QT->isDependentType() || QT->isPointerType() ||
  4894. isValidSubjectOfNSAttribute(QT);
  4895. }
  4896. static bool isValidSubjectOfOSAttribute(QualType QT) {
  4897. if (QT->isDependentType())
  4898. return true;
  4899. QualType PT = QT->getPointeeType();
  4900. return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
  4901. }
  4902. void Sema::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
  4903. RetainOwnershipKind K,
  4904. bool IsTemplateInstantiation) {
  4905. ValueDecl *VD = cast<ValueDecl>(D);
  4906. switch (K) {
  4907. case RetainOwnershipKind::OS:
  4908. handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
  4909. *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()),
  4910. diag::warn_ns_attribute_wrong_parameter_type,
  4911. /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1);
  4912. return;
  4913. case RetainOwnershipKind::NS:
  4914. handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
  4915. *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()),
  4916. // These attributes are normally just advisory, but in ARC, ns_consumed
  4917. // is significant. Allow non-dependent code to contain inappropriate
  4918. // attributes even in ARC, but require template instantiations to be
  4919. // set up correctly.
  4920. ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
  4921. ? diag::err_ns_attribute_wrong_parameter_type
  4922. : diag::warn_ns_attribute_wrong_parameter_type),
  4923. /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0);
  4924. return;
  4925. case RetainOwnershipKind::CF:
  4926. handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
  4927. *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()),
  4928. diag::warn_ns_attribute_wrong_parameter_type,
  4929. /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1);
  4930. return;
  4931. }
  4932. }
  4933. static Sema::RetainOwnershipKind
  4934. parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
  4935. switch (AL.getKind()) {
  4936. case ParsedAttr::AT_CFConsumed:
  4937. case ParsedAttr::AT_CFReturnsRetained:
  4938. case ParsedAttr::AT_CFReturnsNotRetained:
  4939. return Sema::RetainOwnershipKind::CF;
  4940. case ParsedAttr::AT_OSConsumesThis:
  4941. case ParsedAttr::AT_OSConsumed:
  4942. case ParsedAttr::AT_OSReturnsRetained:
  4943. case ParsedAttr::AT_OSReturnsNotRetained:
  4944. case ParsedAttr::AT_OSReturnsRetainedOnZero:
  4945. case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
  4946. return Sema::RetainOwnershipKind::OS;
  4947. case ParsedAttr::AT_NSConsumesSelf:
  4948. case ParsedAttr::AT_NSConsumed:
  4949. case ParsedAttr::AT_NSReturnsRetained:
  4950. case ParsedAttr::AT_NSReturnsNotRetained:
  4951. case ParsedAttr::AT_NSReturnsAutoreleased:
  4952. return Sema::RetainOwnershipKind::NS;
  4953. default:
  4954. llvm_unreachable("Wrong argument supplied");
  4955. }
  4956. }
  4957. bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
  4958. if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
  4959. return false;
  4960. Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
  4961. << "'ns_returns_retained'" << 0 << 0;
  4962. return true;
  4963. }
  4964. /// \return whether the parameter is a pointer to OSObject pointer.
  4965. static bool isValidOSObjectOutParameter(const Decl *D) {
  4966. const auto *PVD = dyn_cast<ParmVarDecl>(D);
  4967. if (!PVD)
  4968. return false;
  4969. QualType QT = PVD->getType();
  4970. QualType PT = QT->getPointeeType();
  4971. return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
  4972. }
  4973. static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
  4974. const ParsedAttr &AL) {
  4975. QualType ReturnType;
  4976. Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
  4977. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  4978. ReturnType = MD->getReturnType();
  4979. } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
  4980. (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
  4981. return; // ignore: was handled as a type attribute
  4982. } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
  4983. ReturnType = PD->getType();
  4984. } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  4985. ReturnType = FD->getReturnType();
  4986. } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
  4987. // Attributes on parameters are used for out-parameters,
  4988. // passed as pointers-to-pointers.
  4989. unsigned DiagID = K == Sema::RetainOwnershipKind::CF
  4990. ? /*pointer-to-CF-pointer*/2
  4991. : /*pointer-to-OSObject-pointer*/3;
  4992. ReturnType = Param->getType()->getPointeeType();
  4993. if (ReturnType.isNull()) {
  4994. S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
  4995. << AL << DiagID << AL.getRange();
  4996. return;
  4997. }
  4998. } else if (AL.isUsedAsTypeAttr()) {
  4999. return;
  5000. } else {
  5001. AttributeDeclKind ExpectedDeclKind;
  5002. switch (AL.getKind()) {
  5003. default: llvm_unreachable("invalid ownership attribute");
  5004. case ParsedAttr::AT_NSReturnsRetained:
  5005. case ParsedAttr::AT_NSReturnsAutoreleased:
  5006. case ParsedAttr::AT_NSReturnsNotRetained:
  5007. ExpectedDeclKind = ExpectedFunctionOrMethod;
  5008. break;
  5009. case ParsedAttr::AT_OSReturnsRetained:
  5010. case ParsedAttr::AT_OSReturnsNotRetained:
  5011. case ParsedAttr::AT_CFReturnsRetained:
  5012. case ParsedAttr::AT_CFReturnsNotRetained:
  5013. ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
  5014. break;
  5015. }
  5016. S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
  5017. << AL.getRange() << AL << ExpectedDeclKind;
  5018. return;
  5019. }
  5020. bool TypeOK;
  5021. bool Cf;
  5022. unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
  5023. switch (AL.getKind()) {
  5024. default: llvm_unreachable("invalid ownership attribute");
  5025. case ParsedAttr::AT_NSReturnsRetained:
  5026. TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
  5027. Cf = false;
  5028. break;
  5029. case ParsedAttr::AT_NSReturnsAutoreleased:
  5030. case ParsedAttr::AT_NSReturnsNotRetained:
  5031. TypeOK = isValidSubjectOfNSAttribute(ReturnType);
  5032. Cf = false;
  5033. break;
  5034. case ParsedAttr::AT_CFReturnsRetained:
  5035. case ParsedAttr::AT_CFReturnsNotRetained:
  5036. TypeOK = isValidSubjectOfCFAttribute(ReturnType);
  5037. Cf = true;
  5038. break;
  5039. case ParsedAttr::AT_OSReturnsRetained:
  5040. case ParsedAttr::AT_OSReturnsNotRetained:
  5041. TypeOK = isValidSubjectOfOSAttribute(ReturnType);
  5042. Cf = true;
  5043. ParmDiagID = 3; // Pointer-to-OSObject-pointer
  5044. break;
  5045. }
  5046. if (!TypeOK) {
  5047. if (AL.isUsedAsTypeAttr())
  5048. return;
  5049. if (isa<ParmVarDecl>(D)) {
  5050. S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
  5051. << AL << ParmDiagID << AL.getRange();
  5052. } else {
  5053. // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
  5054. enum : unsigned {
  5055. Function,
  5056. Method,
  5057. Property
  5058. } SubjectKind = Function;
  5059. if (isa<ObjCMethodDecl>(D))
  5060. SubjectKind = Method;
  5061. else if (isa<ObjCPropertyDecl>(D))
  5062. SubjectKind = Property;
  5063. S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
  5064. << AL << SubjectKind << Cf << AL.getRange();
  5065. }
  5066. return;
  5067. }
  5068. switch (AL.getKind()) {
  5069. default:
  5070. llvm_unreachable("invalid ownership attribute");
  5071. case ParsedAttr::AT_NSReturnsAutoreleased:
  5072. handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
  5073. return;
  5074. case ParsedAttr::AT_CFReturnsNotRetained:
  5075. handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
  5076. return;
  5077. case ParsedAttr::AT_NSReturnsNotRetained:
  5078. handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
  5079. return;
  5080. case ParsedAttr::AT_CFReturnsRetained:
  5081. handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
  5082. return;
  5083. case ParsedAttr::AT_NSReturnsRetained:
  5084. handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
  5085. return;
  5086. case ParsedAttr::AT_OSReturnsRetained:
  5087. handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
  5088. return;
  5089. case ParsedAttr::AT_OSReturnsNotRetained:
  5090. handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
  5091. return;
  5092. };
  5093. }
  5094. static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
  5095. const ParsedAttr &Attrs) {
  5096. const int EP_ObjCMethod = 1;
  5097. const int EP_ObjCProperty = 2;
  5098. SourceLocation loc = Attrs.getLoc();
  5099. QualType resultType;
  5100. if (isa<ObjCMethodDecl>(D))
  5101. resultType = cast<ObjCMethodDecl>(D)->getReturnType();
  5102. else
  5103. resultType = cast<ObjCPropertyDecl>(D)->getType();
  5104. if (!resultType->isReferenceType() &&
  5105. (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
  5106. S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
  5107. << SourceRange(loc) << Attrs
  5108. << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
  5109. << /*non-retainable pointer*/ 2;
  5110. // Drop the attribute.
  5111. return;
  5112. }
  5113. D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs));
  5114. }
  5115. static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
  5116. const ParsedAttr &Attrs) {
  5117. const auto *Method = cast<ObjCMethodDecl>(D);
  5118. const DeclContext *DC = Method->getDeclContext();
  5119. if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
  5120. S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
  5121. << 0;
  5122. S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
  5123. return;
  5124. }
  5125. if (Method->getMethodFamily() == OMF_dealloc) {
  5126. S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
  5127. << 1;
  5128. return;
  5129. }
  5130. D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
  5131. }
  5132. static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &AL) {
  5133. auto *E = AL.getArgAsExpr(0);
  5134. auto Loc = E ? E->getBeginLoc() : AL.getLoc();
  5135. auto *DRE = dyn_cast<DeclRefExpr>(AL.getArgAsExpr(0));
  5136. if (!DRE) {
  5137. S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 0;
  5138. return;
  5139. }
  5140. auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
  5141. if (!VD) {
  5142. S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 1 << DRE->getDecl();
  5143. return;
  5144. }
  5145. if (!isNSStringType(VD->getType(), S.Context) &&
  5146. !isCFStringType(VD->getType(), S.Context)) {
  5147. S.Diag(Loc, diag::err_nserrordomain_wrong_type) << VD;
  5148. return;
  5149. }
  5150. D->addAttr(::new (S.Context) NSErrorDomainAttr(S.Context, AL, VD));
  5151. }
  5152. static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5153. IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
  5154. if (!Parm) {
  5155. S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
  5156. return;
  5157. }
  5158. // Typedefs only allow objc_bridge(id) and have some additional checking.
  5159. if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  5160. if (!Parm->Ident->isStr("id")) {
  5161. S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
  5162. return;
  5163. }
  5164. // Only allow 'cv void *'.
  5165. QualType T = TD->getUnderlyingType();
  5166. if (!T->isVoidPointerType()) {
  5167. S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
  5168. return;
  5169. }
  5170. }
  5171. D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident));
  5172. }
  5173. static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
  5174. const ParsedAttr &AL) {
  5175. IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
  5176. if (!Parm) {
  5177. S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
  5178. return;
  5179. }
  5180. D->addAttr(::new (S.Context)
  5181. ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident));
  5182. }
  5183. static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
  5184. const ParsedAttr &AL) {
  5185. IdentifierInfo *RelatedClass =
  5186. AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
  5187. if (!RelatedClass) {
  5188. S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
  5189. return;
  5190. }
  5191. IdentifierInfo *ClassMethod =
  5192. AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
  5193. IdentifierInfo *InstanceMethod =
  5194. AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
  5195. D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr(
  5196. S.Context, AL, RelatedClass, ClassMethod, InstanceMethod));
  5197. }
  5198. static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
  5199. const ParsedAttr &AL) {
  5200. DeclContext *Ctx = D->getDeclContext();
  5201. // This attribute can only be applied to methods in interfaces or class
  5202. // extensions.
  5203. if (!isa<ObjCInterfaceDecl>(Ctx) &&
  5204. !(isa<ObjCCategoryDecl>(Ctx) &&
  5205. cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
  5206. S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
  5207. return;
  5208. }
  5209. ObjCInterfaceDecl *IFace;
  5210. if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
  5211. IFace = CatDecl->getClassInterface();
  5212. else
  5213. IFace = cast<ObjCInterfaceDecl>(Ctx);
  5214. if (!IFace)
  5215. return;
  5216. IFace->setHasDesignatedInitializers();
  5217. D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL));
  5218. }
  5219. static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
  5220. StringRef MetaDataName;
  5221. if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
  5222. return;
  5223. D->addAttr(::new (S.Context)
  5224. ObjCRuntimeNameAttr(S.Context, AL, MetaDataName));
  5225. }
  5226. // When a user wants to use objc_boxable with a union or struct
  5227. // but they don't have access to the declaration (legacy/third-party code)
  5228. // then they can 'enable' this feature with a typedef:
  5229. // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
  5230. static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
  5231. bool notify = false;
  5232. auto *RD = dyn_cast<RecordDecl>(D);
  5233. if (RD && RD->getDefinition()) {
  5234. RD = RD->getDefinition();
  5235. notify = true;
  5236. }
  5237. if (RD) {
  5238. ObjCBoxableAttr *BoxableAttr =
  5239. ::new (S.Context) ObjCBoxableAttr(S.Context, AL);
  5240. RD->addAttr(BoxableAttr);
  5241. if (notify) {
  5242. // we need to notify ASTReader/ASTWriter about
  5243. // modification of existing declaration
  5244. if (ASTMutationListener *L = S.getASTMutationListener())
  5245. L->AddedAttributeToRecord(BoxableAttr, RD);
  5246. }
  5247. }
  5248. }
  5249. static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5250. if (hasDeclarator(D)) return;
  5251. S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
  5252. << AL.getRange() << AL << ExpectedVariable;
  5253. }
  5254. static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
  5255. const ParsedAttr &AL) {
  5256. const auto *VD = cast<ValueDecl>(D);
  5257. QualType QT = VD->getType();
  5258. if (!QT->isDependentType() &&
  5259. !QT->isObjCLifetimeType()) {
  5260. S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
  5261. << QT;
  5262. return;
  5263. }
  5264. Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
  5265. // If we have no lifetime yet, check the lifetime we're presumably
  5266. // going to infer.
  5267. if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
  5268. Lifetime = QT->getObjCARCImplicitLifetime();
  5269. switch (Lifetime) {
  5270. case Qualifiers::OCL_None:
  5271. assert(QT->isDependentType() &&
  5272. "didn't infer lifetime for non-dependent type?");
  5273. break;
  5274. case Qualifiers::OCL_Weak: // meaningful
  5275. case Qualifiers::OCL_Strong: // meaningful
  5276. break;
  5277. case Qualifiers::OCL_ExplicitNone:
  5278. case Qualifiers::OCL_Autoreleasing:
  5279. S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
  5280. << (Lifetime == Qualifiers::OCL_Autoreleasing);
  5281. break;
  5282. }
  5283. D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL));
  5284. }
  5285. static void handleSwiftAttrAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5286. // Make sure that there is a string literal as the annotation's single
  5287. // argument.
  5288. StringRef Str;
  5289. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
  5290. return;
  5291. D->addAttr(::new (S.Context) SwiftAttrAttr(S.Context, AL, Str));
  5292. }
  5293. static void handleSwiftBridge(Sema &S, Decl *D, const ParsedAttr &AL) {
  5294. // Make sure that there is a string literal as the annotation's single
  5295. // argument.
  5296. StringRef BT;
  5297. if (!S.checkStringLiteralArgumentAttr(AL, 0, BT))
  5298. return;
  5299. // Warn about duplicate attributes if they have different arguments, but drop
  5300. // any duplicate attributes regardless.
  5301. if (const auto *Other = D->getAttr<SwiftBridgeAttr>()) {
  5302. if (Other->getSwiftType() != BT)
  5303. S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
  5304. return;
  5305. }
  5306. D->addAttr(::new (S.Context) SwiftBridgeAttr(S.Context, AL, BT));
  5307. }
  5308. static bool isErrorParameter(Sema &S, QualType QT) {
  5309. const auto *PT = QT->getAs<PointerType>();
  5310. if (!PT)
  5311. return false;
  5312. QualType Pointee = PT->getPointeeType();
  5313. // Check for NSError**.
  5314. if (const auto *OPT = Pointee->getAs<ObjCObjectPointerType>())
  5315. if (const auto *ID = OPT->getInterfaceDecl())
  5316. if (ID->getIdentifier() == S.getNSErrorIdent())
  5317. return true;
  5318. // Check for CFError**.
  5319. if (const auto *PT = Pointee->getAs<PointerType>())
  5320. if (const auto *RT = PT->getPointeeType()->getAs<RecordType>())
  5321. if (S.isCFError(RT->getDecl()))
  5322. return true;
  5323. return false;
  5324. }
  5325. static void handleSwiftError(Sema &S, Decl *D, const ParsedAttr &AL) {
  5326. auto hasErrorParameter = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
  5327. for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
  5328. if (isErrorParameter(S, getFunctionOrMethodParamType(D, I)))
  5329. return true;
  5330. }
  5331. S.Diag(AL.getLoc(), diag::err_attr_swift_error_no_error_parameter)
  5332. << AL << isa<ObjCMethodDecl>(D);
  5333. return false;
  5334. };
  5335. auto hasPointerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
  5336. // - C, ObjC, and block pointers are definitely okay.
  5337. // - References are definitely not okay.
  5338. // - nullptr_t is weird, but acceptable.
  5339. QualType RT = getFunctionOrMethodResultType(D);
  5340. if (RT->hasPointerRepresentation() && !RT->isReferenceType())
  5341. return true;
  5342. S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
  5343. << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
  5344. << /*pointer*/ 1;
  5345. return false;
  5346. };
  5347. auto hasIntegerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
  5348. QualType RT = getFunctionOrMethodResultType(D);
  5349. if (RT->isIntegralType(S.Context))
  5350. return true;
  5351. S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
  5352. << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
  5353. << /*integral*/ 0;
  5354. return false;
  5355. };
  5356. if (D->isInvalidDecl())
  5357. return;
  5358. IdentifierLoc *Loc = AL.getArgAsIdent(0);
  5359. SwiftErrorAttr::ConventionKind Convention;
  5360. if (!SwiftErrorAttr::ConvertStrToConventionKind(Loc->Ident->getName(),
  5361. Convention)) {
  5362. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
  5363. << AL << Loc->Ident;
  5364. return;
  5365. }
  5366. switch (Convention) {
  5367. case SwiftErrorAttr::None:
  5368. // No additional validation required.
  5369. break;
  5370. case SwiftErrorAttr::NonNullError:
  5371. if (!hasErrorParameter(S, D, AL))
  5372. return;
  5373. break;
  5374. case SwiftErrorAttr::NullResult:
  5375. if (!hasErrorParameter(S, D, AL) || !hasPointerResult(S, D, AL))
  5376. return;
  5377. break;
  5378. case SwiftErrorAttr::NonZeroResult:
  5379. case SwiftErrorAttr::ZeroResult:
  5380. if (!hasErrorParameter(S, D, AL) || !hasIntegerResult(S, D, AL))
  5381. return;
  5382. break;
  5383. }
  5384. D->addAttr(::new (S.Context) SwiftErrorAttr(S.Context, AL, Convention));
  5385. }
  5386. static void checkSwiftAsyncErrorBlock(Sema &S, Decl *D,
  5387. const SwiftAsyncErrorAttr *ErrorAttr,
  5388. const SwiftAsyncAttr *AsyncAttr) {
  5389. if (AsyncAttr->getKind() == SwiftAsyncAttr::None) {
  5390. if (ErrorAttr->getConvention() != SwiftAsyncErrorAttr::None) {
  5391. S.Diag(AsyncAttr->getLocation(),
  5392. diag::err_swift_async_error_without_swift_async)
  5393. << AsyncAttr << isa<ObjCMethodDecl>(D);
  5394. }
  5395. return;
  5396. }
  5397. const ParmVarDecl *HandlerParam = getFunctionOrMethodParam(
  5398. D, AsyncAttr->getCompletionHandlerIndex().getASTIndex());
  5399. // handleSwiftAsyncAttr already verified the type is correct, so no need to
  5400. // double-check it here.
  5401. const auto *FuncTy = HandlerParam->getType()
  5402. ->castAs<BlockPointerType>()
  5403. ->getPointeeType()
  5404. ->getAs<FunctionProtoType>();
  5405. ArrayRef<QualType> BlockParams;
  5406. if (FuncTy)
  5407. BlockParams = FuncTy->getParamTypes();
  5408. switch (ErrorAttr->getConvention()) {
  5409. case SwiftAsyncErrorAttr::ZeroArgument:
  5410. case SwiftAsyncErrorAttr::NonZeroArgument: {
  5411. uint32_t ParamIdx = ErrorAttr->getHandlerParamIdx();
  5412. if (ParamIdx == 0 || ParamIdx > BlockParams.size()) {
  5413. S.Diag(ErrorAttr->getLocation(),
  5414. diag::err_attribute_argument_out_of_bounds) << ErrorAttr << 2;
  5415. return;
  5416. }
  5417. QualType ErrorParam = BlockParams[ParamIdx - 1];
  5418. if (!ErrorParam->isIntegralType(S.Context)) {
  5419. StringRef ConvStr =
  5420. ErrorAttr->getConvention() == SwiftAsyncErrorAttr::ZeroArgument
  5421. ? "zero_argument"
  5422. : "nonzero_argument";
  5423. S.Diag(ErrorAttr->getLocation(), diag::err_swift_async_error_non_integral)
  5424. << ErrorAttr << ConvStr << ParamIdx << ErrorParam;
  5425. return;
  5426. }
  5427. break;
  5428. }
  5429. case SwiftAsyncErrorAttr::NonNullError: {
  5430. bool AnyErrorParams = false;
  5431. for (QualType Param : BlockParams) {
  5432. // Check for NSError *.
  5433. if (const auto *ObjCPtrTy = Param->getAs<ObjCObjectPointerType>()) {
  5434. if (const auto *ID = ObjCPtrTy->getInterfaceDecl()) {
  5435. if (ID->getIdentifier() == S.getNSErrorIdent()) {
  5436. AnyErrorParams = true;
  5437. break;
  5438. }
  5439. }
  5440. }
  5441. // Check for CFError *.
  5442. if (const auto *PtrTy = Param->getAs<PointerType>()) {
  5443. if (const auto *RT = PtrTy->getPointeeType()->getAs<RecordType>()) {
  5444. if (S.isCFError(RT->getDecl())) {
  5445. AnyErrorParams = true;
  5446. break;
  5447. }
  5448. }
  5449. }
  5450. }
  5451. if (!AnyErrorParams) {
  5452. S.Diag(ErrorAttr->getLocation(),
  5453. diag::err_swift_async_error_no_error_parameter)
  5454. << ErrorAttr << isa<ObjCMethodDecl>(D);
  5455. return;
  5456. }
  5457. break;
  5458. }
  5459. case SwiftAsyncErrorAttr::None:
  5460. break;
  5461. }
  5462. }
  5463. static void handleSwiftAsyncError(Sema &S, Decl *D, const ParsedAttr &AL) {
  5464. IdentifierLoc *IDLoc = AL.getArgAsIdent(0);
  5465. SwiftAsyncErrorAttr::ConventionKind ConvKind;
  5466. if (!SwiftAsyncErrorAttr::ConvertStrToConventionKind(IDLoc->Ident->getName(),
  5467. ConvKind)) {
  5468. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
  5469. << AL << IDLoc->Ident;
  5470. return;
  5471. }
  5472. uint32_t ParamIdx = 0;
  5473. switch (ConvKind) {
  5474. case SwiftAsyncErrorAttr::ZeroArgument:
  5475. case SwiftAsyncErrorAttr::NonZeroArgument: {
  5476. if (!AL.checkExactlyNumArgs(S, 2))
  5477. return;
  5478. Expr *IdxExpr = AL.getArgAsExpr(1);
  5479. if (!checkUInt32Argument(S, AL, IdxExpr, ParamIdx))
  5480. return;
  5481. break;
  5482. }
  5483. case SwiftAsyncErrorAttr::NonNullError:
  5484. case SwiftAsyncErrorAttr::None: {
  5485. if (!AL.checkExactlyNumArgs(S, 1))
  5486. return;
  5487. break;
  5488. }
  5489. }
  5490. auto *ErrorAttr =
  5491. ::new (S.Context) SwiftAsyncErrorAttr(S.Context, AL, ConvKind, ParamIdx);
  5492. D->addAttr(ErrorAttr);
  5493. if (auto *AsyncAttr = D->getAttr<SwiftAsyncAttr>())
  5494. checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
  5495. }
  5496. // For a function, this will validate a compound Swift name, e.g.
  5497. // <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, and
  5498. // the function will output the number of parameter names, and whether this is a
  5499. // single-arg initializer.
  5500. //
  5501. // For a type, enum constant, property, or variable declaration, this will
  5502. // validate either a simple identifier, or a qualified
  5503. // <code>context.identifier</code> name.
  5504. static bool
  5505. validateSwiftFunctionName(Sema &S, const ParsedAttr &AL, SourceLocation Loc,
  5506. StringRef Name, unsigned &SwiftParamCount,
  5507. bool &IsSingleParamInit) {
  5508. SwiftParamCount = 0;
  5509. IsSingleParamInit = false;
  5510. // Check whether this will be mapped to a getter or setter of a property.
  5511. bool IsGetter = false, IsSetter = false;
  5512. if (Name.startswith("getter:")) {
  5513. IsGetter = true;
  5514. Name = Name.substr(7);
  5515. } else if (Name.startswith("setter:")) {
  5516. IsSetter = true;
  5517. Name = Name.substr(7);
  5518. }
  5519. if (Name.back() != ')') {
  5520. S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
  5521. return false;
  5522. }
  5523. bool IsMember = false;
  5524. StringRef ContextName, BaseName, Parameters;
  5525. std::tie(BaseName, Parameters) = Name.split('(');
  5526. // Split at the first '.', if it exists, which separates the context name
  5527. // from the base name.
  5528. std::tie(ContextName, BaseName) = BaseName.split('.');
  5529. if (BaseName.empty()) {
  5530. BaseName = ContextName;
  5531. ContextName = StringRef();
  5532. } else if (ContextName.empty() || !isValidAsciiIdentifier(ContextName)) {
  5533. S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
  5534. << AL << /*context*/ 1;
  5535. return false;
  5536. } else {
  5537. IsMember = true;
  5538. }
  5539. if (!isValidAsciiIdentifier(BaseName) || BaseName == "_") {
  5540. S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
  5541. << AL << /*basename*/ 0;
  5542. return false;
  5543. }
  5544. bool IsSubscript = BaseName == "subscript";
  5545. // A subscript accessor must be a getter or setter.
  5546. if (IsSubscript && !IsGetter && !IsSetter) {
  5547. S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
  5548. << AL << /* getter or setter */ 0;
  5549. return false;
  5550. }
  5551. if (Parameters.empty()) {
  5552. S.Diag(Loc, diag::warn_attr_swift_name_missing_parameters) << AL;
  5553. return false;
  5554. }
  5555. assert(Parameters.back() == ')' && "expected ')'");
  5556. Parameters = Parameters.drop_back(); // ')'
  5557. if (Parameters.empty()) {
  5558. // Setters and subscripts must have at least one parameter.
  5559. if (IsSubscript) {
  5560. S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
  5561. << AL << /* have at least one parameter */1;
  5562. return false;
  5563. }
  5564. if (IsSetter) {
  5565. S.Diag(Loc, diag::warn_attr_swift_name_setter_parameters) << AL;
  5566. return false;
  5567. }
  5568. return true;
  5569. }
  5570. if (Parameters.back() != ':') {
  5571. S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
  5572. return false;
  5573. }
  5574. StringRef CurrentParam;
  5575. llvm::Optional<unsigned> SelfLocation;
  5576. unsigned NewValueCount = 0;
  5577. llvm::Optional<unsigned> NewValueLocation;
  5578. do {
  5579. std::tie(CurrentParam, Parameters) = Parameters.split(':');
  5580. if (!isValidAsciiIdentifier(CurrentParam)) {
  5581. S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
  5582. << AL << /*parameter*/2;
  5583. return false;
  5584. }
  5585. if (IsMember && CurrentParam == "self") {
  5586. // "self" indicates the "self" argument for a member.
  5587. // More than one "self"?
  5588. if (SelfLocation) {
  5589. S.Diag(Loc, diag::warn_attr_swift_name_multiple_selfs) << AL;
  5590. return false;
  5591. }
  5592. // The "self" location is the current parameter.
  5593. SelfLocation = SwiftParamCount;
  5594. } else if (CurrentParam == "newValue") {
  5595. // "newValue" indicates the "newValue" argument for a setter.
  5596. // There should only be one 'newValue', but it's only significant for
  5597. // subscript accessors, so don't error right away.
  5598. ++NewValueCount;
  5599. NewValueLocation = SwiftParamCount;
  5600. }
  5601. ++SwiftParamCount;
  5602. } while (!Parameters.empty());
  5603. // Only instance subscripts are currently supported.
  5604. if (IsSubscript && !SelfLocation) {
  5605. S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
  5606. << AL << /*have a 'self:' parameter*/2;
  5607. return false;
  5608. }
  5609. IsSingleParamInit =
  5610. SwiftParamCount == 1 && BaseName == "init" && CurrentParam != "_";
  5611. // Check the number of parameters for a getter/setter.
  5612. if (IsGetter || IsSetter) {
  5613. // Setters have one parameter for the new value.
  5614. unsigned NumExpectedParams = IsGetter ? 0 : 1;
  5615. unsigned ParamDiag =
  5616. IsGetter ? diag::warn_attr_swift_name_getter_parameters
  5617. : diag::warn_attr_swift_name_setter_parameters;
  5618. // Instance methods have one parameter for "self".
  5619. if (SelfLocation)
  5620. ++NumExpectedParams;
  5621. // Subscripts may have additional parameters beyond the expected params for
  5622. // the index.
  5623. if (IsSubscript) {
  5624. if (SwiftParamCount < NumExpectedParams) {
  5625. S.Diag(Loc, ParamDiag) << AL;
  5626. return false;
  5627. }
  5628. // A subscript setter must explicitly label its newValue parameter to
  5629. // distinguish it from index parameters.
  5630. if (IsSetter) {
  5631. if (!NewValueLocation) {
  5632. S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_no_newValue)
  5633. << AL;
  5634. return false;
  5635. }
  5636. if (NewValueCount > 1) {
  5637. S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_multiple_newValues)
  5638. << AL;
  5639. return false;
  5640. }
  5641. } else {
  5642. // Subscript getters should have no 'newValue:' parameter.
  5643. if (NewValueLocation) {
  5644. S.Diag(Loc, diag::warn_attr_swift_name_subscript_getter_newValue)
  5645. << AL;
  5646. return false;
  5647. }
  5648. }
  5649. } else {
  5650. // Property accessors must have exactly the number of expected params.
  5651. if (SwiftParamCount != NumExpectedParams) {
  5652. S.Diag(Loc, ParamDiag) << AL;
  5653. return false;
  5654. }
  5655. }
  5656. }
  5657. return true;
  5658. }
  5659. bool Sema::DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
  5660. const ParsedAttr &AL, bool IsAsync) {
  5661. if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
  5662. ArrayRef<ParmVarDecl*> Params;
  5663. unsigned ParamCount;
  5664. if (const auto *Method = dyn_cast<ObjCMethodDecl>(D)) {
  5665. ParamCount = Method->getSelector().getNumArgs();
  5666. Params = Method->parameters().slice(0, ParamCount);
  5667. } else {
  5668. const auto *F = cast<FunctionDecl>(D);
  5669. ParamCount = F->getNumParams();
  5670. Params = F->parameters();
  5671. if (!F->hasWrittenPrototype()) {
  5672. Diag(Loc, diag::warn_attribute_wrong_decl_type) << AL
  5673. << ExpectedFunctionWithProtoType;
  5674. return false;
  5675. }
  5676. }
  5677. // The async name drops the last callback parameter.
  5678. if (IsAsync) {
  5679. if (ParamCount == 0) {
  5680. Diag(Loc, diag::warn_attr_swift_name_decl_missing_params)
  5681. << AL << isa<ObjCMethodDecl>(D);
  5682. return false;
  5683. }
  5684. ParamCount -= 1;
  5685. }
  5686. unsigned SwiftParamCount;
  5687. bool IsSingleParamInit;
  5688. if (!validateSwiftFunctionName(*this, AL, Loc, Name,
  5689. SwiftParamCount, IsSingleParamInit))
  5690. return false;
  5691. bool ParamCountValid;
  5692. if (SwiftParamCount == ParamCount) {
  5693. ParamCountValid = true;
  5694. } else if (SwiftParamCount > ParamCount) {
  5695. ParamCountValid = IsSingleParamInit && ParamCount == 0;
  5696. } else {
  5697. // We have fewer Swift parameters than Objective-C parameters, but that
  5698. // might be because we've transformed some of them. Check for potential
  5699. // "out" parameters and err on the side of not warning.
  5700. unsigned MaybeOutParamCount =
  5701. llvm::count_if(Params, [](const ParmVarDecl *Param) -> bool {
  5702. QualType ParamTy = Param->getType();
  5703. if (ParamTy->isReferenceType() || ParamTy->isPointerType())
  5704. return !ParamTy->getPointeeType().isConstQualified();
  5705. return false;
  5706. });
  5707. ParamCountValid = SwiftParamCount + MaybeOutParamCount >= ParamCount;
  5708. }
  5709. if (!ParamCountValid) {
  5710. Diag(Loc, diag::warn_attr_swift_name_num_params)
  5711. << (SwiftParamCount > ParamCount) << AL << ParamCount
  5712. << SwiftParamCount;
  5713. return false;
  5714. }
  5715. } else if ((isa<EnumConstantDecl>(D) || isa<ObjCProtocolDecl>(D) ||
  5716. isa<ObjCInterfaceDecl>(D) || isa<ObjCPropertyDecl>(D) ||
  5717. isa<VarDecl>(D) || isa<TypedefNameDecl>(D) || isa<TagDecl>(D) ||
  5718. isa<IndirectFieldDecl>(D) || isa<FieldDecl>(D)) &&
  5719. !IsAsync) {
  5720. StringRef ContextName, BaseName;
  5721. std::tie(ContextName, BaseName) = Name.split('.');
  5722. if (BaseName.empty()) {
  5723. BaseName = ContextName;
  5724. ContextName = StringRef();
  5725. } else if (!isValidAsciiIdentifier(ContextName)) {
  5726. Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
  5727. << /*context*/1;
  5728. return false;
  5729. }
  5730. if (!isValidAsciiIdentifier(BaseName)) {
  5731. Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
  5732. << /*basename*/0;
  5733. return false;
  5734. }
  5735. } else {
  5736. Diag(Loc, diag::warn_attr_swift_name_decl_kind) << AL;
  5737. return false;
  5738. }
  5739. return true;
  5740. }
  5741. static void handleSwiftName(Sema &S, Decl *D, const ParsedAttr &AL) {
  5742. StringRef Name;
  5743. SourceLocation Loc;
  5744. if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
  5745. return;
  5746. if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/false))
  5747. return;
  5748. D->addAttr(::new (S.Context) SwiftNameAttr(S.Context, AL, Name));
  5749. }
  5750. static void handleSwiftAsyncName(Sema &S, Decl *D, const ParsedAttr &AL) {
  5751. StringRef Name;
  5752. SourceLocation Loc;
  5753. if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
  5754. return;
  5755. if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/true))
  5756. return;
  5757. D->addAttr(::new (S.Context) SwiftAsyncNameAttr(S.Context, AL, Name));
  5758. }
  5759. static void handleSwiftNewType(Sema &S, Decl *D, const ParsedAttr &AL) {
  5760. // Make sure that there is an identifier as the annotation's single argument.
  5761. if (!AL.checkExactlyNumArgs(S, 1))
  5762. return;
  5763. if (!AL.isArgIdent(0)) {
  5764. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  5765. << AL << AANT_ArgumentIdentifier;
  5766. return;
  5767. }
  5768. SwiftNewTypeAttr::NewtypeKind Kind;
  5769. IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
  5770. if (!SwiftNewTypeAttr::ConvertStrToNewtypeKind(II->getName(), Kind)) {
  5771. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
  5772. return;
  5773. }
  5774. if (!isa<TypedefNameDecl>(D)) {
  5775. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
  5776. << AL << "typedefs";
  5777. return;
  5778. }
  5779. D->addAttr(::new (S.Context) SwiftNewTypeAttr(S.Context, AL, Kind));
  5780. }
  5781. static void handleSwiftAsyncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5782. if (!AL.isArgIdent(0)) {
  5783. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  5784. << AL << 1 << AANT_ArgumentIdentifier;
  5785. return;
  5786. }
  5787. SwiftAsyncAttr::Kind Kind;
  5788. IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
  5789. if (!SwiftAsyncAttr::ConvertStrToKind(II->getName(), Kind)) {
  5790. S.Diag(AL.getLoc(), diag::err_swift_async_no_access) << AL << II;
  5791. return;
  5792. }
  5793. ParamIdx Idx;
  5794. if (Kind == SwiftAsyncAttr::None) {
  5795. // If this is 'none', then there shouldn't be any additional arguments.
  5796. if (!AL.checkExactlyNumArgs(S, 1))
  5797. return;
  5798. } else {
  5799. // Non-none swift_async requires a completion handler index argument.
  5800. if (!AL.checkExactlyNumArgs(S, 2))
  5801. return;
  5802. Expr *HandlerIdx = AL.getArgAsExpr(1);
  5803. if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, HandlerIdx, Idx))
  5804. return;
  5805. const ParmVarDecl *CompletionBlock =
  5806. getFunctionOrMethodParam(D, Idx.getASTIndex());
  5807. QualType CompletionBlockType = CompletionBlock->getType();
  5808. if (!CompletionBlockType->isBlockPointerType()) {
  5809. S.Diag(CompletionBlock->getLocation(),
  5810. diag::err_swift_async_bad_block_type)
  5811. << CompletionBlock->getType();
  5812. return;
  5813. }
  5814. QualType BlockTy =
  5815. CompletionBlockType->castAs<BlockPointerType>()->getPointeeType();
  5816. if (!BlockTy->castAs<FunctionType>()->getReturnType()->isVoidType()) {
  5817. S.Diag(CompletionBlock->getLocation(),
  5818. diag::err_swift_async_bad_block_type)
  5819. << CompletionBlock->getType();
  5820. return;
  5821. }
  5822. }
  5823. auto *AsyncAttr =
  5824. ::new (S.Context) SwiftAsyncAttr(S.Context, AL, Kind, Idx);
  5825. D->addAttr(AsyncAttr);
  5826. if (auto *ErrorAttr = D->getAttr<SwiftAsyncErrorAttr>())
  5827. checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
  5828. }
  5829. //===----------------------------------------------------------------------===//
  5830. // Microsoft specific attribute handlers.
  5831. //===----------------------------------------------------------------------===//
  5832. UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
  5833. StringRef UuidAsWritten, MSGuidDecl *GuidDecl) {
  5834. if (const auto *UA = D->getAttr<UuidAttr>()) {
  5835. if (declaresSameEntity(UA->getGuidDecl(), GuidDecl))
  5836. return nullptr;
  5837. if (!UA->getGuid().empty()) {
  5838. Diag(UA->getLocation(), diag::err_mismatched_uuid);
  5839. Diag(CI.getLoc(), diag::note_previous_uuid);
  5840. D->dropAttr<UuidAttr>();
  5841. }
  5842. }
  5843. return ::new (Context) UuidAttr(Context, CI, UuidAsWritten, GuidDecl);
  5844. }
  5845. static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5846. if (!S.LangOpts.CPlusPlus) {
  5847. S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
  5848. << AL << AttributeLangSupport::C;
  5849. return;
  5850. }
  5851. StringRef OrigStrRef;
  5852. SourceLocation LiteralLoc;
  5853. if (!S.checkStringLiteralArgumentAttr(AL, 0, OrigStrRef, &LiteralLoc))
  5854. return;
  5855. // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
  5856. // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
  5857. StringRef StrRef = OrigStrRef;
  5858. if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
  5859. StrRef = StrRef.drop_front().drop_back();
  5860. // Validate GUID length.
  5861. if (StrRef.size() != 36) {
  5862. S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
  5863. return;
  5864. }
  5865. for (unsigned i = 0; i < 36; ++i) {
  5866. if (i == 8 || i == 13 || i == 18 || i == 23) {
  5867. if (StrRef[i] != '-') {
  5868. S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
  5869. return;
  5870. }
  5871. } else if (!isHexDigit(StrRef[i])) {
  5872. S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
  5873. return;
  5874. }
  5875. }
  5876. // Convert to our parsed format and canonicalize.
  5877. MSGuidDecl::Parts Parsed;
  5878. StrRef.substr(0, 8).getAsInteger(16, Parsed.Part1);
  5879. StrRef.substr(9, 4).getAsInteger(16, Parsed.Part2);
  5880. StrRef.substr(14, 4).getAsInteger(16, Parsed.Part3);
  5881. for (unsigned i = 0; i != 8; ++i)
  5882. StrRef.substr(19 + 2 * i + (i >= 2 ? 1 : 0), 2)
  5883. .getAsInteger(16, Parsed.Part4And5[i]);
  5884. MSGuidDecl *Guid = S.Context.getMSGuidDecl(Parsed);
  5885. // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
  5886. // the only thing in the [] list, the [] too), and add an insertion of
  5887. // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
  5888. // separating attributes nor of the [ and the ] are in the AST.
  5889. // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
  5890. // on cfe-dev.
  5891. if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
  5892. S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
  5893. UuidAttr *UA = S.mergeUuidAttr(D, AL, OrigStrRef, Guid);
  5894. if (UA)
  5895. D->addAttr(UA);
  5896. }
  5897. static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5898. if (!S.LangOpts.CPlusPlus) {
  5899. S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
  5900. << AL << AttributeLangSupport::C;
  5901. return;
  5902. }
  5903. MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
  5904. D, AL, /*BestCase=*/true, (MSInheritanceModel)AL.getSemanticSpelling());
  5905. if (IA) {
  5906. D->addAttr(IA);
  5907. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  5908. }
  5909. }
  5910. static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5911. const auto *VD = cast<VarDecl>(D);
  5912. if (!S.Context.getTargetInfo().isTLSSupported()) {
  5913. S.Diag(AL.getLoc(), diag::err_thread_unsupported);
  5914. return;
  5915. }
  5916. if (VD->getTSCSpec() != TSCS_unspecified) {
  5917. S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
  5918. return;
  5919. }
  5920. if (VD->hasLocalStorage()) {
  5921. S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
  5922. return;
  5923. }
  5924. D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL));
  5925. }
  5926. static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5927. SmallVector<StringRef, 4> Tags;
  5928. for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
  5929. StringRef Tag;
  5930. if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
  5931. return;
  5932. Tags.push_back(Tag);
  5933. }
  5934. if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
  5935. if (!NS->isInline()) {
  5936. S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
  5937. return;
  5938. }
  5939. if (NS->isAnonymousNamespace()) {
  5940. S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
  5941. return;
  5942. }
  5943. if (AL.getNumArgs() == 0)
  5944. Tags.push_back(NS->getName());
  5945. } else if (!AL.checkAtLeastNumArgs(S, 1))
  5946. return;
  5947. // Store tags sorted and without duplicates.
  5948. llvm::sort(Tags);
  5949. Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
  5950. D->addAttr(::new (S.Context)
  5951. AbiTagAttr(S.Context, AL, Tags.data(), Tags.size()));
  5952. }
  5953. static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5954. // Check the attribute arguments.
  5955. if (AL.getNumArgs() > 1) {
  5956. S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
  5957. return;
  5958. }
  5959. StringRef Str;
  5960. SourceLocation ArgLoc;
  5961. if (AL.getNumArgs() == 0)
  5962. Str = "";
  5963. else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
  5964. return;
  5965. ARMInterruptAttr::InterruptType Kind;
  5966. if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
  5967. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
  5968. << ArgLoc;
  5969. return;
  5970. }
  5971. D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind));
  5972. }
  5973. static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5974. // MSP430 'interrupt' attribute is applied to
  5975. // a function with no parameters and void return type.
  5976. if (!isFunctionOrMethod(D)) {
  5977. S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
  5978. << "'interrupt'" << ExpectedFunctionOrMethod;
  5979. return;
  5980. }
  5981. if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
  5982. S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
  5983. << /*MSP430*/ 1 << 0;
  5984. return;
  5985. }
  5986. if (!getFunctionOrMethodResultType(D)->isVoidType()) {
  5987. S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
  5988. << /*MSP430*/ 1 << 1;
  5989. return;
  5990. }
  5991. // The attribute takes one integer argument.
  5992. if (!AL.checkExactlyNumArgs(S, 1))
  5993. return;
  5994. if (!AL.isArgExpr(0)) {
  5995. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  5996. << AL << AANT_ArgumentIntegerConstant;
  5997. return;
  5998. }
  5999. Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
  6000. Optional<llvm::APSInt> NumParams = llvm::APSInt(32);
  6001. if (!(NumParams = NumParamsExpr->getIntegerConstantExpr(S.Context))) {
  6002. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  6003. << AL << AANT_ArgumentIntegerConstant
  6004. << NumParamsExpr->getSourceRange();
  6005. return;
  6006. }
  6007. // The argument should be in range 0..63.
  6008. unsigned Num = NumParams->getLimitedValue(255);
  6009. if (Num > 63) {
  6010. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
  6011. << AL << (int)NumParams->getSExtValue()
  6012. << NumParamsExpr->getSourceRange();
  6013. return;
  6014. }
  6015. D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num));
  6016. D->addAttr(UsedAttr::CreateImplicit(S.Context));
  6017. }
  6018. static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6019. // Only one optional argument permitted.
  6020. if (AL.getNumArgs() > 1) {
  6021. S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
  6022. return;
  6023. }
  6024. StringRef Str;
  6025. SourceLocation ArgLoc;
  6026. if (AL.getNumArgs() == 0)
  6027. Str = "";
  6028. else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
  6029. return;
  6030. // Semantic checks for a function with the 'interrupt' attribute for MIPS:
  6031. // a) Must be a function.
  6032. // b) Must have no parameters.
  6033. // c) Must have the 'void' return type.
  6034. // d) Cannot have the 'mips16' attribute, as that instruction set
  6035. // lacks the 'eret' instruction.
  6036. // e) The attribute itself must either have no argument or one of the
  6037. // valid interrupt types, see [MipsInterruptDocs].
  6038. if (!isFunctionOrMethod(D)) {
  6039. S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
  6040. << "'interrupt'" << ExpectedFunctionOrMethod;
  6041. return;
  6042. }
  6043. if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
  6044. S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
  6045. << /*MIPS*/ 0 << 0;
  6046. return;
  6047. }
  6048. if (!getFunctionOrMethodResultType(D)->isVoidType()) {
  6049. S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
  6050. << /*MIPS*/ 0 << 1;
  6051. return;
  6052. }
  6053. // We still have to do this manually because the Interrupt attributes are
  6054. // a bit special due to sharing their spellings across targets.
  6055. if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
  6056. return;
  6057. MipsInterruptAttr::InterruptType Kind;
  6058. if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
  6059. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
  6060. << AL << "'" + std::string(Str) + "'";
  6061. return;
  6062. }
  6063. D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind));
  6064. }
  6065. static void handleM68kInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6066. if (!AL.checkExactlyNumArgs(S, 1))
  6067. return;
  6068. if (!AL.isArgExpr(0)) {
  6069. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  6070. << AL << AANT_ArgumentIntegerConstant;
  6071. return;
  6072. }
  6073. // FIXME: Check for decl - it should be void ()(void).
  6074. Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
  6075. auto MaybeNumParams = NumParamsExpr->getIntegerConstantExpr(S.Context);
  6076. if (!MaybeNumParams) {
  6077. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  6078. << AL << AANT_ArgumentIntegerConstant
  6079. << NumParamsExpr->getSourceRange();
  6080. return;
  6081. }
  6082. unsigned Num = MaybeNumParams->getLimitedValue(255);
  6083. if ((Num & 1) || Num > 30) {
  6084. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
  6085. << AL << (int)MaybeNumParams->getSExtValue()
  6086. << NumParamsExpr->getSourceRange();
  6087. return;
  6088. }
  6089. D->addAttr(::new (S.Context) M68kInterruptAttr(S.Context, AL, Num));
  6090. D->addAttr(UsedAttr::CreateImplicit(S.Context));
  6091. }
  6092. static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6093. // Semantic checks for a function with the 'interrupt' attribute.
  6094. // a) Must be a function.
  6095. // b) Must have the 'void' return type.
  6096. // c) Must take 1 or 2 arguments.
  6097. // d) The 1st argument must be a pointer.
  6098. // e) The 2nd argument (if any) must be an unsigned integer.
  6099. if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
  6100. CXXMethodDecl::isStaticOverloadedOperator(
  6101. cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
  6102. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  6103. << AL << ExpectedFunctionWithProtoType;
  6104. return;
  6105. }
  6106. // Interrupt handler must have void return type.
  6107. if (!getFunctionOrMethodResultType(D)->isVoidType()) {
  6108. S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
  6109. diag::err_anyx86_interrupt_attribute)
  6110. << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
  6111. ? 0
  6112. : 1)
  6113. << 0;
  6114. return;
  6115. }
  6116. // Interrupt handler must have 1 or 2 parameters.
  6117. unsigned NumParams = getFunctionOrMethodNumParams(D);
  6118. if (NumParams < 1 || NumParams > 2) {
  6119. S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
  6120. << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
  6121. ? 0
  6122. : 1)
  6123. << 1;
  6124. return;
  6125. }
  6126. // The first argument must be a pointer.
  6127. if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
  6128. S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
  6129. diag::err_anyx86_interrupt_attribute)
  6130. << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
  6131. ? 0
  6132. : 1)
  6133. << 2;
  6134. return;
  6135. }
  6136. // The second argument, if present, must be an unsigned integer.
  6137. unsigned TypeSize =
  6138. S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
  6139. ? 64
  6140. : 32;
  6141. if (NumParams == 2 &&
  6142. (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
  6143. S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
  6144. S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
  6145. diag::err_anyx86_interrupt_attribute)
  6146. << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
  6147. ? 0
  6148. : 1)
  6149. << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
  6150. return;
  6151. }
  6152. D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL));
  6153. D->addAttr(UsedAttr::CreateImplicit(S.Context));
  6154. }
  6155. static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6156. if (!isFunctionOrMethod(D)) {
  6157. S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
  6158. << "'interrupt'" << ExpectedFunction;
  6159. return;
  6160. }
  6161. if (!AL.checkExactlyNumArgs(S, 0))
  6162. return;
  6163. handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
  6164. }
  6165. static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6166. if (!isFunctionOrMethod(D)) {
  6167. S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
  6168. << "'signal'" << ExpectedFunction;
  6169. return;
  6170. }
  6171. if (!AL.checkExactlyNumArgs(S, 0))
  6172. return;
  6173. handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
  6174. }
  6175. static void handleBPFPreserveAIRecord(Sema &S, RecordDecl *RD) {
  6176. // Add preserve_access_index attribute to all fields and inner records.
  6177. for (auto D : RD->decls()) {
  6178. if (D->hasAttr<BPFPreserveAccessIndexAttr>())
  6179. continue;
  6180. D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S.Context));
  6181. if (auto *Rec = dyn_cast<RecordDecl>(D))
  6182. handleBPFPreserveAIRecord(S, Rec);
  6183. }
  6184. }
  6185. static void handleBPFPreserveAccessIndexAttr(Sema &S, Decl *D,
  6186. const ParsedAttr &AL) {
  6187. auto *Rec = cast<RecordDecl>(D);
  6188. handleBPFPreserveAIRecord(S, Rec);
  6189. Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL));
  6190. }
  6191. static bool hasBTFDeclTagAttr(Decl *D, StringRef Tag) {
  6192. for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
  6193. if (I->getBTFDeclTag() == Tag)
  6194. return true;
  6195. }
  6196. return false;
  6197. }
  6198. static void handleBTFDeclTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6199. StringRef Str;
  6200. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
  6201. return;
  6202. if (hasBTFDeclTagAttr(D, Str))
  6203. return;
  6204. D->addAttr(::new (S.Context) BTFDeclTagAttr(S.Context, AL, Str));
  6205. }
  6206. BTFDeclTagAttr *Sema::mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL) {
  6207. if (hasBTFDeclTagAttr(D, AL.getBTFDeclTag()))
  6208. return nullptr;
  6209. return ::new (Context) BTFDeclTagAttr(Context, AL, AL.getBTFDeclTag());
  6210. }
  6211. static void handleWebAssemblyExportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6212. if (!isFunctionOrMethod(D)) {
  6213. S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
  6214. << "'export_name'" << ExpectedFunction;
  6215. return;
  6216. }
  6217. auto *FD = cast<FunctionDecl>(D);
  6218. if (FD->isThisDeclarationADefinition()) {
  6219. S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
  6220. return;
  6221. }
  6222. StringRef Str;
  6223. SourceLocation ArgLoc;
  6224. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
  6225. return;
  6226. D->addAttr(::new (S.Context) WebAssemblyExportNameAttr(S.Context, AL, Str));
  6227. D->addAttr(UsedAttr::CreateImplicit(S.Context));
  6228. }
  6229. WebAssemblyImportModuleAttr *
  6230. Sema::mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL) {
  6231. auto *FD = cast<FunctionDecl>(D);
  6232. if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
  6233. if (ExistingAttr->getImportModule() == AL.getImportModule())
  6234. return nullptr;
  6235. Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 0
  6236. << ExistingAttr->getImportModule() << AL.getImportModule();
  6237. Diag(AL.getLoc(), diag::note_previous_attribute);
  6238. return nullptr;
  6239. }
  6240. if (FD->hasBody()) {
  6241. Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
  6242. return nullptr;
  6243. }
  6244. return ::new (Context) WebAssemblyImportModuleAttr(Context, AL,
  6245. AL.getImportModule());
  6246. }
  6247. WebAssemblyImportNameAttr *
  6248. Sema::mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL) {
  6249. auto *FD = cast<FunctionDecl>(D);
  6250. if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportNameAttr>()) {
  6251. if (ExistingAttr->getImportName() == AL.getImportName())
  6252. return nullptr;
  6253. Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 1
  6254. << ExistingAttr->getImportName() << AL.getImportName();
  6255. Diag(AL.getLoc(), diag::note_previous_attribute);
  6256. return nullptr;
  6257. }
  6258. if (FD->hasBody()) {
  6259. Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
  6260. return nullptr;
  6261. }
  6262. return ::new (Context) WebAssemblyImportNameAttr(Context, AL,
  6263. AL.getImportName());
  6264. }
  6265. static void
  6266. handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6267. auto *FD = cast<FunctionDecl>(D);
  6268. StringRef Str;
  6269. SourceLocation ArgLoc;
  6270. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
  6271. return;
  6272. if (FD->hasBody()) {
  6273. S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
  6274. return;
  6275. }
  6276. FD->addAttr(::new (S.Context)
  6277. WebAssemblyImportModuleAttr(S.Context, AL, Str));
  6278. }
  6279. static void
  6280. handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6281. auto *FD = cast<FunctionDecl>(D);
  6282. StringRef Str;
  6283. SourceLocation ArgLoc;
  6284. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
  6285. return;
  6286. if (FD->hasBody()) {
  6287. S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
  6288. return;
  6289. }
  6290. FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str));
  6291. }
  6292. static void handleRISCVInterruptAttr(Sema &S, Decl *D,
  6293. const ParsedAttr &AL) {
  6294. // Warn about repeated attributes.
  6295. if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
  6296. S.Diag(AL.getRange().getBegin(),
  6297. diag::warn_riscv_repeated_interrupt_attribute);
  6298. S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
  6299. return;
  6300. }
  6301. // Check the attribute argument. Argument is optional.
  6302. if (!AL.checkAtMostNumArgs(S, 1))
  6303. return;
  6304. StringRef Str;
  6305. SourceLocation ArgLoc;
  6306. // 'machine'is the default interrupt mode.
  6307. if (AL.getNumArgs() == 0)
  6308. Str = "machine";
  6309. else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
  6310. return;
  6311. // Semantic checks for a function with the 'interrupt' attribute:
  6312. // - Must be a function.
  6313. // - Must have no parameters.
  6314. // - Must have the 'void' return type.
  6315. // - The attribute itself must either have no argument or one of the
  6316. // valid interrupt types, see [RISCVInterruptDocs].
  6317. if (D->getFunctionType() == nullptr) {
  6318. S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
  6319. << "'interrupt'" << ExpectedFunction;
  6320. return;
  6321. }
  6322. if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
  6323. S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
  6324. << /*RISC-V*/ 2 << 0;
  6325. return;
  6326. }
  6327. if (!getFunctionOrMethodResultType(D)->isVoidType()) {
  6328. S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
  6329. << /*RISC-V*/ 2 << 1;
  6330. return;
  6331. }
  6332. RISCVInterruptAttr::InterruptType Kind;
  6333. if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
  6334. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
  6335. << ArgLoc;
  6336. return;
  6337. }
  6338. D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind));
  6339. }
  6340. static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6341. // Dispatch the interrupt attribute based on the current target.
  6342. switch (S.Context.getTargetInfo().getTriple().getArch()) {
  6343. case llvm::Triple::msp430:
  6344. handleMSP430InterruptAttr(S, D, AL);
  6345. break;
  6346. case llvm::Triple::mipsel:
  6347. case llvm::Triple::mips:
  6348. handleMipsInterruptAttr(S, D, AL);
  6349. break;
  6350. case llvm::Triple::m68k:
  6351. handleM68kInterruptAttr(S, D, AL);
  6352. break;
  6353. case llvm::Triple::x86:
  6354. case llvm::Triple::x86_64:
  6355. handleAnyX86InterruptAttr(S, D, AL);
  6356. break;
  6357. case llvm::Triple::avr:
  6358. handleAVRInterruptAttr(S, D, AL);
  6359. break;
  6360. case llvm::Triple::riscv32:
  6361. case llvm::Triple::riscv64:
  6362. handleRISCVInterruptAttr(S, D, AL);
  6363. break;
  6364. default:
  6365. handleARMInterruptAttr(S, D, AL);
  6366. break;
  6367. }
  6368. }
  6369. static bool
  6370. checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr,
  6371. const AMDGPUFlatWorkGroupSizeAttr &Attr) {
  6372. // Accept template arguments for now as they depend on something else.
  6373. // We'll get to check them when they eventually get instantiated.
  6374. if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
  6375. return false;
  6376. uint32_t Min = 0;
  6377. if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
  6378. return true;
  6379. uint32_t Max = 0;
  6380. if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
  6381. return true;
  6382. if (Min == 0 && Max != 0) {
  6383. S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
  6384. << &Attr << 0;
  6385. return true;
  6386. }
  6387. if (Min > Max) {
  6388. S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
  6389. << &Attr << 1;
  6390. return true;
  6391. }
  6392. return false;
  6393. }
  6394. void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl *D,
  6395. const AttributeCommonInfo &CI,
  6396. Expr *MinExpr, Expr *MaxExpr) {
  6397. AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
  6398. if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr))
  6399. return;
  6400. D->addAttr(::new (Context)
  6401. AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr));
  6402. }
  6403. static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
  6404. const ParsedAttr &AL) {
  6405. Expr *MinExpr = AL.getArgAsExpr(0);
  6406. Expr *MaxExpr = AL.getArgAsExpr(1);
  6407. S.addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr);
  6408. }
  6409. static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
  6410. Expr *MaxExpr,
  6411. const AMDGPUWavesPerEUAttr &Attr) {
  6412. if (S.DiagnoseUnexpandedParameterPack(MinExpr) ||
  6413. (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr)))
  6414. return true;
  6415. // Accept template arguments for now as they depend on something else.
  6416. // We'll get to check them when they eventually get instantiated.
  6417. if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
  6418. return false;
  6419. uint32_t Min = 0;
  6420. if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
  6421. return true;
  6422. uint32_t Max = 0;
  6423. if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
  6424. return true;
  6425. if (Min == 0 && Max != 0) {
  6426. S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
  6427. << &Attr << 0;
  6428. return true;
  6429. }
  6430. if (Max != 0 && Min > Max) {
  6431. S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
  6432. << &Attr << 1;
  6433. return true;
  6434. }
  6435. return false;
  6436. }
  6437. void Sema::addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
  6438. Expr *MinExpr, Expr *MaxExpr) {
  6439. AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
  6440. if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr))
  6441. return;
  6442. D->addAttr(::new (Context)
  6443. AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr));
  6444. }
  6445. static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6446. if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
  6447. return;
  6448. Expr *MinExpr = AL.getArgAsExpr(0);
  6449. Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
  6450. S.addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr);
  6451. }
  6452. static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6453. uint32_t NumSGPR = 0;
  6454. Expr *NumSGPRExpr = AL.getArgAsExpr(0);
  6455. if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
  6456. return;
  6457. D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR));
  6458. }
  6459. static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6460. uint32_t NumVGPR = 0;
  6461. Expr *NumVGPRExpr = AL.getArgAsExpr(0);
  6462. if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
  6463. return;
  6464. D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR));
  6465. }
  6466. static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
  6467. const ParsedAttr &AL) {
  6468. // If we try to apply it to a function pointer, don't warn, but don't
  6469. // do anything, either. It doesn't matter anyway, because there's nothing
  6470. // special about calling a force_align_arg_pointer function.
  6471. const auto *VD = dyn_cast<ValueDecl>(D);
  6472. if (VD && VD->getType()->isFunctionPointerType())
  6473. return;
  6474. // Also don't warn on function pointer typedefs.
  6475. const auto *TD = dyn_cast<TypedefNameDecl>(D);
  6476. if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
  6477. TD->getUnderlyingType()->isFunctionType()))
  6478. return;
  6479. // Attribute can only be applied to function types.
  6480. if (!isa<FunctionDecl>(D)) {
  6481. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  6482. << AL << ExpectedFunction;
  6483. return;
  6484. }
  6485. D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL));
  6486. }
  6487. static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
  6488. uint32_t Version;
  6489. Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
  6490. if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
  6491. return;
  6492. // TODO: Investigate what happens with the next major version of MSVC.
  6493. if (Version != LangOptions::MSVC2015 / 100) {
  6494. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
  6495. << AL << Version << VersionExpr->getSourceRange();
  6496. return;
  6497. }
  6498. // The attribute expects a "major" version number like 19, but new versions of
  6499. // MSVC have moved to updating the "minor", or less significant numbers, so we
  6500. // have to multiply by 100 now.
  6501. Version *= 100;
  6502. D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version));
  6503. }
  6504. DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D,
  6505. const AttributeCommonInfo &CI) {
  6506. if (D->hasAttr<DLLExportAttr>()) {
  6507. Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'";
  6508. return nullptr;
  6509. }
  6510. if (D->hasAttr<DLLImportAttr>())
  6511. return nullptr;
  6512. return ::new (Context) DLLImportAttr(Context, CI);
  6513. }
  6514. DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D,
  6515. const AttributeCommonInfo &CI) {
  6516. if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
  6517. Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
  6518. D->dropAttr<DLLImportAttr>();
  6519. }
  6520. if (D->hasAttr<DLLExportAttr>())
  6521. return nullptr;
  6522. return ::new (Context) DLLExportAttr(Context, CI);
  6523. }
  6524. static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
  6525. if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
  6526. (S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
  6527. S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
  6528. return;
  6529. }
  6530. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  6531. if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
  6532. !(S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
  6533. // MinGW doesn't allow dllimport on inline functions.
  6534. S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
  6535. << A;
  6536. return;
  6537. }
  6538. }
  6539. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  6540. if ((S.Context.getTargetInfo().shouldDLLImportComdatSymbols()) &&
  6541. MD->getParent()->isLambda()) {
  6542. S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
  6543. return;
  6544. }
  6545. }
  6546. Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
  6547. ? (Attr *)S.mergeDLLExportAttr(D, A)
  6548. : (Attr *)S.mergeDLLImportAttr(D, A);
  6549. if (NewAttr)
  6550. D->addAttr(NewAttr);
  6551. }
  6552. MSInheritanceAttr *
  6553. Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI,
  6554. bool BestCase,
  6555. MSInheritanceModel Model) {
  6556. if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
  6557. if (IA->getInheritanceModel() == Model)
  6558. return nullptr;
  6559. Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
  6560. << 1 /*previous declaration*/;
  6561. Diag(CI.getLoc(), diag::note_previous_ms_inheritance);
  6562. D->dropAttr<MSInheritanceAttr>();
  6563. }
  6564. auto *RD = cast<CXXRecordDecl>(D);
  6565. if (RD->hasDefinition()) {
  6566. if (checkMSInheritanceAttrOnDefinition(RD, CI.getRange(), BestCase,
  6567. Model)) {
  6568. return nullptr;
  6569. }
  6570. } else {
  6571. if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
  6572. Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
  6573. << 1 /*partial specialization*/;
  6574. return nullptr;
  6575. }
  6576. if (RD->getDescribedClassTemplate()) {
  6577. Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
  6578. << 0 /*primary template*/;
  6579. return nullptr;
  6580. }
  6581. }
  6582. return ::new (Context) MSInheritanceAttr(Context, CI, BestCase);
  6583. }
  6584. static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6585. // The capability attributes take a single string parameter for the name of
  6586. // the capability they represent. The lockable attribute does not take any
  6587. // parameters. However, semantically, both attributes represent the same
  6588. // concept, and so they use the same semantic attribute. Eventually, the
  6589. // lockable attribute will be removed.
  6590. //
  6591. // For backward compatibility, any capability which has no specified string
  6592. // literal will be considered a "mutex."
  6593. StringRef N("mutex");
  6594. SourceLocation LiteralLoc;
  6595. if (AL.getKind() == ParsedAttr::AT_Capability &&
  6596. !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
  6597. return;
  6598. D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N));
  6599. }
  6600. static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6601. SmallVector<Expr*, 1> Args;
  6602. if (!checkLockFunAttrCommon(S, D, AL, Args))
  6603. return;
  6604. D->addAttr(::new (S.Context)
  6605. AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size()));
  6606. }
  6607. static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
  6608. const ParsedAttr &AL) {
  6609. SmallVector<Expr*, 1> Args;
  6610. if (!checkLockFunAttrCommon(S, D, AL, Args))
  6611. return;
  6612. D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(),
  6613. Args.size()));
  6614. }
  6615. static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
  6616. const ParsedAttr &AL) {
  6617. SmallVector<Expr*, 2> Args;
  6618. if (!checkTryLockFunAttrCommon(S, D, AL, Args))
  6619. return;
  6620. D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(
  6621. S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
  6622. }
  6623. static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
  6624. const ParsedAttr &AL) {
  6625. // Check that all arguments are lockable objects.
  6626. SmallVector<Expr *, 1> Args;
  6627. checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
  6628. D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(),
  6629. Args.size()));
  6630. }
  6631. static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
  6632. const ParsedAttr &AL) {
  6633. if (!AL.checkAtLeastNumArgs(S, 1))
  6634. return;
  6635. // check that all arguments are lockable objects
  6636. SmallVector<Expr*, 1> Args;
  6637. checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
  6638. if (Args.empty())
  6639. return;
  6640. RequiresCapabilityAttr *RCA = ::new (S.Context)
  6641. RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size());
  6642. D->addAttr(RCA);
  6643. }
  6644. static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6645. if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
  6646. if (NSD->isAnonymousNamespace()) {
  6647. S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
  6648. // Do not want to attach the attribute to the namespace because that will
  6649. // cause confusing diagnostic reports for uses of declarations within the
  6650. // namespace.
  6651. return;
  6652. }
  6653. } else if (isa<UsingDecl, UnresolvedUsingTypenameDecl,
  6654. UnresolvedUsingValueDecl>(D)) {
  6655. S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
  6656. << AL;
  6657. return;
  6658. }
  6659. // Handle the cases where the attribute has a text message.
  6660. StringRef Str, Replacement;
  6661. if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
  6662. !S.checkStringLiteralArgumentAttr(AL, 0, Str))
  6663. return;
  6664. // Support a single optional message only for Declspec and [[]] spellings.
  6665. if (AL.isDeclspecAttribute() || AL.isStandardAttributeSyntax())
  6666. AL.checkAtMostNumArgs(S, 1);
  6667. else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
  6668. !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
  6669. return;
  6670. if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
  6671. S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
  6672. D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement));
  6673. }
  6674. static bool isGlobalVar(const Decl *D) {
  6675. if (const auto *S = dyn_cast<VarDecl>(D))
  6676. return S->hasGlobalStorage();
  6677. return false;
  6678. }
  6679. static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6680. if (!AL.checkAtLeastNumArgs(S, 1))
  6681. return;
  6682. std::vector<StringRef> Sanitizers;
  6683. for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
  6684. StringRef SanitizerName;
  6685. SourceLocation LiteralLoc;
  6686. if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
  6687. return;
  6688. if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
  6689. SanitizerMask() &&
  6690. SanitizerName != "coverage")
  6691. S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
  6692. else if (isGlobalVar(D) && SanitizerName != "address")
  6693. S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  6694. << AL << ExpectedFunctionOrMethod;
  6695. Sanitizers.push_back(SanitizerName);
  6696. }
  6697. D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(),
  6698. Sanitizers.size()));
  6699. }
  6700. static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
  6701. const ParsedAttr &AL) {
  6702. StringRef AttrName = AL.getAttrName()->getName();
  6703. normalizeName(AttrName);
  6704. StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
  6705. .Case("no_address_safety_analysis", "address")
  6706. .Case("no_sanitize_address", "address")
  6707. .Case("no_sanitize_thread", "thread")
  6708. .Case("no_sanitize_memory", "memory");
  6709. if (isGlobalVar(D) && SanitizerName != "address")
  6710. S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  6711. << AL << ExpectedFunction;
  6712. // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
  6713. // NoSanitizeAttr object; but we need to calculate the correct spelling list
  6714. // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
  6715. // has the same spellings as the index for NoSanitizeAttr. We don't have a
  6716. // general way to "translate" between the two, so this hack attempts to work
  6717. // around the issue with hard-coded indices. This is critical for calling
  6718. // getSpelling() or prettyPrint() on the resulting semantic attribute object
  6719. // without failing assertions.
  6720. unsigned TranslatedSpellingIndex = 0;
  6721. if (AL.isStandardAttributeSyntax())
  6722. TranslatedSpellingIndex = 1;
  6723. AttributeCommonInfo Info = AL;
  6724. Info.setAttributeSpellingListIndex(TranslatedSpellingIndex);
  6725. D->addAttr(::new (S.Context)
  6726. NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
  6727. }
  6728. static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6729. if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
  6730. D->addAttr(Internal);
  6731. }
  6732. static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6733. if (S.LangOpts.getOpenCLCompatibleVersion() < 200)
  6734. S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
  6735. << AL << "2.0" << 1;
  6736. else
  6737. S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
  6738. << AL << S.LangOpts.getOpenCLVersionString();
  6739. }
  6740. static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6741. if (D->isInvalidDecl())
  6742. return;
  6743. // Check if there is only one access qualifier.
  6744. if (D->hasAttr<OpenCLAccessAttr>()) {
  6745. if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
  6746. AL.getSemanticSpelling()) {
  6747. S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
  6748. << AL.getAttrName()->getName() << AL.getRange();
  6749. } else {
  6750. S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
  6751. << D->getSourceRange();
  6752. D->setInvalidDecl(true);
  6753. return;
  6754. }
  6755. }
  6756. // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that
  6757. // an image object can be read and written. OpenCL v2.0 s6.13.6 - A kernel
  6758. // cannot read from and write to the same pipe object. Using the read_write
  6759. // (or __read_write) qualifier with the pipe qualifier is a compilation error.
  6760. // OpenCL v3.0 s6.8 - For OpenCL C 2.0, or with the
  6761. // __opencl_c_read_write_images feature, image objects specified as arguments
  6762. // to a kernel can additionally be declared to be read-write.
  6763. // C++ for OpenCL 1.0 inherits rule from OpenCL C v2.0.
  6764. // C++ for OpenCL 2021 inherits rule from OpenCL C v3.0.
  6765. if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
  6766. const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
  6767. if (AL.getAttrName()->getName().contains("read_write")) {
  6768. bool ReadWriteImagesUnsupported =
  6769. (S.getLangOpts().getOpenCLCompatibleVersion() < 200) ||
  6770. (S.getLangOpts().getOpenCLCompatibleVersion() == 300 &&
  6771. !S.getOpenCLOptions().isSupported("__opencl_c_read_write_images",
  6772. S.getLangOpts()));
  6773. if (ReadWriteImagesUnsupported || DeclTy->isPipeType()) {
  6774. S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
  6775. << AL << PDecl->getType() << DeclTy->isImageType();
  6776. D->setInvalidDecl(true);
  6777. return;
  6778. }
  6779. }
  6780. }
  6781. D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL));
  6782. }
  6783. static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6784. // The 'sycl_kernel' attribute applies only to function templates.
  6785. const auto *FD = cast<FunctionDecl>(D);
  6786. const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate();
  6787. assert(FT && "Function template is expected");
  6788. // Function template must have at least two template parameters.
  6789. const TemplateParameterList *TL = FT->getTemplateParameters();
  6790. if (TL->size() < 2) {
  6791. S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params);
  6792. return;
  6793. }
  6794. // Template parameters must be typenames.
  6795. for (unsigned I = 0; I < 2; ++I) {
  6796. const NamedDecl *TParam = TL->getParam(I);
  6797. if (isa<NonTypeTemplateParmDecl>(TParam)) {
  6798. S.Diag(FT->getLocation(),
  6799. diag::warn_sycl_kernel_invalid_template_param_type);
  6800. return;
  6801. }
  6802. }
  6803. // Function must have at least one argument.
  6804. if (getFunctionOrMethodNumParams(D) != 1) {
  6805. S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_function_params);
  6806. return;
  6807. }
  6808. // Function must return void.
  6809. QualType RetTy = getFunctionOrMethodResultType(D);
  6810. if (!RetTy->isVoidType()) {
  6811. S.Diag(FT->getLocation(), diag::warn_sycl_kernel_return_type);
  6812. return;
  6813. }
  6814. handleSimpleAttribute<SYCLKernelAttr>(S, D, AL);
  6815. }
  6816. static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
  6817. if (!cast<VarDecl>(D)->hasGlobalStorage()) {
  6818. S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
  6819. << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
  6820. return;
  6821. }
  6822. if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
  6823. handleSimpleAttribute<AlwaysDestroyAttr>(S, D, A);
  6824. else
  6825. handleSimpleAttribute<NoDestroyAttr>(S, D, A);
  6826. }
  6827. static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6828. assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
  6829. "uninitialized is only valid on automatic duration variables");
  6830. D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL));
  6831. }
  6832. static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
  6833. bool DiagnoseFailure) {
  6834. QualType Ty = VD->getType();
  6835. if (!Ty->isObjCRetainableType()) {
  6836. if (DiagnoseFailure) {
  6837. S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
  6838. << 0;
  6839. }
  6840. return false;
  6841. }
  6842. Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
  6843. // Sema::inferObjCARCLifetime must run after processing decl attributes
  6844. // (because __block lowers to an attribute), so if the lifetime hasn't been
  6845. // explicitly specified, infer it locally now.
  6846. if (LifetimeQual == Qualifiers::OCL_None)
  6847. LifetimeQual = Ty->getObjCARCImplicitLifetime();
  6848. // The attributes only really makes sense for __strong variables; ignore any
  6849. // attempts to annotate a parameter with any other lifetime qualifier.
  6850. if (LifetimeQual != Qualifiers::OCL_Strong) {
  6851. if (DiagnoseFailure) {
  6852. S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
  6853. << 1;
  6854. }
  6855. return false;
  6856. }
  6857. // Tampering with the type of a VarDecl here is a bit of a hack, but we need
  6858. // to ensure that the variable is 'const' so that we can error on
  6859. // modification, which can otherwise over-release.
  6860. VD->setType(Ty.withConst());
  6861. VD->setARCPseudoStrong(true);
  6862. return true;
  6863. }
  6864. static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
  6865. const ParsedAttr &AL) {
  6866. if (auto *VD = dyn_cast<VarDecl>(D)) {
  6867. assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
  6868. if (!VD->hasLocalStorage()) {
  6869. S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
  6870. << 0;
  6871. return;
  6872. }
  6873. if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
  6874. return;
  6875. handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
  6876. return;
  6877. }
  6878. // If D is a function-like declaration (method, block, or function), then we
  6879. // make every parameter psuedo-strong.
  6880. unsigned NumParams =
  6881. hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0;
  6882. for (unsigned I = 0; I != NumParams; ++I) {
  6883. auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
  6884. QualType Ty = PVD->getType();
  6885. // If a user wrote a parameter with __strong explicitly, then assume they
  6886. // want "real" strong semantics for that parameter. This works because if
  6887. // the parameter was written with __strong, then the strong qualifier will
  6888. // be non-local.
  6889. if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
  6890. Qualifiers::OCL_Strong)
  6891. continue;
  6892. tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
  6893. }
  6894. handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
  6895. }
  6896. static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6897. // Check that the return type is a `typedef int kern_return_t` or a typedef
  6898. // around it, because otherwise MIG convention checks make no sense.
  6899. // BlockDecl doesn't store a return type, so it's annoying to check,
  6900. // so let's skip it for now.
  6901. if (!isa<BlockDecl>(D)) {
  6902. QualType T = getFunctionOrMethodResultType(D);
  6903. bool IsKernReturnT = false;
  6904. while (const auto *TT = T->getAs<TypedefType>()) {
  6905. IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
  6906. T = TT->desugar();
  6907. }
  6908. if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
  6909. S.Diag(D->getBeginLoc(),
  6910. diag::warn_mig_server_routine_does_not_return_kern_return_t);
  6911. return;
  6912. }
  6913. }
  6914. handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL);
  6915. }
  6916. static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6917. // Warn if the return type is not a pointer or reference type.
  6918. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  6919. QualType RetTy = FD->getReturnType();
  6920. if (!RetTy->isPointerType() && !RetTy->isReferenceType()) {
  6921. S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer)
  6922. << AL.getRange() << RetTy;
  6923. return;
  6924. }
  6925. }
  6926. handleSimpleAttribute<MSAllocatorAttr>(S, D, AL);
  6927. }
  6928. static void handleAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6929. if (AL.isUsedAsTypeAttr())
  6930. return;
  6931. // Warn if the parameter is definitely not an output parameter.
  6932. if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
  6933. if (PVD->getType()->isIntegerType()) {
  6934. S.Diag(AL.getLoc(), diag::err_attribute_output_parameter)
  6935. << AL.getRange();
  6936. return;
  6937. }
  6938. }
  6939. StringRef Argument;
  6940. if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
  6941. return;
  6942. D->addAttr(AcquireHandleAttr::Create(S.Context, Argument, AL));
  6943. }
  6944. template<typename Attr>
  6945. static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6946. StringRef Argument;
  6947. if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
  6948. return;
  6949. D->addAttr(Attr::Create(S.Context, Argument, AL));
  6950. }
  6951. static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6952. // The guard attribute takes a single identifier argument.
  6953. if (!AL.isArgIdent(0)) {
  6954. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  6955. << AL << AANT_ArgumentIdentifier;
  6956. return;
  6957. }
  6958. CFGuardAttr::GuardArg Arg;
  6959. IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
  6960. if (!CFGuardAttr::ConvertStrToGuardArg(II->getName(), Arg)) {
  6961. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
  6962. return;
  6963. }
  6964. D->addAttr(::new (S.Context) CFGuardAttr(S.Context, AL, Arg));
  6965. }
  6966. template <typename AttrTy>
  6967. static const AttrTy *findEnforceTCBAttrByName(Decl *D, StringRef Name) {
  6968. auto Attrs = D->specific_attrs<AttrTy>();
  6969. auto I = llvm::find_if(Attrs,
  6970. [Name](const AttrTy *A) {
  6971. return A->getTCBName() == Name;
  6972. });
  6973. return I == Attrs.end() ? nullptr : *I;
  6974. }
  6975. template <typename AttrTy, typename ConflictingAttrTy>
  6976. static void handleEnforceTCBAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  6977. StringRef Argument;
  6978. if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
  6979. return;
  6980. // A function cannot be have both regular and leaf membership in the same TCB.
  6981. if (const ConflictingAttrTy *ConflictingAttr =
  6982. findEnforceTCBAttrByName<ConflictingAttrTy>(D, Argument)) {
  6983. // We could attach a note to the other attribute but in this case
  6984. // there's no need given how the two are very close to each other.
  6985. S.Diag(AL.getLoc(), diag::err_tcb_conflicting_attributes)
  6986. << AL.getAttrName()->getName() << ConflictingAttr->getAttrName()->getName()
  6987. << Argument;
  6988. // Error recovery: drop the non-leaf attribute so that to suppress
  6989. // all future warnings caused by erroneous attributes. The leaf attribute
  6990. // needs to be kept because it can only suppresses warnings, not cause them.
  6991. D->dropAttr<EnforceTCBAttr>();
  6992. return;
  6993. }
  6994. D->addAttr(AttrTy::Create(S.Context, Argument, AL));
  6995. }
  6996. template <typename AttrTy, typename ConflictingAttrTy>
  6997. static AttrTy *mergeEnforceTCBAttrImpl(Sema &S, Decl *D, const AttrTy &AL) {
  6998. // Check if the new redeclaration has different leaf-ness in the same TCB.
  6999. StringRef TCBName = AL.getTCBName();
  7000. if (const ConflictingAttrTy *ConflictingAttr =
  7001. findEnforceTCBAttrByName<ConflictingAttrTy>(D, TCBName)) {
  7002. S.Diag(ConflictingAttr->getLoc(), diag::err_tcb_conflicting_attributes)
  7003. << ConflictingAttr->getAttrName()->getName()
  7004. << AL.getAttrName()->getName() << TCBName;
  7005. // Add a note so that the user could easily find the conflicting attribute.
  7006. S.Diag(AL.getLoc(), diag::note_conflicting_attribute);
  7007. // More error recovery.
  7008. D->dropAttr<EnforceTCBAttr>();
  7009. return nullptr;
  7010. }
  7011. ASTContext &Context = S.getASTContext();
  7012. return ::new(Context) AttrTy(Context, AL, AL.getTCBName());
  7013. }
  7014. EnforceTCBAttr *Sema::mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL) {
  7015. return mergeEnforceTCBAttrImpl<EnforceTCBAttr, EnforceTCBLeafAttr>(
  7016. *this, D, AL);
  7017. }
  7018. EnforceTCBLeafAttr *Sema::mergeEnforceTCBLeafAttr(
  7019. Decl *D, const EnforceTCBLeafAttr &AL) {
  7020. return mergeEnforceTCBAttrImpl<EnforceTCBLeafAttr, EnforceTCBAttr>(
  7021. *this, D, AL);
  7022. }
  7023. //===----------------------------------------------------------------------===//
  7024. // Top Level Sema Entry Points
  7025. //===----------------------------------------------------------------------===//
  7026. /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
  7027. /// the attribute applies to decls. If the attribute is a type attribute, just
  7028. /// silently ignore it if a GNU attribute.
  7029. static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
  7030. const ParsedAttr &AL,
  7031. bool IncludeCXX11Attributes) {
  7032. if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
  7033. return;
  7034. // Ignore C++11 attributes on declarator chunks: they appertain to the type
  7035. // instead.
  7036. if (AL.isCXX11Attribute() && !IncludeCXX11Attributes)
  7037. return;
  7038. // Unknown attributes are automatically warned on. Target-specific attributes
  7039. // which do not apply to the current target architecture are treated as
  7040. // though they were unknown attributes.
  7041. if (AL.getKind() == ParsedAttr::UnknownAttribute ||
  7042. !AL.existsInTarget(S.Context.getTargetInfo())) {
  7043. S.Diag(AL.getLoc(),
  7044. AL.isDeclspecAttribute()
  7045. ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
  7046. : (unsigned)diag::warn_unknown_attribute_ignored)
  7047. << AL << AL.getRange();
  7048. return;
  7049. }
  7050. if (S.checkCommonAttributeFeatures(D, AL))
  7051. return;
  7052. switch (AL.getKind()) {
  7053. default:
  7054. if (AL.getInfo().handleDeclAttribute(S, D, AL) != ParsedAttrInfo::NotHandled)
  7055. break;
  7056. if (!AL.isStmtAttr()) {
  7057. // Type attributes are handled elsewhere; silently move on.
  7058. assert(AL.isTypeAttr() && "Non-type attribute not handled");
  7059. break;
  7060. }
  7061. // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
  7062. // statement attribute is not written on a declaration, but this code is
  7063. // needed for attributes in Attr.td that do not list any subjects.
  7064. S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
  7065. << AL << D->getLocation();
  7066. break;
  7067. case ParsedAttr::AT_Interrupt:
  7068. handleInterruptAttr(S, D, AL);
  7069. break;
  7070. case ParsedAttr::AT_X86ForceAlignArgPointer:
  7071. handleX86ForceAlignArgPointerAttr(S, D, AL);
  7072. break;
  7073. case ParsedAttr::AT_DLLExport:
  7074. case ParsedAttr::AT_DLLImport:
  7075. handleDLLAttr(S, D, AL);
  7076. break;
  7077. case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
  7078. handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
  7079. break;
  7080. case ParsedAttr::AT_AMDGPUWavesPerEU:
  7081. handleAMDGPUWavesPerEUAttr(S, D, AL);
  7082. break;
  7083. case ParsedAttr::AT_AMDGPUNumSGPR:
  7084. handleAMDGPUNumSGPRAttr(S, D, AL);
  7085. break;
  7086. case ParsedAttr::AT_AMDGPUNumVGPR:
  7087. handleAMDGPUNumVGPRAttr(S, D, AL);
  7088. break;
  7089. case ParsedAttr::AT_AVRSignal:
  7090. handleAVRSignalAttr(S, D, AL);
  7091. break;
  7092. case ParsedAttr::AT_BPFPreserveAccessIndex:
  7093. handleBPFPreserveAccessIndexAttr(S, D, AL);
  7094. break;
  7095. case ParsedAttr::AT_BTFDeclTag:
  7096. handleBTFDeclTagAttr(S, D, AL);
  7097. break;
  7098. case ParsedAttr::AT_WebAssemblyExportName:
  7099. handleWebAssemblyExportNameAttr(S, D, AL);
  7100. break;
  7101. case ParsedAttr::AT_WebAssemblyImportModule:
  7102. handleWebAssemblyImportModuleAttr(S, D, AL);
  7103. break;
  7104. case ParsedAttr::AT_WebAssemblyImportName:
  7105. handleWebAssemblyImportNameAttr(S, D, AL);
  7106. break;
  7107. case ParsedAttr::AT_IBOutlet:
  7108. handleIBOutlet(S, D, AL);
  7109. break;
  7110. case ParsedAttr::AT_IBOutletCollection:
  7111. handleIBOutletCollection(S, D, AL);
  7112. break;
  7113. case ParsedAttr::AT_IFunc:
  7114. handleIFuncAttr(S, D, AL);
  7115. break;
  7116. case ParsedAttr::AT_Alias:
  7117. handleAliasAttr(S, D, AL);
  7118. break;
  7119. case ParsedAttr::AT_Aligned:
  7120. handleAlignedAttr(S, D, AL);
  7121. break;
  7122. case ParsedAttr::AT_AlignValue:
  7123. handleAlignValueAttr(S, D, AL);
  7124. break;
  7125. case ParsedAttr::AT_AllocSize:
  7126. handleAllocSizeAttr(S, D, AL);
  7127. break;
  7128. case ParsedAttr::AT_AlwaysInline:
  7129. handleAlwaysInlineAttr(S, D, AL);
  7130. break;
  7131. case ParsedAttr::AT_AnalyzerNoReturn:
  7132. handleAnalyzerNoReturnAttr(S, D, AL);
  7133. break;
  7134. case ParsedAttr::AT_TLSModel:
  7135. handleTLSModelAttr(S, D, AL);
  7136. break;
  7137. case ParsedAttr::AT_Annotate:
  7138. handleAnnotateAttr(S, D, AL);
  7139. break;
  7140. case ParsedAttr::AT_Availability:
  7141. handleAvailabilityAttr(S, D, AL);
  7142. break;
  7143. case ParsedAttr::AT_CarriesDependency:
  7144. handleDependencyAttr(S, scope, D, AL);
  7145. break;
  7146. case ParsedAttr::AT_CPUDispatch:
  7147. case ParsedAttr::AT_CPUSpecific:
  7148. handleCPUSpecificAttr(S, D, AL);
  7149. break;
  7150. case ParsedAttr::AT_Common:
  7151. handleCommonAttr(S, D, AL);
  7152. break;
  7153. case ParsedAttr::AT_CUDAConstant:
  7154. handleConstantAttr(S, D, AL);
  7155. break;
  7156. case ParsedAttr::AT_PassObjectSize:
  7157. handlePassObjectSizeAttr(S, D, AL);
  7158. break;
  7159. case ParsedAttr::AT_Constructor:
  7160. handleConstructorAttr(S, D, AL);
  7161. break;
  7162. case ParsedAttr::AT_Deprecated:
  7163. handleDeprecatedAttr(S, D, AL);
  7164. break;
  7165. case ParsedAttr::AT_Destructor:
  7166. handleDestructorAttr(S, D, AL);
  7167. break;
  7168. case ParsedAttr::AT_EnableIf:
  7169. handleEnableIfAttr(S, D, AL);
  7170. break;
  7171. case ParsedAttr::AT_Error:
  7172. handleErrorAttr(S, D, AL);
  7173. break;
  7174. case ParsedAttr::AT_DiagnoseIf:
  7175. handleDiagnoseIfAttr(S, D, AL);
  7176. break;
  7177. case ParsedAttr::AT_DiagnoseAsBuiltin:
  7178. handleDiagnoseAsBuiltinAttr(S, D, AL);
  7179. break;
  7180. case ParsedAttr::AT_NoBuiltin:
  7181. handleNoBuiltinAttr(S, D, AL);
  7182. break;
  7183. case ParsedAttr::AT_ExtVectorType:
  7184. handleExtVectorTypeAttr(S, D, AL);
  7185. break;
  7186. case ParsedAttr::AT_ExternalSourceSymbol:
  7187. handleExternalSourceSymbolAttr(S, D, AL);
  7188. break;
  7189. case ParsedAttr::AT_MinSize:
  7190. handleMinSizeAttr(S, D, AL);
  7191. break;
  7192. case ParsedAttr::AT_OptimizeNone:
  7193. handleOptimizeNoneAttr(S, D, AL);
  7194. break;
  7195. case ParsedAttr::AT_EnumExtensibility:
  7196. handleEnumExtensibilityAttr(S, D, AL);
  7197. break;
  7198. case ParsedAttr::AT_SYCLKernel:
  7199. handleSYCLKernelAttr(S, D, AL);
  7200. break;
  7201. case ParsedAttr::AT_SYCLSpecialClass:
  7202. handleSimpleAttribute<SYCLSpecialClassAttr>(S, D, AL);
  7203. break;
  7204. case ParsedAttr::AT_Format:
  7205. handleFormatAttr(S, D, AL);
  7206. break;
  7207. case ParsedAttr::AT_FormatArg:
  7208. handleFormatArgAttr(S, D, AL);
  7209. break;
  7210. case ParsedAttr::AT_Callback:
  7211. handleCallbackAttr(S, D, AL);
  7212. break;
  7213. case ParsedAttr::AT_CalledOnce:
  7214. handleCalledOnceAttr(S, D, AL);
  7215. break;
  7216. case ParsedAttr::AT_CUDAGlobal:
  7217. handleGlobalAttr(S, D, AL);
  7218. break;
  7219. case ParsedAttr::AT_CUDADevice:
  7220. handleDeviceAttr(S, D, AL);
  7221. break;
  7222. case ParsedAttr::AT_HIPManaged:
  7223. handleManagedAttr(S, D, AL);
  7224. break;
  7225. case ParsedAttr::AT_GNUInline:
  7226. handleGNUInlineAttr(S, D, AL);
  7227. break;
  7228. case ParsedAttr::AT_CUDALaunchBounds:
  7229. handleLaunchBoundsAttr(S, D, AL);
  7230. break;
  7231. case ParsedAttr::AT_Restrict:
  7232. handleRestrictAttr(S, D, AL);
  7233. break;
  7234. case ParsedAttr::AT_Mode:
  7235. handleModeAttr(S, D, AL);
  7236. break;
  7237. case ParsedAttr::AT_NonNull:
  7238. if (auto *PVD = dyn_cast<ParmVarDecl>(D))
  7239. handleNonNullAttrParameter(S, PVD, AL);
  7240. else
  7241. handleNonNullAttr(S, D, AL);
  7242. break;
  7243. case ParsedAttr::AT_ReturnsNonNull:
  7244. handleReturnsNonNullAttr(S, D, AL);
  7245. break;
  7246. case ParsedAttr::AT_NoEscape:
  7247. handleNoEscapeAttr(S, D, AL);
  7248. break;
  7249. case ParsedAttr::AT_AssumeAligned:
  7250. handleAssumeAlignedAttr(S, D, AL);
  7251. break;
  7252. case ParsedAttr::AT_AllocAlign:
  7253. handleAllocAlignAttr(S, D, AL);
  7254. break;
  7255. case ParsedAttr::AT_Ownership:
  7256. handleOwnershipAttr(S, D, AL);
  7257. break;
  7258. case ParsedAttr::AT_Naked:
  7259. handleNakedAttr(S, D, AL);
  7260. break;
  7261. case ParsedAttr::AT_NoReturn:
  7262. handleNoReturnAttr(S, D, AL);
  7263. break;
  7264. case ParsedAttr::AT_AnyX86NoCfCheck:
  7265. handleNoCfCheckAttr(S, D, AL);
  7266. break;
  7267. case ParsedAttr::AT_NoThrow:
  7268. if (!AL.isUsedAsTypeAttr())
  7269. handleSimpleAttribute<NoThrowAttr>(S, D, AL);
  7270. break;
  7271. case ParsedAttr::AT_CUDAShared:
  7272. handleSharedAttr(S, D, AL);
  7273. break;
  7274. case ParsedAttr::AT_VecReturn:
  7275. handleVecReturnAttr(S, D, AL);
  7276. break;
  7277. case ParsedAttr::AT_ObjCOwnership:
  7278. handleObjCOwnershipAttr(S, D, AL);
  7279. break;
  7280. case ParsedAttr::AT_ObjCPreciseLifetime:
  7281. handleObjCPreciseLifetimeAttr(S, D, AL);
  7282. break;
  7283. case ParsedAttr::AT_ObjCReturnsInnerPointer:
  7284. handleObjCReturnsInnerPointerAttr(S, D, AL);
  7285. break;
  7286. case ParsedAttr::AT_ObjCRequiresSuper:
  7287. handleObjCRequiresSuperAttr(S, D, AL);
  7288. break;
  7289. case ParsedAttr::AT_ObjCBridge:
  7290. handleObjCBridgeAttr(S, D, AL);
  7291. break;
  7292. case ParsedAttr::AT_ObjCBridgeMutable:
  7293. handleObjCBridgeMutableAttr(S, D, AL);
  7294. break;
  7295. case ParsedAttr::AT_ObjCBridgeRelated:
  7296. handleObjCBridgeRelatedAttr(S, D, AL);
  7297. break;
  7298. case ParsedAttr::AT_ObjCDesignatedInitializer:
  7299. handleObjCDesignatedInitializer(S, D, AL);
  7300. break;
  7301. case ParsedAttr::AT_ObjCRuntimeName:
  7302. handleObjCRuntimeName(S, D, AL);
  7303. break;
  7304. case ParsedAttr::AT_ObjCBoxable:
  7305. handleObjCBoxable(S, D, AL);
  7306. break;
  7307. case ParsedAttr::AT_NSErrorDomain:
  7308. handleNSErrorDomain(S, D, AL);
  7309. break;
  7310. case ParsedAttr::AT_CFConsumed:
  7311. case ParsedAttr::AT_NSConsumed:
  7312. case ParsedAttr::AT_OSConsumed:
  7313. S.AddXConsumedAttr(D, AL, parsedAttrToRetainOwnershipKind(AL),
  7314. /*IsTemplateInstantiation=*/false);
  7315. break;
  7316. case ParsedAttr::AT_OSReturnsRetainedOnZero:
  7317. handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
  7318. S, D, AL, isValidOSObjectOutParameter(D),
  7319. diag::warn_ns_attribute_wrong_parameter_type,
  7320. /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
  7321. break;
  7322. case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
  7323. handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
  7324. S, D, AL, isValidOSObjectOutParameter(D),
  7325. diag::warn_ns_attribute_wrong_parameter_type,
  7326. /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
  7327. break;
  7328. case ParsedAttr::AT_NSReturnsAutoreleased:
  7329. case ParsedAttr::AT_NSReturnsNotRetained:
  7330. case ParsedAttr::AT_NSReturnsRetained:
  7331. case ParsedAttr::AT_CFReturnsNotRetained:
  7332. case ParsedAttr::AT_CFReturnsRetained:
  7333. case ParsedAttr::AT_OSReturnsNotRetained:
  7334. case ParsedAttr::AT_OSReturnsRetained:
  7335. handleXReturnsXRetainedAttr(S, D, AL);
  7336. break;
  7337. case ParsedAttr::AT_WorkGroupSizeHint:
  7338. handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
  7339. break;
  7340. case ParsedAttr::AT_ReqdWorkGroupSize:
  7341. handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
  7342. break;
  7343. case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
  7344. handleSubGroupSize(S, D, AL);
  7345. break;
  7346. case ParsedAttr::AT_VecTypeHint:
  7347. handleVecTypeHint(S, D, AL);
  7348. break;
  7349. case ParsedAttr::AT_InitPriority:
  7350. handleInitPriorityAttr(S, D, AL);
  7351. break;
  7352. case ParsedAttr::AT_Packed:
  7353. handlePackedAttr(S, D, AL);
  7354. break;
  7355. case ParsedAttr::AT_PreferredName:
  7356. handlePreferredName(S, D, AL);
  7357. break;
  7358. case ParsedAttr::AT_Section:
  7359. handleSectionAttr(S, D, AL);
  7360. break;
  7361. case ParsedAttr::AT_CodeSeg:
  7362. handleCodeSegAttr(S, D, AL);
  7363. break;
  7364. case ParsedAttr::AT_Target:
  7365. handleTargetAttr(S, D, AL);
  7366. break;
  7367. case ParsedAttr::AT_TargetClones:
  7368. handleTargetClonesAttr(S, D, AL);
  7369. break;
  7370. case ParsedAttr::AT_MinVectorWidth:
  7371. handleMinVectorWidthAttr(S, D, AL);
  7372. break;
  7373. case ParsedAttr::AT_Unavailable:
  7374. handleAttrWithMessage<UnavailableAttr>(S, D, AL);
  7375. break;
  7376. case ParsedAttr::AT_Assumption:
  7377. handleAssumumptionAttr(S, D, AL);
  7378. break;
  7379. case ParsedAttr::AT_ObjCDirect:
  7380. handleObjCDirectAttr(S, D, AL);
  7381. break;
  7382. case ParsedAttr::AT_ObjCDirectMembers:
  7383. handleObjCDirectMembersAttr(S, D, AL);
  7384. handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
  7385. break;
  7386. case ParsedAttr::AT_ObjCExplicitProtocolImpl:
  7387. handleObjCSuppresProtocolAttr(S, D, AL);
  7388. break;
  7389. case ParsedAttr::AT_Unused:
  7390. handleUnusedAttr(S, D, AL);
  7391. break;
  7392. case ParsedAttr::AT_Visibility:
  7393. handleVisibilityAttr(S, D, AL, false);
  7394. break;
  7395. case ParsedAttr::AT_TypeVisibility:
  7396. handleVisibilityAttr(S, D, AL, true);
  7397. break;
  7398. case ParsedAttr::AT_WarnUnusedResult:
  7399. handleWarnUnusedResult(S, D, AL);
  7400. break;
  7401. case ParsedAttr::AT_WeakRef:
  7402. handleWeakRefAttr(S, D, AL);
  7403. break;
  7404. case ParsedAttr::AT_WeakImport:
  7405. handleWeakImportAttr(S, D, AL);
  7406. break;
  7407. case ParsedAttr::AT_TransparentUnion:
  7408. handleTransparentUnionAttr(S, D, AL);
  7409. break;
  7410. case ParsedAttr::AT_ObjCMethodFamily:
  7411. handleObjCMethodFamilyAttr(S, D, AL);
  7412. break;
  7413. case ParsedAttr::AT_ObjCNSObject:
  7414. handleObjCNSObject(S, D, AL);
  7415. break;
  7416. case ParsedAttr::AT_ObjCIndependentClass:
  7417. handleObjCIndependentClass(S, D, AL);
  7418. break;
  7419. case ParsedAttr::AT_Blocks:
  7420. handleBlocksAttr(S, D, AL);
  7421. break;
  7422. case ParsedAttr::AT_Sentinel:
  7423. handleSentinelAttr(S, D, AL);
  7424. break;
  7425. case ParsedAttr::AT_Cleanup:
  7426. handleCleanupAttr(S, D, AL);
  7427. break;
  7428. case ParsedAttr::AT_NoDebug:
  7429. handleNoDebugAttr(S, D, AL);
  7430. break;
  7431. case ParsedAttr::AT_CmseNSEntry:
  7432. handleCmseNSEntryAttr(S, D, AL);
  7433. break;
  7434. case ParsedAttr::AT_StdCall:
  7435. case ParsedAttr::AT_CDecl:
  7436. case ParsedAttr::AT_FastCall:
  7437. case ParsedAttr::AT_ThisCall:
  7438. case ParsedAttr::AT_Pascal:
  7439. case ParsedAttr::AT_RegCall:
  7440. case ParsedAttr::AT_SwiftCall:
  7441. case ParsedAttr::AT_SwiftAsyncCall:
  7442. case ParsedAttr::AT_VectorCall:
  7443. case ParsedAttr::AT_MSABI:
  7444. case ParsedAttr::AT_SysVABI:
  7445. case ParsedAttr::AT_Pcs:
  7446. case ParsedAttr::AT_IntelOclBicc:
  7447. case ParsedAttr::AT_PreserveMost:
  7448. case ParsedAttr::AT_PreserveAll:
  7449. case ParsedAttr::AT_AArch64VectorPcs:
  7450. handleCallConvAttr(S, D, AL);
  7451. break;
  7452. case ParsedAttr::AT_Suppress:
  7453. handleSuppressAttr(S, D, AL);
  7454. break;
  7455. case ParsedAttr::AT_Owner:
  7456. case ParsedAttr::AT_Pointer:
  7457. handleLifetimeCategoryAttr(S, D, AL);
  7458. break;
  7459. case ParsedAttr::AT_OpenCLAccess:
  7460. handleOpenCLAccessAttr(S, D, AL);
  7461. break;
  7462. case ParsedAttr::AT_OpenCLNoSVM:
  7463. handleOpenCLNoSVMAttr(S, D, AL);
  7464. break;
  7465. case ParsedAttr::AT_SwiftContext:
  7466. S.AddParameterABIAttr(D, AL, ParameterABI::SwiftContext);
  7467. break;
  7468. case ParsedAttr::AT_SwiftAsyncContext:
  7469. S.AddParameterABIAttr(D, AL, ParameterABI::SwiftAsyncContext);
  7470. break;
  7471. case ParsedAttr::AT_SwiftErrorResult:
  7472. S.AddParameterABIAttr(D, AL, ParameterABI::SwiftErrorResult);
  7473. break;
  7474. case ParsedAttr::AT_SwiftIndirectResult:
  7475. S.AddParameterABIAttr(D, AL, ParameterABI::SwiftIndirectResult);
  7476. break;
  7477. case ParsedAttr::AT_InternalLinkage:
  7478. handleInternalLinkageAttr(S, D, AL);
  7479. break;
  7480. // Microsoft attributes:
  7481. case ParsedAttr::AT_LayoutVersion:
  7482. handleLayoutVersion(S, D, AL);
  7483. break;
  7484. case ParsedAttr::AT_Uuid:
  7485. handleUuidAttr(S, D, AL);
  7486. break;
  7487. case ParsedAttr::AT_MSInheritance:
  7488. handleMSInheritanceAttr(S, D, AL);
  7489. break;
  7490. case ParsedAttr::AT_Thread:
  7491. handleDeclspecThreadAttr(S, D, AL);
  7492. break;
  7493. case ParsedAttr::AT_AbiTag:
  7494. handleAbiTagAttr(S, D, AL);
  7495. break;
  7496. case ParsedAttr::AT_CFGuard:
  7497. handleCFGuardAttr(S, D, AL);
  7498. break;
  7499. // Thread safety attributes:
  7500. case ParsedAttr::AT_AssertExclusiveLock:
  7501. handleAssertExclusiveLockAttr(S, D, AL);
  7502. break;
  7503. case ParsedAttr::AT_AssertSharedLock:
  7504. handleAssertSharedLockAttr(S, D, AL);
  7505. break;
  7506. case ParsedAttr::AT_PtGuardedVar:
  7507. handlePtGuardedVarAttr(S, D, AL);
  7508. break;
  7509. case ParsedAttr::AT_NoSanitize:
  7510. handleNoSanitizeAttr(S, D, AL);
  7511. break;
  7512. case ParsedAttr::AT_NoSanitizeSpecific:
  7513. handleNoSanitizeSpecificAttr(S, D, AL);
  7514. break;
  7515. case ParsedAttr::AT_GuardedBy:
  7516. handleGuardedByAttr(S, D, AL);
  7517. break;
  7518. case ParsedAttr::AT_PtGuardedBy:
  7519. handlePtGuardedByAttr(S, D, AL);
  7520. break;
  7521. case ParsedAttr::AT_ExclusiveTrylockFunction:
  7522. handleExclusiveTrylockFunctionAttr(S, D, AL);
  7523. break;
  7524. case ParsedAttr::AT_LockReturned:
  7525. handleLockReturnedAttr(S, D, AL);
  7526. break;
  7527. case ParsedAttr::AT_LocksExcluded:
  7528. handleLocksExcludedAttr(S, D, AL);
  7529. break;
  7530. case ParsedAttr::AT_SharedTrylockFunction:
  7531. handleSharedTrylockFunctionAttr(S, D, AL);
  7532. break;
  7533. case ParsedAttr::AT_AcquiredBefore:
  7534. handleAcquiredBeforeAttr(S, D, AL);
  7535. break;
  7536. case ParsedAttr::AT_AcquiredAfter:
  7537. handleAcquiredAfterAttr(S, D, AL);
  7538. break;
  7539. // Capability analysis attributes.
  7540. case ParsedAttr::AT_Capability:
  7541. case ParsedAttr::AT_Lockable:
  7542. handleCapabilityAttr(S, D, AL);
  7543. break;
  7544. case ParsedAttr::AT_RequiresCapability:
  7545. handleRequiresCapabilityAttr(S, D, AL);
  7546. break;
  7547. case ParsedAttr::AT_AssertCapability:
  7548. handleAssertCapabilityAttr(S, D, AL);
  7549. break;
  7550. case ParsedAttr::AT_AcquireCapability:
  7551. handleAcquireCapabilityAttr(S, D, AL);
  7552. break;
  7553. case ParsedAttr::AT_ReleaseCapability:
  7554. handleReleaseCapabilityAttr(S, D, AL);
  7555. break;
  7556. case ParsedAttr::AT_TryAcquireCapability:
  7557. handleTryAcquireCapabilityAttr(S, D, AL);
  7558. break;
  7559. // Consumed analysis attributes.
  7560. case ParsedAttr::AT_Consumable:
  7561. handleConsumableAttr(S, D, AL);
  7562. break;
  7563. case ParsedAttr::AT_CallableWhen:
  7564. handleCallableWhenAttr(S, D, AL);
  7565. break;
  7566. case ParsedAttr::AT_ParamTypestate:
  7567. handleParamTypestateAttr(S, D, AL);
  7568. break;
  7569. case ParsedAttr::AT_ReturnTypestate:
  7570. handleReturnTypestateAttr(S, D, AL);
  7571. break;
  7572. case ParsedAttr::AT_SetTypestate:
  7573. handleSetTypestateAttr(S, D, AL);
  7574. break;
  7575. case ParsedAttr::AT_TestTypestate:
  7576. handleTestTypestateAttr(S, D, AL);
  7577. break;
  7578. // Type safety attributes.
  7579. case ParsedAttr::AT_ArgumentWithTypeTag:
  7580. handleArgumentWithTypeTagAttr(S, D, AL);
  7581. break;
  7582. case ParsedAttr::AT_TypeTagForDatatype:
  7583. handleTypeTagForDatatypeAttr(S, D, AL);
  7584. break;
  7585. // Swift attributes.
  7586. case ParsedAttr::AT_SwiftAsyncName:
  7587. handleSwiftAsyncName(S, D, AL);
  7588. break;
  7589. case ParsedAttr::AT_SwiftAttr:
  7590. handleSwiftAttrAttr(S, D, AL);
  7591. break;
  7592. case ParsedAttr::AT_SwiftBridge:
  7593. handleSwiftBridge(S, D, AL);
  7594. break;
  7595. case ParsedAttr::AT_SwiftError:
  7596. handleSwiftError(S, D, AL);
  7597. break;
  7598. case ParsedAttr::AT_SwiftName:
  7599. handleSwiftName(S, D, AL);
  7600. break;
  7601. case ParsedAttr::AT_SwiftNewType:
  7602. handleSwiftNewType(S, D, AL);
  7603. break;
  7604. case ParsedAttr::AT_SwiftAsync:
  7605. handleSwiftAsyncAttr(S, D, AL);
  7606. break;
  7607. case ParsedAttr::AT_SwiftAsyncError:
  7608. handleSwiftAsyncError(S, D, AL);
  7609. break;
  7610. // XRay attributes.
  7611. case ParsedAttr::AT_XRayLogArgs:
  7612. handleXRayLogArgsAttr(S, D, AL);
  7613. break;
  7614. case ParsedAttr::AT_PatchableFunctionEntry:
  7615. handlePatchableFunctionEntryAttr(S, D, AL);
  7616. break;
  7617. case ParsedAttr::AT_AlwaysDestroy:
  7618. case ParsedAttr::AT_NoDestroy:
  7619. handleDestroyAttr(S, D, AL);
  7620. break;
  7621. case ParsedAttr::AT_Uninitialized:
  7622. handleUninitializedAttr(S, D, AL);
  7623. break;
  7624. case ParsedAttr::AT_ObjCExternallyRetained:
  7625. handleObjCExternallyRetainedAttr(S, D, AL);
  7626. break;
  7627. case ParsedAttr::AT_MIGServerRoutine:
  7628. handleMIGServerRoutineAttr(S, D, AL);
  7629. break;
  7630. case ParsedAttr::AT_MSAllocator:
  7631. handleMSAllocatorAttr(S, D, AL);
  7632. break;
  7633. case ParsedAttr::AT_ArmBuiltinAlias:
  7634. handleArmBuiltinAliasAttr(S, D, AL);
  7635. break;
  7636. case ParsedAttr::AT_AcquireHandle:
  7637. handleAcquireHandleAttr(S, D, AL);
  7638. break;
  7639. case ParsedAttr::AT_ReleaseHandle:
  7640. handleHandleAttr<ReleaseHandleAttr>(S, D, AL);
  7641. break;
  7642. case ParsedAttr::AT_UseHandle:
  7643. handleHandleAttr<UseHandleAttr>(S, D, AL);
  7644. break;
  7645. case ParsedAttr::AT_EnforceTCB:
  7646. handleEnforceTCBAttr<EnforceTCBAttr, EnforceTCBLeafAttr>(S, D, AL);
  7647. break;
  7648. case ParsedAttr::AT_EnforceTCBLeaf:
  7649. handleEnforceTCBAttr<EnforceTCBLeafAttr, EnforceTCBAttr>(S, D, AL);
  7650. break;
  7651. case ParsedAttr::AT_BuiltinAlias:
  7652. handleBuiltinAliasAttr(S, D, AL);
  7653. break;
  7654. case ParsedAttr::AT_UsingIfExists:
  7655. handleSimpleAttribute<UsingIfExistsAttr>(S, D, AL);
  7656. break;
  7657. }
  7658. }
  7659. /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
  7660. /// attribute list to the specified decl, ignoring any type attributes.
  7661. void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
  7662. const ParsedAttributesView &AttrList,
  7663. bool IncludeCXX11Attributes) {
  7664. if (AttrList.empty())
  7665. return;
  7666. for (const ParsedAttr &AL : AttrList)
  7667. ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes);
  7668. // FIXME: We should be able to handle these cases in TableGen.
  7669. // GCC accepts
  7670. // static int a9 __attribute__((weakref));
  7671. // but that looks really pointless. We reject it.
  7672. if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
  7673. Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
  7674. << cast<NamedDecl>(D);
  7675. D->dropAttr<WeakRefAttr>();
  7676. return;
  7677. }
  7678. // FIXME: We should be able to handle this in TableGen as well. It would be
  7679. // good to have a way to specify "these attributes must appear as a group",
  7680. // for these. Additionally, it would be good to have a way to specify "these
  7681. // attribute must never appear as a group" for attributes like cold and hot.
  7682. if (!D->hasAttr<OpenCLKernelAttr>()) {
  7683. // These attributes cannot be applied to a non-kernel function.
  7684. if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
  7685. // FIXME: This emits a different error message than
  7686. // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
  7687. Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
  7688. D->setInvalidDecl();
  7689. } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
  7690. Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
  7691. D->setInvalidDecl();
  7692. } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
  7693. Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
  7694. D->setInvalidDecl();
  7695. } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
  7696. Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
  7697. D->setInvalidDecl();
  7698. } else if (!D->hasAttr<CUDAGlobalAttr>()) {
  7699. if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
  7700. Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  7701. << A << ExpectedKernelFunction;
  7702. D->setInvalidDecl();
  7703. } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
  7704. Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  7705. << A << ExpectedKernelFunction;
  7706. D->setInvalidDecl();
  7707. } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
  7708. Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  7709. << A << ExpectedKernelFunction;
  7710. D->setInvalidDecl();
  7711. } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
  7712. Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  7713. << A << ExpectedKernelFunction;
  7714. D->setInvalidDecl();
  7715. }
  7716. }
  7717. }
  7718. // Do this check after processing D's attributes because the attribute
  7719. // objc_method_family can change whether the given method is in the init
  7720. // family, and it can be applied after objc_designated_initializer. This is a
  7721. // bit of a hack, but we need it to be compatible with versions of clang that
  7722. // processed the attribute list in the wrong order.
  7723. if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
  7724. cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
  7725. Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
  7726. D->dropAttr<ObjCDesignatedInitializerAttr>();
  7727. }
  7728. }
  7729. // Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr
  7730. // attribute.
  7731. void Sema::ProcessDeclAttributeDelayed(Decl *D,
  7732. const ParsedAttributesView &AttrList) {
  7733. for (const ParsedAttr &AL : AttrList)
  7734. if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
  7735. handleTransparentUnionAttr(*this, D, AL);
  7736. break;
  7737. }
  7738. // For BPFPreserveAccessIndexAttr, we want to populate the attributes
  7739. // to fields and inner records as well.
  7740. if (D && D->hasAttr<BPFPreserveAccessIndexAttr>())
  7741. handleBPFPreserveAIRecord(*this, cast<RecordDecl>(D));
  7742. }
  7743. // Annotation attributes are the only attributes allowed after an access
  7744. // specifier.
  7745. bool Sema::ProcessAccessDeclAttributeList(
  7746. AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
  7747. for (const ParsedAttr &AL : AttrList) {
  7748. if (AL.getKind() == ParsedAttr::AT_Annotate) {
  7749. ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute());
  7750. } else {
  7751. Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
  7752. return true;
  7753. }
  7754. }
  7755. return false;
  7756. }
  7757. /// checkUnusedDeclAttributes - Check a list of attributes to see if it
  7758. /// contains any decl attributes that we should warn about.
  7759. static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
  7760. for (const ParsedAttr &AL : A) {
  7761. // Only warn if the attribute is an unignored, non-type attribute.
  7762. if (AL.isUsedAsTypeAttr() || AL.isInvalid())
  7763. continue;
  7764. if (AL.getKind() == ParsedAttr::IgnoredAttribute)
  7765. continue;
  7766. if (AL.getKind() == ParsedAttr::UnknownAttribute) {
  7767. S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
  7768. << AL << AL.getRange();
  7769. } else {
  7770. S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
  7771. << AL.getRange();
  7772. }
  7773. }
  7774. }
  7775. /// checkUnusedDeclAttributes - Given a declarator which is not being
  7776. /// used to build a declaration, complain about any decl attributes
  7777. /// which might be lying around on it.
  7778. void Sema::checkUnusedDeclAttributes(Declarator &D) {
  7779. ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
  7780. ::checkUnusedDeclAttributes(*this, D.getAttributes());
  7781. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
  7782. ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
  7783. }
  7784. /// DeclClonePragmaWeak - clone existing decl (maybe definition),
  7785. /// \#pragma weak needs a non-definition decl and source may not have one.
  7786. NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
  7787. SourceLocation Loc) {
  7788. assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
  7789. NamedDecl *NewD = nullptr;
  7790. if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
  7791. FunctionDecl *NewFD;
  7792. // FIXME: Missing call to CheckFunctionDeclaration().
  7793. // FIXME: Mangling?
  7794. // FIXME: Is the qualifier info correct?
  7795. // FIXME: Is the DeclContext correct?
  7796. NewFD = FunctionDecl::Create(
  7797. FD->getASTContext(), FD->getDeclContext(), Loc, Loc,
  7798. DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None,
  7799. getCurFPFeatures().isFPConstrained(), false /*isInlineSpecified*/,
  7800. FD->hasPrototype(), ConstexprSpecKind::Unspecified,
  7801. FD->getTrailingRequiresClause());
  7802. NewD = NewFD;
  7803. if (FD->getQualifier())
  7804. NewFD->setQualifierInfo(FD->getQualifierLoc());
  7805. // Fake up parameter variables; they are declared as if this were
  7806. // a typedef.
  7807. QualType FDTy = FD->getType();
  7808. if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
  7809. SmallVector<ParmVarDecl*, 16> Params;
  7810. for (const auto &AI : FT->param_types()) {
  7811. ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
  7812. Param->setScopeInfo(0, Params.size());
  7813. Params.push_back(Param);
  7814. }
  7815. NewFD->setParams(Params);
  7816. }
  7817. } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
  7818. NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
  7819. VD->getInnerLocStart(), VD->getLocation(), II,
  7820. VD->getType(), VD->getTypeSourceInfo(),
  7821. VD->getStorageClass());
  7822. if (VD->getQualifier())
  7823. cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
  7824. }
  7825. return NewD;
  7826. }
  7827. /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
  7828. /// applied to it, possibly with an alias.
  7829. void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
  7830. if (W.getUsed()) return; // only do this once
  7831. W.setUsed(true);
  7832. if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
  7833. IdentifierInfo *NDId = ND->getIdentifier();
  7834. NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
  7835. NewD->addAttr(
  7836. AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation()));
  7837. NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
  7838. AttributeCommonInfo::AS_Pragma));
  7839. WeakTopLevelDecl.push_back(NewD);
  7840. // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
  7841. // to insert Decl at TU scope, sorry.
  7842. DeclContext *SavedContext = CurContext;
  7843. CurContext = Context.getTranslationUnitDecl();
  7844. NewD->setDeclContext(CurContext);
  7845. NewD->setLexicalDeclContext(CurContext);
  7846. PushOnScopeChains(NewD, S);
  7847. CurContext = SavedContext;
  7848. } else { // just add weak to existing
  7849. ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
  7850. AttributeCommonInfo::AS_Pragma));
  7851. }
  7852. }
  7853. void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
  7854. // It's valid to "forward-declare" #pragma weak, in which case we
  7855. // have to do this.
  7856. LoadExternalWeakUndeclaredIdentifiers();
  7857. if (!WeakUndeclaredIdentifiers.empty()) {
  7858. NamedDecl *ND = nullptr;
  7859. if (auto *VD = dyn_cast<VarDecl>(D))
  7860. if (VD->isExternC())
  7861. ND = VD;
  7862. if (auto *FD = dyn_cast<FunctionDecl>(D))
  7863. if (FD->isExternC())
  7864. ND = FD;
  7865. if (ND) {
  7866. if (IdentifierInfo *Id = ND->getIdentifier()) {
  7867. auto I = WeakUndeclaredIdentifiers.find(Id);
  7868. if (I != WeakUndeclaredIdentifiers.end()) {
  7869. WeakInfo W = I->second;
  7870. DeclApplyPragmaWeak(S, ND, W);
  7871. WeakUndeclaredIdentifiers[Id] = W;
  7872. }
  7873. }
  7874. }
  7875. }
  7876. }
  7877. /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
  7878. /// it, apply them to D. This is a bit tricky because PD can have attributes
  7879. /// specified in many different places, and we need to find and apply them all.
  7880. void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
  7881. // Apply decl attributes from the DeclSpec if present.
  7882. if (!PD.getDeclSpec().getAttributes().empty())
  7883. ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes());
  7884. // Walk the declarator structure, applying decl attributes that were in a type
  7885. // position to the decl itself. This handles cases like:
  7886. // int *__attr__(x)** D;
  7887. // when X is a decl attribute.
  7888. for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
  7889. ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
  7890. /*IncludeCXX11Attributes=*/false);
  7891. // Finally, apply any attributes on the decl itself.
  7892. ProcessDeclAttributeList(S, D, PD.getAttributes());
  7893. // Apply additional attributes specified by '#pragma clang attribute'.
  7894. AddPragmaAttributes(S, D);
  7895. }
  7896. /// Is the given declaration allowed to use a forbidden type?
  7897. /// If so, it'll still be annotated with an attribute that makes it
  7898. /// illegal to actually use.
  7899. static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
  7900. const DelayedDiagnostic &diag,
  7901. UnavailableAttr::ImplicitReason &reason) {
  7902. // Private ivars are always okay. Unfortunately, people don't
  7903. // always properly make their ivars private, even in system headers.
  7904. // Plus we need to make fields okay, too.
  7905. if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
  7906. !isa<FunctionDecl>(D))
  7907. return false;
  7908. // Silently accept unsupported uses of __weak in both user and system
  7909. // declarations when it's been disabled, for ease of integration with
  7910. // -fno-objc-arc files. We do have to take some care against attempts
  7911. // to define such things; for now, we've only done that for ivars
  7912. // and properties.
  7913. if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
  7914. if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
  7915. diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
  7916. reason = UnavailableAttr::IR_ForbiddenWeak;
  7917. return true;
  7918. }
  7919. }
  7920. // Allow all sorts of things in system headers.
  7921. if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) {
  7922. // Currently, all the failures dealt with this way are due to ARC
  7923. // restrictions.
  7924. reason = UnavailableAttr::IR_ARCForbiddenType;
  7925. return true;
  7926. }
  7927. return false;
  7928. }
  7929. /// Handle a delayed forbidden-type diagnostic.
  7930. static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
  7931. Decl *D) {
  7932. auto Reason = UnavailableAttr::IR_None;
  7933. if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
  7934. assert(Reason && "didn't set reason?");
  7935. D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
  7936. return;
  7937. }
  7938. if (S.getLangOpts().ObjCAutoRefCount)
  7939. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  7940. // FIXME: we may want to suppress diagnostics for all
  7941. // kind of forbidden type messages on unavailable functions.
  7942. if (FD->hasAttr<UnavailableAttr>() &&
  7943. DD.getForbiddenTypeDiagnostic() ==
  7944. diag::err_arc_array_param_no_ownership) {
  7945. DD.Triggered = true;
  7946. return;
  7947. }
  7948. }
  7949. S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
  7950. << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
  7951. DD.Triggered = true;
  7952. }
  7953. void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
  7954. assert(DelayedDiagnostics.getCurrentPool());
  7955. DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
  7956. DelayedDiagnostics.popWithoutEmitting(state);
  7957. // When delaying diagnostics to run in the context of a parsed
  7958. // declaration, we only want to actually emit anything if parsing
  7959. // succeeds.
  7960. if (!decl) return;
  7961. // We emit all the active diagnostics in this pool or any of its
  7962. // parents. In general, we'll get one pool for the decl spec
  7963. // and a child pool for each declarator; in a decl group like:
  7964. // deprecated_typedef foo, *bar, baz();
  7965. // only the declarator pops will be passed decls. This is correct;
  7966. // we really do need to consider delayed diagnostics from the decl spec
  7967. // for each of the different declarations.
  7968. const DelayedDiagnosticPool *pool = &poppedPool;
  7969. do {
  7970. bool AnyAccessFailures = false;
  7971. for (DelayedDiagnosticPool::pool_iterator
  7972. i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
  7973. // This const_cast is a bit lame. Really, Triggered should be mutable.
  7974. DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
  7975. if (diag.Triggered)
  7976. continue;
  7977. switch (diag.Kind) {
  7978. case DelayedDiagnostic::Availability:
  7979. // Don't bother giving deprecation/unavailable diagnostics if
  7980. // the decl is invalid.
  7981. if (!decl->isInvalidDecl())
  7982. handleDelayedAvailabilityCheck(diag, decl);
  7983. break;
  7984. case DelayedDiagnostic::Access:
  7985. // Only produce one access control diagnostic for a structured binding
  7986. // declaration: we don't need to tell the user that all the fields are
  7987. // inaccessible one at a time.
  7988. if (AnyAccessFailures && isa<DecompositionDecl>(decl))
  7989. continue;
  7990. HandleDelayedAccessCheck(diag, decl);
  7991. if (diag.Triggered)
  7992. AnyAccessFailures = true;
  7993. break;
  7994. case DelayedDiagnostic::ForbiddenType:
  7995. handleDelayedForbiddenType(*this, diag, decl);
  7996. break;
  7997. }
  7998. }
  7999. } while ((pool = pool->getParent()));
  8000. }
  8001. /// Given a set of delayed diagnostics, re-emit them as if they had
  8002. /// been delayed in the current context instead of in the given pool.
  8003. /// Essentially, this just moves them to the current pool.
  8004. void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
  8005. DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
  8006. assert(curPool && "re-emitting in undelayed context not supported");
  8007. curPool->steal(pool);
  8008. }