SemaDeclAttr.cpp 302 KB

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