SemaDeclAttr.cpp 194 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540
  1. //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements decl-related attribute processing.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "clang/AST/ASTContext.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/ASTMutationListener.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/Lookup.h"
  30. #include "clang/Sema/Scope.h"
  31. #include "llvm/ADT/StringExtras.h"
  32. #include "llvm/Support/MathExtras.h"
  33. #include "clang/Sema/SemaHLSL.h" // HLSL Change
  34. using namespace clang;
  35. using namespace sema;
  36. namespace AttributeLangSupport {
  37. enum LANG {
  38. C,
  39. Cpp,
  40. ObjC
  41. };
  42. }
  43. //===----------------------------------------------------------------------===//
  44. // Helper functions
  45. //===----------------------------------------------------------------------===//
  46. /// isFunctionOrMethod - Return true if the given decl has function
  47. /// type (function or function-typed variable) or an Objective-C
  48. /// method.
  49. static bool isFunctionOrMethod(const Decl *D) {
  50. return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
  51. }
  52. /// \brief Return true if the given decl has function type (function or
  53. /// function-typed variable) or an Objective-C method or a block.
  54. static bool isFunctionOrMethodOrBlock(const Decl *D) {
  55. return isFunctionOrMethod(D) || isa<BlockDecl>(D);
  56. }
  57. /// Return true if the given decl has a declarator that should have
  58. /// been processed by Sema::GetTypeForDeclarator.
  59. static bool hasDeclarator(const Decl *D) {
  60. // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
  61. return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
  62. isa<ObjCPropertyDecl>(D);
  63. }
  64. /// hasFunctionProto - Return true if the given decl has a argument
  65. /// information. This decl should have already passed
  66. /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
  67. static bool hasFunctionProto(const Decl *D) {
  68. if (const FunctionType *FnTy = D->getFunctionType())
  69. return isa<FunctionProtoType>(FnTy);
  70. return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
  71. }
  72. /// getFunctionOrMethodNumParams - Return number of function or method
  73. /// parameters. It is an error to call this on a K&R function (use
  74. /// hasFunctionProto first).
  75. static unsigned getFunctionOrMethodNumParams(const Decl *D) {
  76. if (const FunctionType *FnTy = D->getFunctionType())
  77. return cast<FunctionProtoType>(FnTy)->getNumParams();
  78. if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
  79. return BD->getNumParams();
  80. return cast<ObjCMethodDecl>(D)->param_size();
  81. }
  82. static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
  83. if (const FunctionType *FnTy = D->getFunctionType())
  84. return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
  85. if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
  86. return BD->getParamDecl(Idx)->getType();
  87. return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
  88. }
  89. static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
  90. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  91. return FD->getParamDecl(Idx)->getSourceRange();
  92. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  93. return MD->parameters()[Idx]->getSourceRange();
  94. if (const auto *BD = dyn_cast<BlockDecl>(D))
  95. return BD->getParamDecl(Idx)->getSourceRange();
  96. return SourceRange();
  97. }
  98. static QualType getFunctionOrMethodResultType(const Decl *D) {
  99. if (const FunctionType *FnTy = D->getFunctionType())
  100. return cast<FunctionType>(FnTy)->getReturnType();
  101. return cast<ObjCMethodDecl>(D)->getReturnType();
  102. }
  103. static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
  104. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  105. return FD->getReturnTypeSourceRange();
  106. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  107. return MD->getReturnTypeSourceRange();
  108. return SourceRange();
  109. }
  110. static bool isFunctionOrMethodVariadic(const Decl *D) {
  111. if (const FunctionType *FnTy = D->getFunctionType()) {
  112. const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
  113. return proto->isVariadic();
  114. }
  115. if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
  116. return BD->isVariadic();
  117. return cast<ObjCMethodDecl>(D)->isVariadic();
  118. }
  119. static bool isInstanceMethod(const Decl *D) {
  120. if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
  121. return MethodDecl->isInstance();
  122. return false;
  123. }
  124. static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
  125. const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
  126. if (!PT)
  127. return false;
  128. ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
  129. if (!Cls)
  130. return false;
  131. IdentifierInfo* ClsName = Cls->getIdentifier();
  132. // FIXME: Should we walk the chain of classes?
  133. return ClsName == &Ctx.Idents.get("NSString") ||
  134. ClsName == &Ctx.Idents.get("NSMutableString");
  135. }
  136. static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
  137. const PointerType *PT = T->getAs<PointerType>();
  138. if (!PT)
  139. return false;
  140. const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
  141. if (!RT)
  142. return false;
  143. const RecordDecl *RD = RT->getDecl();
  144. if (RD->getTagKind() != TTK_Struct)
  145. return false;
  146. return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
  147. }
  148. static unsigned getNumAttributeArgs(const AttributeList &Attr) {
  149. // FIXME: Include the type in the argument list.
  150. return Attr.getNumArgs() + Attr.hasParsedType();
  151. }
  152. template <typename Compare>
  153. static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
  154. unsigned Num, unsigned Diag,
  155. Compare Comp) {
  156. if (Comp(getNumAttributeArgs(Attr), Num)) {
  157. S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
  158. return false;
  159. }
  160. return true;
  161. }
  162. /// \brief Check if the attribute has exactly as many args as Num. May
  163. /// output an error.
  164. static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
  165. unsigned Num) {
  166. return checkAttributeNumArgsImpl(S, Attr, Num,
  167. diag::err_attribute_wrong_number_arguments,
  168. std::not_equal_to<unsigned>());
  169. }
  170. /// \brief Check if the attribute has at least as many args as Num. May
  171. /// output an error.
  172. static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
  173. unsigned Num) {
  174. return checkAttributeNumArgsImpl(S, Attr, Num,
  175. diag::err_attribute_too_few_arguments,
  176. std::less<unsigned>());
  177. }
  178. /// \brief Check if the attribute has at most as many args as Num. May
  179. /// output an error.
  180. static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
  181. unsigned Num) {
  182. return checkAttributeNumArgsImpl(S, Attr, Num,
  183. diag::err_attribute_too_many_arguments,
  184. std::greater<unsigned>());
  185. }
  186. /// \brief If Expr is a valid integer constant, get the value of the integer
  187. /// expression and return success or failure. May output an error.
  188. static bool checkUInt32Argument(Sema &S, const AttributeList &Attr,
  189. const Expr *Expr, uint32_t &Val,
  190. unsigned Idx = UINT_MAX) {
  191. llvm::APSInt I(32);
  192. if (Expr->isTypeDependent() || Expr->isValueDependent() ||
  193. !Expr->isIntegerConstantExpr(I, S.Context)) {
  194. if (Idx != UINT_MAX)
  195. S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
  196. << Attr.getName() << Idx << AANT_ArgumentIntegerConstant
  197. << Expr->getSourceRange();
  198. else
  199. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  200. << Attr.getName() << AANT_ArgumentIntegerConstant
  201. << Expr->getSourceRange();
  202. return false;
  203. }
  204. if (!I.isIntN(32)) {
  205. S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
  206. << I.toString(10, false) << 32 << /* Unsigned */ 1;
  207. return false;
  208. }
  209. Val = (uint32_t)I.getZExtValue();
  210. return true;
  211. }
  212. /// \brief Diagnose mutually exclusive attributes when present on a given
  213. /// declaration. Returns true if diagnosed.
  214. template <typename AttrTy>
  215. static bool checkAttrMutualExclusion(Sema &S, Decl *D,
  216. const AttributeList &Attr) {
  217. if (AttrTy *A = D->getAttr<AttrTy>()) {
  218. S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
  219. << Attr.getName() << A;
  220. return true;
  221. }
  222. return false;
  223. }
  224. /// \brief Check if IdxExpr is a valid parameter index for a function or
  225. /// instance method D. May output an error.
  226. ///
  227. /// \returns true if IdxExpr is a valid index.
  228. static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
  229. const AttributeList &Attr,
  230. unsigned AttrArgNum,
  231. const Expr *IdxExpr,
  232. uint64_t &Idx) {
  233. assert(isFunctionOrMethodOrBlock(D));
  234. // In C++ the implicit 'this' function parameter also counts.
  235. // Parameters are counted from one.
  236. bool HP = hasFunctionProto(D);
  237. bool HasImplicitThisParam = isInstanceMethod(D);
  238. bool IV = HP && isFunctionOrMethodVariadic(D);
  239. unsigned NumParams =
  240. (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
  241. llvm::APSInt IdxInt;
  242. if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
  243. !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
  244. S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
  245. << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
  246. << IdxExpr->getSourceRange();
  247. return false;
  248. }
  249. Idx = IdxInt.getLimitedValue();
  250. if (Idx < 1 || (!IV && Idx > NumParams)) {
  251. S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
  252. << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
  253. return false;
  254. }
  255. Idx--; // Convert to zero-based.
  256. if (HasImplicitThisParam) {
  257. if (Idx == 0) {
  258. S.Diag(Attr.getLoc(),
  259. diag::err_attribute_invalid_implicit_this_argument)
  260. << Attr.getName() << IdxExpr->getSourceRange();
  261. return false;
  262. }
  263. --Idx;
  264. }
  265. return true;
  266. }
  267. /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
  268. /// If not emit an error and return false. If the argument is an identifier it
  269. /// will emit an error with a fixit hint and treat it as if it was a string
  270. /// literal.
  271. bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
  272. unsigned ArgNum, StringRef &Str,
  273. SourceLocation *ArgLocation) {
  274. // Look for identifiers. If we have one emit a hint to fix it to a literal.
  275. if (Attr.isArgIdent(ArgNum)) {
  276. IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
  277. Diag(Loc->Loc, diag::err_attribute_argument_type)
  278. << Attr.getName() << AANT_ArgumentString
  279. << FixItHint::CreateInsertion(Loc->Loc, "\"")
  280. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(Loc->Loc), "\"");
  281. Str = Loc->Ident->getName();
  282. if (ArgLocation)
  283. *ArgLocation = Loc->Loc;
  284. return true;
  285. }
  286. // Now check for an actual string literal.
  287. Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
  288. StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
  289. if (ArgLocation)
  290. *ArgLocation = ArgExpr->getLocStart();
  291. if (!Literal || !Literal->isAscii()) {
  292. Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
  293. << Attr.getName() << AANT_ArgumentString;
  294. return false;
  295. }
  296. Str = Literal->getString();
  297. return true;
  298. }
  299. /// \brief Applies the given attribute to the Decl without performing any
  300. /// additional semantic checking.
  301. template <typename AttrType>
  302. static void handleSimpleAttribute(Sema &S, Decl *D,
  303. const AttributeList &Attr) {
  304. D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
  305. Attr.getAttributeSpellingListIndex()));
  306. }
  307. /// \brief Check if the passed-in expression is of type int or bool.
  308. static bool isIntOrBool(Expr *Exp) {
  309. QualType QT = Exp->getType();
  310. return QT->isBooleanType() || QT->isIntegerType();
  311. }
  312. // Check to see if the type is a smart pointer of some kind. We assume
  313. // it's a smart pointer if it defines both operator-> and operator*.
  314. static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
  315. DeclContextLookupResult Res1 = RT->getDecl()->lookup(
  316. S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
  317. if (Res1.empty())
  318. return false;
  319. DeclContextLookupResult Res2 = RT->getDecl()->lookup(
  320. S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
  321. if (Res2.empty())
  322. return false;
  323. return true;
  324. }
  325. /// \brief Check if passed in Decl is a pointer type.
  326. /// Note that this function may produce an error message.
  327. /// \return true if the Decl is a pointer type; false otherwise
  328. static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
  329. const AttributeList &Attr) {
  330. const ValueDecl *vd = cast<ValueDecl>(D);
  331. QualType QT = vd->getType();
  332. if (QT->isAnyPointerType())
  333. return true;
  334. if (const RecordType *RT = QT->getAs<RecordType>()) {
  335. // If it's an incomplete type, it could be a smart pointer; skip it.
  336. // (We don't want to force template instantiation if we can avoid it,
  337. // since that would alter the order in which templates are instantiated.)
  338. if (RT->isIncompleteType())
  339. return true;
  340. if (threadSafetyCheckIsSmartPointer(S, RT))
  341. return true;
  342. }
  343. S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
  344. << Attr.getName() << QT;
  345. return false;
  346. }
  347. /// \brief Checks that the passed in QualType either is of RecordType or points
  348. /// to RecordType. Returns the relevant RecordType, null if it does not exit.
  349. static const RecordType *getRecordType(QualType QT) {
  350. if (const RecordType *RT = QT->getAs<RecordType>())
  351. return RT;
  352. // Now check if we point to record type.
  353. if (const PointerType *PT = QT->getAs<PointerType>())
  354. return PT->getPointeeType()->getAs<RecordType>();
  355. return nullptr;
  356. }
  357. static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
  358. const RecordType *RT = getRecordType(Ty);
  359. if (!RT)
  360. return false;
  361. // Don't check for the capability if the class hasn't been defined yet.
  362. if (RT->isIncompleteType())
  363. return true;
  364. // Allow smart pointers to be used as capability objects.
  365. // FIXME -- Check the type that the smart pointer points to.
  366. if (threadSafetyCheckIsSmartPointer(S, RT))
  367. return true;
  368. // Check if the record itself has a capability.
  369. RecordDecl *RD = RT->getDecl();
  370. if (RD->hasAttr<CapabilityAttr>())
  371. return true;
  372. // Else check if any base classes have a capability.
  373. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  374. CXXBasePaths BPaths(false, false);
  375. if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &P,
  376. void *) {
  377. return BS->getType()->getAs<RecordType>()
  378. ->getDecl()->hasAttr<CapabilityAttr>();
  379. }, nullptr, BPaths))
  380. return true;
  381. }
  382. return false;
  383. }
  384. static bool checkTypedefTypeForCapability(QualType Ty) {
  385. const auto *TD = Ty->getAs<TypedefType>();
  386. if (!TD)
  387. return false;
  388. TypedefNameDecl *TN = TD->getDecl();
  389. if (!TN)
  390. return false;
  391. return TN->hasAttr<CapabilityAttr>();
  392. }
  393. static bool typeHasCapability(Sema &S, QualType Ty) {
  394. if (checkTypedefTypeForCapability(Ty))
  395. return true;
  396. if (checkRecordTypeForCapability(S, Ty))
  397. return true;
  398. return false;
  399. }
  400. static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
  401. // Capability expressions are simple expressions involving the boolean logic
  402. // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
  403. // a DeclRefExpr is found, its type should be checked to determine whether it
  404. // is a capability or not.
  405. if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
  406. return typeHasCapability(S, E->getType());
  407. else if (const auto *E = dyn_cast<CastExpr>(Ex))
  408. return isCapabilityExpr(S, E->getSubExpr());
  409. else if (const auto *E = dyn_cast<ParenExpr>(Ex))
  410. return isCapabilityExpr(S, E->getSubExpr());
  411. else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
  412. if (E->getOpcode() == UO_LNot)
  413. return isCapabilityExpr(S, E->getSubExpr());
  414. return false;
  415. } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
  416. if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
  417. return isCapabilityExpr(S, E->getLHS()) &&
  418. isCapabilityExpr(S, E->getRHS());
  419. return false;
  420. }
  421. return false;
  422. }
  423. /// \brief Checks that all attribute arguments, starting from Sidx, resolve to
  424. /// a capability object.
  425. /// \param Sidx The attribute argument index to start checking with.
  426. /// \param ParamIdxOk Whether an argument can be indexing into a function
  427. /// parameter list.
  428. static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
  429. const AttributeList &Attr,
  430. SmallVectorImpl<Expr *> &Args,
  431. int Sidx = 0,
  432. bool ParamIdxOk = false) {
  433. for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
  434. Expr *ArgExp = Attr.getArgAsExpr(Idx);
  435. if (ArgExp->isTypeDependent()) {
  436. // FIXME -- need to check this again on template instantiation
  437. Args.push_back(ArgExp);
  438. continue;
  439. }
  440. if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
  441. if (StrLit->getLength() == 0 ||
  442. (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
  443. // Pass empty strings to the analyzer without warnings.
  444. // Treat "*" as the universal lock.
  445. Args.push_back(ArgExp);
  446. continue;
  447. }
  448. // We allow constant strings to be used as a placeholder for expressions
  449. // that are not valid C++ syntax, but warn that they are ignored.
  450. S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
  451. Attr.getName();
  452. Args.push_back(ArgExp);
  453. continue;
  454. }
  455. QualType ArgTy = ArgExp->getType();
  456. // A pointer to member expression of the form &MyClass::mu is treated
  457. // specially -- we need to look at the type of the member.
  458. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
  459. if (UOp->getOpcode() == UO_AddrOf)
  460. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
  461. if (DRE->getDecl()->isCXXInstanceMember())
  462. ArgTy = DRE->getDecl()->getType();
  463. // First see if we can just cast to record type, or pointer to record type.
  464. const RecordType *RT = getRecordType(ArgTy);
  465. // Now check if we index into a record type function param.
  466. if(!RT && ParamIdxOk) {
  467. FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  468. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
  469. if(FD && IL) {
  470. unsigned int NumParams = FD->getNumParams();
  471. llvm::APInt ArgValue = IL->getValue();
  472. uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
  473. uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
  474. if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
  475. S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
  476. << Attr.getName() << Idx + 1 << NumParams;
  477. continue;
  478. }
  479. ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
  480. }
  481. }
  482. // If the type does not have a capability, see if the components of the
  483. // expression have capabilities. This allows for writing C code where the
  484. // capability may be on the type, and the expression is a capability
  485. // boolean logic expression. Eg) requires_capability(A || B && !C)
  486. if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
  487. S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
  488. << Attr.getName() << ArgTy;
  489. Args.push_back(ArgExp);
  490. }
  491. }
  492. //===----------------------------------------------------------------------===//
  493. // Attribute Implementations
  494. //===----------------------------------------------------------------------===//
  495. static void handlePtGuardedVarAttr(Sema &S, Decl *D,
  496. const AttributeList &Attr) {
  497. if (!threadSafetyCheckIsPointer(S, D, Attr))
  498. return;
  499. D->addAttr(::new (S.Context)
  500. PtGuardedVarAttr(Attr.getRange(), S.Context,
  501. Attr.getAttributeSpellingListIndex()));
  502. }
  503. static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
  504. const AttributeList &Attr,
  505. Expr* &Arg) {
  506. SmallVector<Expr*, 1> Args;
  507. // check that all arguments are lockable objects
  508. checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
  509. unsigned Size = Args.size();
  510. if (Size != 1)
  511. return false;
  512. Arg = Args[0];
  513. return true;
  514. }
  515. static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  516. Expr *Arg = nullptr;
  517. if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
  518. return;
  519. D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
  520. Attr.getAttributeSpellingListIndex()));
  521. }
  522. static void handlePtGuardedByAttr(Sema &S, Decl *D,
  523. const AttributeList &Attr) {
  524. Expr *Arg = nullptr;
  525. if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
  526. return;
  527. if (!threadSafetyCheckIsPointer(S, D, Attr))
  528. return;
  529. D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
  530. S.Context, Arg,
  531. Attr.getAttributeSpellingListIndex()));
  532. }
  533. static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
  534. const AttributeList &Attr,
  535. SmallVectorImpl<Expr *> &Args) {
  536. if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
  537. return false;
  538. // Check that this attribute only applies to lockable types.
  539. QualType QT = cast<ValueDecl>(D)->getType();
  540. if (!QT->isDependentType()) {
  541. const RecordType *RT = getRecordType(QT);
  542. if (!RT || !RT->getDecl()->hasAttr<CapabilityAttr>()) {
  543. S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
  544. << Attr.getName();
  545. return false;
  546. }
  547. }
  548. // Check that all arguments are lockable objects.
  549. checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
  550. if (Args.empty())
  551. return false;
  552. return true;
  553. }
  554. static void handleAcquiredAfterAttr(Sema &S, Decl *D,
  555. const AttributeList &Attr) {
  556. SmallVector<Expr*, 1> Args;
  557. if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
  558. return;
  559. Expr **StartArg = &Args[0];
  560. D->addAttr(::new (S.Context)
  561. AcquiredAfterAttr(Attr.getRange(), S.Context,
  562. StartArg, Args.size(),
  563. Attr.getAttributeSpellingListIndex()));
  564. }
  565. static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
  566. const AttributeList &Attr) {
  567. SmallVector<Expr*, 1> Args;
  568. if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
  569. return;
  570. Expr **StartArg = &Args[0];
  571. D->addAttr(::new (S.Context)
  572. AcquiredBeforeAttr(Attr.getRange(), S.Context,
  573. StartArg, Args.size(),
  574. Attr.getAttributeSpellingListIndex()));
  575. }
  576. static bool checkLockFunAttrCommon(Sema &S, Decl *D,
  577. const AttributeList &Attr,
  578. SmallVectorImpl<Expr *> &Args) {
  579. // zero or more arguments ok
  580. // check that all arguments are lockable objects
  581. checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
  582. return true;
  583. }
  584. static void handleAssertSharedLockAttr(Sema &S, Decl *D,
  585. const AttributeList &Attr) {
  586. SmallVector<Expr*, 1> Args;
  587. if (!checkLockFunAttrCommon(S, D, Attr, Args))
  588. return;
  589. unsigned Size = Args.size();
  590. Expr **StartArg = Size == 0 ? nullptr : &Args[0];
  591. D->addAttr(::new (S.Context)
  592. AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
  593. Attr.getAttributeSpellingListIndex()));
  594. }
  595. static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
  596. const AttributeList &Attr) {
  597. SmallVector<Expr*, 1> Args;
  598. if (!checkLockFunAttrCommon(S, D, Attr, Args))
  599. return;
  600. unsigned Size = Args.size();
  601. Expr **StartArg = Size == 0 ? nullptr : &Args[0];
  602. D->addAttr(::new (S.Context)
  603. AssertExclusiveLockAttr(Attr.getRange(), S.Context,
  604. StartArg, Size,
  605. Attr.getAttributeSpellingListIndex()));
  606. }
  607. static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
  608. const AttributeList &Attr,
  609. SmallVectorImpl<Expr *> &Args) {
  610. if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
  611. return false;
  612. if (!isIntOrBool(Attr.getArgAsExpr(0))) {
  613. S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
  614. << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
  615. return false;
  616. }
  617. // check that all arguments are lockable objects
  618. checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
  619. return true;
  620. }
  621. static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
  622. const AttributeList &Attr) {
  623. SmallVector<Expr*, 2> Args;
  624. if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
  625. return;
  626. D->addAttr(::new (S.Context)
  627. SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
  628. Attr.getArgAsExpr(0),
  629. Args.data(), Args.size(),
  630. Attr.getAttributeSpellingListIndex()));
  631. }
  632. static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
  633. const AttributeList &Attr) {
  634. SmallVector<Expr*, 2> Args;
  635. if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
  636. return;
  637. D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
  638. Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
  639. Args.size(), Attr.getAttributeSpellingListIndex()));
  640. }
  641. static void handleLockReturnedAttr(Sema &S, Decl *D,
  642. const AttributeList &Attr) {
  643. // check that the argument is lockable object
  644. SmallVector<Expr*, 1> Args;
  645. checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
  646. unsigned Size = Args.size();
  647. if (Size == 0)
  648. return;
  649. D->addAttr(::new (S.Context)
  650. LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
  651. Attr.getAttributeSpellingListIndex()));
  652. }
  653. static void handleLocksExcludedAttr(Sema &S, Decl *D,
  654. const AttributeList &Attr) {
  655. if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
  656. return;
  657. // check that all arguments are lockable objects
  658. SmallVector<Expr*, 1> Args;
  659. checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
  660. unsigned Size = Args.size();
  661. if (Size == 0)
  662. return;
  663. Expr **StartArg = &Args[0];
  664. D->addAttr(::new (S.Context)
  665. LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
  666. Attr.getAttributeSpellingListIndex()));
  667. }
  668. static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  669. Expr *Cond = Attr.getArgAsExpr(0);
  670. if (!Cond->isTypeDependent()) {
  671. ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
  672. if (Converted.isInvalid())
  673. return;
  674. Cond = Converted.get();
  675. }
  676. StringRef Msg;
  677. if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
  678. return;
  679. SmallVector<PartialDiagnosticAt, 8> Diags;
  680. if (!Cond->isValueDependent() &&
  681. !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
  682. Diags)) {
  683. S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr);
  684. for (int I = 0, N = Diags.size(); I != N; ++I)
  685. S.Diag(Diags[I].first, Diags[I].second);
  686. return;
  687. }
  688. D->addAttr(::new (S.Context)
  689. EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
  690. Attr.getAttributeSpellingListIndex()));
  691. }
  692. static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  693. ConsumableAttr::ConsumedState DefaultState;
  694. if (Attr.isArgIdent(0)) {
  695. IdentifierLoc *IL = Attr.getArgAsIdent(0);
  696. if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
  697. DefaultState)) {
  698. S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
  699. << Attr.getName() << IL->Ident;
  700. return;
  701. }
  702. } else {
  703. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  704. << Attr.getName() << AANT_ArgumentIdentifier;
  705. return;
  706. }
  707. D->addAttr(::new (S.Context)
  708. ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
  709. Attr.getAttributeSpellingListIndex()));
  710. }
  711. static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
  712. const AttributeList &Attr) {
  713. ASTContext &CurrContext = S.getASTContext();
  714. QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
  715. if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
  716. if (!RD->hasAttr<ConsumableAttr>()) {
  717. S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
  718. RD->getNameAsString();
  719. return false;
  720. }
  721. }
  722. return true;
  723. }
  724. static void handleCallableWhenAttr(Sema &S, Decl *D,
  725. const AttributeList &Attr) {
  726. if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
  727. return;
  728. if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
  729. return;
  730. SmallVector<CallableWhenAttr::ConsumedState, 3> States;
  731. for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
  732. CallableWhenAttr::ConsumedState CallableState;
  733. StringRef StateString;
  734. SourceLocation Loc;
  735. if (Attr.isArgIdent(ArgIndex)) {
  736. IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
  737. StateString = Ident->Ident->getName();
  738. Loc = Ident->Loc;
  739. } else {
  740. if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
  741. return;
  742. }
  743. if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
  744. CallableState)) {
  745. S.Diag(Loc, diag::warn_attribute_type_not_supported)
  746. << Attr.getName() << StateString;
  747. return;
  748. }
  749. States.push_back(CallableState);
  750. }
  751. D->addAttr(::new (S.Context)
  752. CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
  753. States.size(), Attr.getAttributeSpellingListIndex()));
  754. }
  755. static void handleParamTypestateAttr(Sema &S, Decl *D,
  756. const AttributeList &Attr) {
  757. ParamTypestateAttr::ConsumedState ParamState;
  758. if (Attr.isArgIdent(0)) {
  759. IdentifierLoc *Ident = Attr.getArgAsIdent(0);
  760. StringRef StateString = Ident->Ident->getName();
  761. if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
  762. ParamState)) {
  763. S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
  764. << Attr.getName() << StateString;
  765. return;
  766. }
  767. } else {
  768. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
  769. Attr.getName() << AANT_ArgumentIdentifier;
  770. return;
  771. }
  772. // FIXME: This check is currently being done in the analysis. It can be
  773. // enabled here only after the parser propagates attributes at
  774. // template specialization definition, not declaration.
  775. //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
  776. //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
  777. //
  778. //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
  779. // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
  780. // ReturnType.getAsString();
  781. // return;
  782. //}
  783. D->addAttr(::new (S.Context)
  784. ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
  785. Attr.getAttributeSpellingListIndex()));
  786. }
  787. static void handleReturnTypestateAttr(Sema &S, Decl *D,
  788. const AttributeList &Attr) {
  789. ReturnTypestateAttr::ConsumedState ReturnState;
  790. if (Attr.isArgIdent(0)) {
  791. IdentifierLoc *IL = Attr.getArgAsIdent(0);
  792. if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
  793. ReturnState)) {
  794. S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
  795. << Attr.getName() << IL->Ident;
  796. return;
  797. }
  798. } else {
  799. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
  800. Attr.getName() << AANT_ArgumentIdentifier;
  801. return;
  802. }
  803. // FIXME: This check is currently being done in the analysis. It can be
  804. // enabled here only after the parser propagates attributes at
  805. // template specialization definition, not declaration.
  806. //QualType ReturnType;
  807. //
  808. //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
  809. // ReturnType = Param->getType();
  810. //
  811. //} else if (const CXXConstructorDecl *Constructor =
  812. // dyn_cast<CXXConstructorDecl>(D)) {
  813. // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
  814. //
  815. //} else {
  816. //
  817. // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
  818. //}
  819. //
  820. //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
  821. //
  822. //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
  823. // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
  824. // ReturnType.getAsString();
  825. // return;
  826. //}
  827. D->addAttr(::new (S.Context)
  828. ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
  829. Attr.getAttributeSpellingListIndex()));
  830. }
  831. static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  832. if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
  833. return;
  834. SetTypestateAttr::ConsumedState NewState;
  835. if (Attr.isArgIdent(0)) {
  836. IdentifierLoc *Ident = Attr.getArgAsIdent(0);
  837. StringRef Param = Ident->Ident->getName();
  838. if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
  839. S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
  840. << Attr.getName() << Param;
  841. return;
  842. }
  843. } else {
  844. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
  845. Attr.getName() << AANT_ArgumentIdentifier;
  846. return;
  847. }
  848. D->addAttr(::new (S.Context)
  849. SetTypestateAttr(Attr.getRange(), S.Context, NewState,
  850. Attr.getAttributeSpellingListIndex()));
  851. }
  852. static void handleTestTypestateAttr(Sema &S, Decl *D,
  853. const AttributeList &Attr) {
  854. if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
  855. return;
  856. TestTypestateAttr::ConsumedState TestState;
  857. if (Attr.isArgIdent(0)) {
  858. IdentifierLoc *Ident = Attr.getArgAsIdent(0);
  859. StringRef Param = Ident->Ident->getName();
  860. if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
  861. S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
  862. << Attr.getName() << Param;
  863. return;
  864. }
  865. } else {
  866. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
  867. Attr.getName() << AANT_ArgumentIdentifier;
  868. return;
  869. }
  870. D->addAttr(::new (S.Context)
  871. TestTypestateAttr(Attr.getRange(), S.Context, TestState,
  872. Attr.getAttributeSpellingListIndex()));
  873. }
  874. static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
  875. const AttributeList &Attr) {
  876. // Remember this typedef decl, we will need it later for diagnostics.
  877. S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
  878. }
  879. static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  880. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  881. TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
  882. Attr.getAttributeSpellingListIndex()));
  883. else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  884. // If the alignment is less than or equal to 8 bits, the packed attribute
  885. // has no effect.
  886. if (!FD->getType()->isDependentType() &&
  887. !FD->getType()->isIncompleteType() &&
  888. S.Context.getTypeAlign(FD->getType()) <= 8)
  889. S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
  890. << Attr.getName() << FD->getType();
  891. else
  892. FD->addAttr(::new (S.Context)
  893. PackedAttr(Attr.getRange(), S.Context,
  894. Attr.getAttributeSpellingListIndex()));
  895. } else
  896. S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
  897. }
  898. static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
  899. // The IBOutlet/IBOutletCollection attributes only apply to instance
  900. // variables or properties of Objective-C classes. The outlet must also
  901. // have an object reference type.
  902. if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
  903. if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
  904. S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
  905. << Attr.getName() << VD->getType() << 0;
  906. return false;
  907. }
  908. }
  909. else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
  910. if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
  911. S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
  912. << Attr.getName() << PD->getType() << 1;
  913. return false;
  914. }
  915. }
  916. else {
  917. S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
  918. return false;
  919. }
  920. return true;
  921. }
  922. static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
  923. if (!checkIBOutletCommon(S, D, Attr))
  924. return;
  925. D->addAttr(::new (S.Context)
  926. IBOutletAttr(Attr.getRange(), S.Context,
  927. Attr.getAttributeSpellingListIndex()));
  928. }
  929. static void handleIBOutletCollection(Sema &S, Decl *D,
  930. const AttributeList &Attr) {
  931. // The iboutletcollection attribute can have zero or one arguments.
  932. if (Attr.getNumArgs() > 1) {
  933. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
  934. << Attr.getName() << 1;
  935. return;
  936. }
  937. if (!checkIBOutletCommon(S, D, Attr))
  938. return;
  939. ParsedType PT;
  940. if (Attr.hasParsedType())
  941. PT = Attr.getTypeArg();
  942. else {
  943. PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
  944. S.getScopeForContext(D->getDeclContext()->getParent()));
  945. if (!PT) {
  946. S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
  947. return;
  948. }
  949. }
  950. TypeSourceInfo *QTLoc = nullptr;
  951. QualType QT = S.GetTypeFromParser(PT, &QTLoc);
  952. if (!QTLoc)
  953. QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
  954. // Diagnose use of non-object type in iboutletcollection attribute.
  955. // FIXME. Gnu attribute extension ignores use of builtin types in
  956. // attributes. So, __attribute__((iboutletcollection(char))) will be
  957. // treated as __attribute__((iboutletcollection())).
  958. if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
  959. S.Diag(Attr.getLoc(),
  960. QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
  961. : diag::err_iboutletcollection_type) << QT;
  962. return;
  963. }
  964. D->addAttr(::new (S.Context)
  965. IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
  966. Attr.getAttributeSpellingListIndex()));
  967. }
  968. bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
  969. if (RefOkay) {
  970. if (T->isReferenceType())
  971. return true;
  972. } else {
  973. T = T.getNonReferenceType();
  974. }
  975. // The nonnull attribute, and other similar attributes, can be applied to a
  976. // transparent union that contains a pointer type.
  977. if (const RecordType *UT = T->getAsUnionType()) {
  978. if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
  979. RecordDecl *UD = UT->getDecl();
  980. for (const auto *I : UD->fields()) {
  981. QualType QT = I->getType();
  982. if (QT->isAnyPointerType() || QT->isBlockPointerType())
  983. return true;
  984. }
  985. }
  986. }
  987. return T->isAnyPointerType() || T->isBlockPointerType();
  988. }
  989. static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
  990. SourceRange AttrParmRange,
  991. SourceRange TypeRange,
  992. bool isReturnValue = false) {
  993. if (!S.isValidPointerAttrType(T)) {
  994. S.Diag(Attr.getLoc(), isReturnValue
  995. ? diag::warn_attribute_return_pointers_only
  996. : diag::warn_attribute_pointers_only)
  997. << Attr.getName() << AttrParmRange << TypeRange;
  998. return false;
  999. }
  1000. return true;
  1001. }
  1002. static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1003. SmallVector<unsigned, 8> NonNullArgs;
  1004. for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
  1005. Expr *Ex = Attr.getArgAsExpr(I);
  1006. uint64_t Idx;
  1007. if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
  1008. return;
  1009. // Is the function argument a pointer type?
  1010. if (Idx < getFunctionOrMethodNumParams(D) &&
  1011. !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
  1012. Ex->getSourceRange(),
  1013. getFunctionOrMethodParamRange(D, Idx)))
  1014. continue;
  1015. NonNullArgs.push_back(Idx);
  1016. }
  1017. // If no arguments were specified to __attribute__((nonnull)) then all pointer
  1018. // arguments have a nonnull attribute; warn if there aren't any. Skip this
  1019. // check if the attribute came from a macro expansion or a template
  1020. // instantiation.
  1021. if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
  1022. S.ActiveTemplateInstantiations.empty()) {
  1023. bool AnyPointers = isFunctionOrMethodVariadic(D);
  1024. for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
  1025. I != E && !AnyPointers; ++I) {
  1026. QualType T = getFunctionOrMethodParamType(D, I);
  1027. if (T->isDependentType() || S.isValidPointerAttrType(T))
  1028. AnyPointers = true;
  1029. }
  1030. if (!AnyPointers)
  1031. S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
  1032. }
  1033. unsigned *Start = NonNullArgs.data();
  1034. unsigned Size = NonNullArgs.size();
  1035. llvm::array_pod_sort(Start, Start + Size);
  1036. D->addAttr(::new (S.Context)
  1037. NonNullAttr(Attr.getRange(), S.Context, Start, Size,
  1038. Attr.getAttributeSpellingListIndex()));
  1039. }
  1040. static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
  1041. const AttributeList &Attr) {
  1042. if (Attr.getNumArgs() > 0) {
  1043. if (D->getFunctionType()) {
  1044. handleNonNullAttr(S, D, Attr);
  1045. } else {
  1046. S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
  1047. << D->getSourceRange();
  1048. }
  1049. return;
  1050. }
  1051. // Is the argument a pointer type?
  1052. if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
  1053. D->getSourceRange()))
  1054. return;
  1055. D->addAttr(::new (S.Context)
  1056. NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
  1057. Attr.getAttributeSpellingListIndex()));
  1058. }
  1059. static void handleReturnsNonNullAttr(Sema &S, Decl *D,
  1060. const AttributeList &Attr) {
  1061. QualType ResultType = getFunctionOrMethodResultType(D);
  1062. SourceRange SR = getFunctionOrMethodResultSourceRange(D);
  1063. if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
  1064. /* isReturnValue */ true))
  1065. return;
  1066. D->addAttr(::new (S.Context)
  1067. ReturnsNonNullAttr(Attr.getRange(), S.Context,
  1068. Attr.getAttributeSpellingListIndex()));
  1069. }
  1070. static void handleAssumeAlignedAttr(Sema &S, Decl *D,
  1071. const AttributeList &Attr) {
  1072. Expr *E = Attr.getArgAsExpr(0),
  1073. *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
  1074. S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
  1075. Attr.getAttributeSpellingListIndex());
  1076. }
  1077. void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
  1078. Expr *OE, unsigned SpellingListIndex) {
  1079. QualType ResultType = getFunctionOrMethodResultType(D);
  1080. SourceRange SR = getFunctionOrMethodResultSourceRange(D);
  1081. AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
  1082. SourceLocation AttrLoc = AttrRange.getBegin();
  1083. if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
  1084. Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
  1085. << &TmpAttr << AttrRange << SR;
  1086. return;
  1087. }
  1088. if (!E->isValueDependent()) {
  1089. llvm::APSInt I(64);
  1090. if (!E->isIntegerConstantExpr(I, Context)) {
  1091. if (OE)
  1092. Diag(AttrLoc, diag::err_attribute_argument_n_type)
  1093. << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
  1094. << E->getSourceRange();
  1095. else
  1096. Diag(AttrLoc, diag::err_attribute_argument_type)
  1097. << &TmpAttr << AANT_ArgumentIntegerConstant
  1098. << E->getSourceRange();
  1099. return;
  1100. }
  1101. if (!I.isPowerOf2()) {
  1102. Diag(AttrLoc, diag::err_alignment_not_power_of_two)
  1103. << E->getSourceRange();
  1104. return;
  1105. }
  1106. }
  1107. if (OE) {
  1108. if (!OE->isValueDependent()) {
  1109. llvm::APSInt I(64);
  1110. if (!OE->isIntegerConstantExpr(I, Context)) {
  1111. Diag(AttrLoc, diag::err_attribute_argument_n_type)
  1112. << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
  1113. << OE->getSourceRange();
  1114. return;
  1115. }
  1116. }
  1117. }
  1118. D->addAttr(::new (Context)
  1119. AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
  1120. }
  1121. static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
  1122. // This attribute must be applied to a function declaration. The first
  1123. // argument to the attribute must be an identifier, the name of the resource,
  1124. // for example: malloc. The following arguments must be argument indexes, the
  1125. // arguments must be of integer type for Returns, otherwise of pointer type.
  1126. // The difference between Holds and Takes is that a pointer may still be used
  1127. // after being held. free() should be __attribute((ownership_takes)), whereas
  1128. // a list append function may well be __attribute((ownership_holds)).
  1129. if (!AL.isArgIdent(0)) {
  1130. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  1131. << AL.getName() << 1 << AANT_ArgumentIdentifier;
  1132. return;
  1133. }
  1134. // Figure out our Kind.
  1135. OwnershipAttr::OwnershipKind K =
  1136. OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
  1137. AL.getAttributeSpellingListIndex()).getOwnKind();
  1138. // Check arguments.
  1139. switch (K) {
  1140. case OwnershipAttr::Takes:
  1141. case OwnershipAttr::Holds:
  1142. if (AL.getNumArgs() < 2) {
  1143. S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
  1144. << AL.getName() << 2;
  1145. return;
  1146. }
  1147. break;
  1148. case OwnershipAttr::Returns:
  1149. if (AL.getNumArgs() > 2) {
  1150. S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
  1151. << AL.getName() << 1;
  1152. return;
  1153. }
  1154. break;
  1155. }
  1156. IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
  1157. // Normalize the argument, __foo__ becomes foo.
  1158. StringRef ModuleName = Module->getName();
  1159. if (ModuleName.startswith("__") && ModuleName.endswith("__") &&
  1160. ModuleName.size() > 4) {
  1161. ModuleName = ModuleName.drop_front(2).drop_back(2);
  1162. Module = &S.PP.getIdentifierTable().get(ModuleName);
  1163. }
  1164. SmallVector<unsigned, 8> OwnershipArgs;
  1165. for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
  1166. Expr *Ex = AL.getArgAsExpr(i);
  1167. uint64_t Idx;
  1168. if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
  1169. return;
  1170. // Is the function argument a pointer type?
  1171. QualType T = getFunctionOrMethodParamType(D, Idx);
  1172. int Err = -1; // No error
  1173. switch (K) {
  1174. case OwnershipAttr::Takes:
  1175. case OwnershipAttr::Holds:
  1176. if (!T->isAnyPointerType() && !T->isBlockPointerType())
  1177. Err = 0;
  1178. break;
  1179. case OwnershipAttr::Returns:
  1180. if (!T->isIntegerType())
  1181. Err = 1;
  1182. break;
  1183. }
  1184. if (-1 != Err) {
  1185. S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
  1186. << Ex->getSourceRange();
  1187. return;
  1188. }
  1189. // Check we don't have a conflict with another ownership attribute.
  1190. for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
  1191. // Cannot have two ownership attributes of different kinds for the same
  1192. // index.
  1193. if (I->getOwnKind() != K && I->args_end() !=
  1194. std::find(I->args_begin(), I->args_end(), Idx)) {
  1195. S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
  1196. << AL.getName() << I;
  1197. return;
  1198. } else if (K == OwnershipAttr::Returns &&
  1199. I->getOwnKind() == OwnershipAttr::Returns) {
  1200. // A returns attribute conflicts with any other returns attribute using
  1201. // a different index. Note, diagnostic reporting is 1-based, but stored
  1202. // argument indexes are 0-based.
  1203. if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
  1204. S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
  1205. << *(I->args_begin()) + 1;
  1206. if (I->args_size())
  1207. S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
  1208. << (unsigned)Idx + 1 << Ex->getSourceRange();
  1209. return;
  1210. }
  1211. }
  1212. }
  1213. OwnershipArgs.push_back(Idx);
  1214. }
  1215. unsigned* start = OwnershipArgs.data();
  1216. unsigned size = OwnershipArgs.size();
  1217. llvm::array_pod_sort(start, start + size);
  1218. D->addAttr(::new (S.Context)
  1219. OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
  1220. AL.getAttributeSpellingListIndex()));
  1221. }
  1222. static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1223. // Check the attribute arguments.
  1224. if (Attr.getNumArgs() > 1) {
  1225. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
  1226. << Attr.getName() << 1;
  1227. return;
  1228. }
  1229. NamedDecl *nd = cast<NamedDecl>(D);
  1230. // gcc rejects
  1231. // class c {
  1232. // static int a __attribute__((weakref ("v2")));
  1233. // static int b() __attribute__((weakref ("f3")));
  1234. // };
  1235. // and ignores the attributes of
  1236. // void f(void) {
  1237. // static int a __attribute__((weakref ("v2")));
  1238. // }
  1239. // we reject them
  1240. const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
  1241. if (!Ctx->isFileContext()) {
  1242. S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
  1243. << nd;
  1244. return;
  1245. }
  1246. // The GCC manual says
  1247. //
  1248. // At present, a declaration to which `weakref' is attached can only
  1249. // be `static'.
  1250. //
  1251. // It also says
  1252. //
  1253. // Without a TARGET,
  1254. // given as an argument to `weakref' or to `alias', `weakref' is
  1255. // equivalent to `weak'.
  1256. //
  1257. // gcc 4.4.1 will accept
  1258. // int a7 __attribute__((weakref));
  1259. // as
  1260. // int a7 __attribute__((weak));
  1261. // This looks like a bug in gcc. We reject that for now. We should revisit
  1262. // it if this behaviour is actually used.
  1263. // GCC rejects
  1264. // static ((alias ("y"), weakref)).
  1265. // Should we? How to check that weakref is before or after alias?
  1266. // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
  1267. // of transforming it into an AliasAttr. The WeakRefAttr never uses the
  1268. // StringRef parameter it was given anyway.
  1269. StringRef Str;
  1270. if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
  1271. // GCC will accept anything as the argument of weakref. Should we
  1272. // check for an existing decl?
  1273. D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
  1274. Attr.getAttributeSpellingListIndex()));
  1275. D->addAttr(::new (S.Context)
  1276. WeakRefAttr(Attr.getRange(), S.Context,
  1277. Attr.getAttributeSpellingListIndex()));
  1278. }
  1279. static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1280. StringRef Str;
  1281. if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
  1282. return;
  1283. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  1284. S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
  1285. return;
  1286. }
  1287. // Aliases should be on declarations, not definitions.
  1288. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  1289. if (FD->isThisDeclarationADefinition()) {
  1290. S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD;
  1291. return;
  1292. }
  1293. } else {
  1294. const auto *VD = cast<VarDecl>(D);
  1295. if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
  1296. S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD;
  1297. return;
  1298. }
  1299. }
  1300. // FIXME: check if target symbol exists in current file
  1301. D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
  1302. Attr.getAttributeSpellingListIndex()));
  1303. }
  1304. static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1305. if (checkAttrMutualExclusion<HotAttr>(S, D, Attr))
  1306. return;
  1307. D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
  1308. Attr.getAttributeSpellingListIndex()));
  1309. }
  1310. static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1311. if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr))
  1312. return;
  1313. D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
  1314. Attr.getAttributeSpellingListIndex()));
  1315. }
  1316. static void handleTLSModelAttr(Sema &S, Decl *D,
  1317. const AttributeList &Attr) {
  1318. StringRef Model;
  1319. SourceLocation LiteralLoc;
  1320. // Check that it is a string.
  1321. if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
  1322. return;
  1323. // Check that the value.
  1324. if (Model != "global-dynamic" && Model != "local-dynamic"
  1325. && Model != "initial-exec" && Model != "local-exec") {
  1326. S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
  1327. return;
  1328. }
  1329. D->addAttr(::new (S.Context)
  1330. TLSModelAttr(Attr.getRange(), S.Context, Model,
  1331. Attr.getAttributeSpellingListIndex()));
  1332. }
  1333. static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1334. QualType ResultType = getFunctionOrMethodResultType(D);
  1335. if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
  1336. D->addAttr(::new (S.Context) RestrictAttr(
  1337. Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
  1338. return;
  1339. }
  1340. S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
  1341. << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
  1342. }
  1343. static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1344. if (S.LangOpts.CPlusPlus) {
  1345. S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
  1346. << Attr.getName() << AttributeLangSupport::Cpp;
  1347. return;
  1348. }
  1349. D->addAttr(::new (S.Context) CommonAttr(Attr.getRange(), S.Context,
  1350. Attr.getAttributeSpellingListIndex()));
  1351. }
  1352. static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
  1353. if (hasDeclarator(D)) return;
  1354. if (S.CheckNoReturnAttr(attr)) return;
  1355. if (!isa<ObjCMethodDecl>(D)) {
  1356. S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
  1357. << attr.getName() << ExpectedFunctionOrMethod;
  1358. return;
  1359. }
  1360. D->addAttr(::new (S.Context)
  1361. NoReturnAttr(attr.getRange(), S.Context,
  1362. attr.getAttributeSpellingListIndex()));
  1363. }
  1364. bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
  1365. if (!checkAttributeNumArgs(*this, attr, 0)) {
  1366. attr.setInvalid();
  1367. return true;
  1368. }
  1369. return false;
  1370. }
  1371. static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
  1372. const AttributeList &Attr) {
  1373. // The checking path for 'noreturn' and 'analyzer_noreturn' are different
  1374. // because 'analyzer_noreturn' does not impact the type.
  1375. if (!isFunctionOrMethodOrBlock(D)) {
  1376. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  1377. if (!VD || (!VD->getType()->isBlockPointerType() &&
  1378. !VD->getType()->isFunctionPointerType())) {
  1379. S.Diag(Attr.getLoc(),
  1380. Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
  1381. : diag::warn_attribute_wrong_decl_type)
  1382. << Attr.getName() << ExpectedFunctionMethodOrBlock;
  1383. return;
  1384. }
  1385. }
  1386. D->addAttr(::new (S.Context)
  1387. AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
  1388. Attr.getAttributeSpellingListIndex()));
  1389. }
  1390. // PS3 PPU-specific.
  1391. static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1392. /*
  1393. Returning a Vector Class in Registers
  1394. According to the PPU ABI specifications, a class with a single member of
  1395. vector type is returned in memory when used as the return value of a function.
  1396. This results in inefficient code when implementing vector classes. To return
  1397. the value in a single vector register, add the vecreturn attribute to the
  1398. class definition. This attribute is also applicable to struct types.
  1399. Example:
  1400. struct Vector
  1401. {
  1402. __vector float xyzw;
  1403. } __attribute__((vecreturn));
  1404. Vector Add(Vector lhs, Vector rhs)
  1405. {
  1406. Vector result;
  1407. result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
  1408. return result; // This will be returned in a register
  1409. }
  1410. */
  1411. if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
  1412. S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
  1413. return;
  1414. }
  1415. RecordDecl *record = cast<RecordDecl>(D);
  1416. int count = 0;
  1417. if (!isa<CXXRecordDecl>(record)) {
  1418. S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
  1419. return;
  1420. }
  1421. if (!cast<CXXRecordDecl>(record)->isPOD()) {
  1422. S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
  1423. return;
  1424. }
  1425. for (const auto *I : record->fields()) {
  1426. if ((count == 1) || !I->getType()->isVectorType()) {
  1427. S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
  1428. return;
  1429. }
  1430. count++;
  1431. }
  1432. D->addAttr(::new (S.Context)
  1433. VecReturnAttr(Attr.getRange(), S.Context,
  1434. Attr.getAttributeSpellingListIndex()));
  1435. }
  1436. static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
  1437. const AttributeList &Attr) {
  1438. if (isa<ParmVarDecl>(D)) {
  1439. // [[carries_dependency]] can only be applied to a parameter if it is a
  1440. // parameter of a function declaration or lambda.
  1441. if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
  1442. S.Diag(Attr.getLoc(),
  1443. diag::err_carries_dependency_param_not_function_decl);
  1444. return;
  1445. }
  1446. }
  1447. D->addAttr(::new (S.Context) CarriesDependencyAttr(
  1448. Attr.getRange(), S.Context,
  1449. Attr.getAttributeSpellingListIndex()));
  1450. }
  1451. static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1452. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1453. if (VD->hasLocalStorage()) {
  1454. S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
  1455. return;
  1456. }
  1457. } else if (!isFunctionOrMethod(D)) {
  1458. S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
  1459. << Attr.getName() << ExpectedVariableOrFunction;
  1460. return;
  1461. }
  1462. D->addAttr(::new (S.Context)
  1463. UsedAttr(Attr.getRange(), S.Context,
  1464. Attr.getAttributeSpellingListIndex()));
  1465. }
  1466. static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1467. uint32_t priority = ConstructorAttr::DefaultPriority;
  1468. if (Attr.getNumArgs() &&
  1469. !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
  1470. return;
  1471. D->addAttr(::new (S.Context)
  1472. ConstructorAttr(Attr.getRange(), S.Context, priority,
  1473. Attr.getAttributeSpellingListIndex()));
  1474. }
  1475. static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1476. uint32_t priority = DestructorAttr::DefaultPriority;
  1477. if (Attr.getNumArgs() &&
  1478. !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
  1479. return;
  1480. D->addAttr(::new (S.Context)
  1481. DestructorAttr(Attr.getRange(), S.Context, priority,
  1482. Attr.getAttributeSpellingListIndex()));
  1483. }
  1484. template <typename AttrTy>
  1485. static void handleAttrWithMessage(Sema &S, Decl *D,
  1486. const AttributeList &Attr) {
  1487. // Handle the case where the attribute has a text message.
  1488. StringRef Str;
  1489. if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
  1490. return;
  1491. D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
  1492. Attr.getAttributeSpellingListIndex()));
  1493. }
  1494. static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
  1495. const AttributeList &Attr) {
  1496. if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
  1497. S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
  1498. << Attr.getName() << Attr.getRange();
  1499. return;
  1500. }
  1501. D->addAttr(::new (S.Context)
  1502. ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
  1503. Attr.getAttributeSpellingListIndex()));
  1504. }
  1505. static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
  1506. IdentifierInfo *Platform,
  1507. VersionTuple Introduced,
  1508. VersionTuple Deprecated,
  1509. VersionTuple Obsoleted) {
  1510. StringRef PlatformName
  1511. = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
  1512. if (PlatformName.empty())
  1513. PlatformName = Platform->getName();
  1514. // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
  1515. // of these steps are needed).
  1516. if (!Introduced.empty() && !Deprecated.empty() &&
  1517. !(Introduced <= Deprecated)) {
  1518. S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
  1519. << 1 << PlatformName << Deprecated.getAsString()
  1520. << 0 << Introduced.getAsString();
  1521. return true;
  1522. }
  1523. if (!Introduced.empty() && !Obsoleted.empty() &&
  1524. !(Introduced <= Obsoleted)) {
  1525. S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
  1526. << 2 << PlatformName << Obsoleted.getAsString()
  1527. << 0 << Introduced.getAsString();
  1528. return true;
  1529. }
  1530. if (!Deprecated.empty() && !Obsoleted.empty() &&
  1531. !(Deprecated <= Obsoleted)) {
  1532. S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
  1533. << 2 << PlatformName << Obsoleted.getAsString()
  1534. << 1 << Deprecated.getAsString();
  1535. return true;
  1536. }
  1537. return false;
  1538. }
  1539. /// \brief Check whether the two versions match.
  1540. ///
  1541. /// If either version tuple is empty, then they are assumed to match. If
  1542. /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
  1543. static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
  1544. bool BeforeIsOkay) {
  1545. if (X.empty() || Y.empty())
  1546. return true;
  1547. if (X == Y)
  1548. return true;
  1549. if (BeforeIsOkay && X < Y)
  1550. return true;
  1551. return false;
  1552. }
  1553. AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
  1554. IdentifierInfo *Platform,
  1555. VersionTuple Introduced,
  1556. VersionTuple Deprecated,
  1557. VersionTuple Obsoleted,
  1558. bool IsUnavailable,
  1559. StringRef Message,
  1560. bool Override,
  1561. unsigned AttrSpellingListIndex) {
  1562. VersionTuple MergedIntroduced = Introduced;
  1563. VersionTuple MergedDeprecated = Deprecated;
  1564. VersionTuple MergedObsoleted = Obsoleted;
  1565. bool FoundAny = false;
  1566. if (D->hasAttrs()) {
  1567. AttrVec &Attrs = D->getAttrs();
  1568. for (unsigned i = 0, e = Attrs.size(); i != e;) {
  1569. const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
  1570. if (!OldAA) {
  1571. ++i;
  1572. continue;
  1573. }
  1574. IdentifierInfo *OldPlatform = OldAA->getPlatform();
  1575. if (OldPlatform != Platform) {
  1576. ++i;
  1577. continue;
  1578. }
  1579. FoundAny = true;
  1580. VersionTuple OldIntroduced = OldAA->getIntroduced();
  1581. VersionTuple OldDeprecated = OldAA->getDeprecated();
  1582. VersionTuple OldObsoleted = OldAA->getObsoleted();
  1583. bool OldIsUnavailable = OldAA->getUnavailable();
  1584. if (!versionsMatch(OldIntroduced, Introduced, Override) ||
  1585. !versionsMatch(Deprecated, OldDeprecated, Override) ||
  1586. !versionsMatch(Obsoleted, OldObsoleted, Override) ||
  1587. !(OldIsUnavailable == IsUnavailable ||
  1588. (Override && !OldIsUnavailable && IsUnavailable))) {
  1589. if (Override) {
  1590. int Which = -1;
  1591. VersionTuple FirstVersion;
  1592. VersionTuple SecondVersion;
  1593. if (!versionsMatch(OldIntroduced, Introduced, Override)) {
  1594. Which = 0;
  1595. FirstVersion = OldIntroduced;
  1596. SecondVersion = Introduced;
  1597. } else if (!versionsMatch(Deprecated, OldDeprecated, Override)) {
  1598. Which = 1;
  1599. FirstVersion = Deprecated;
  1600. SecondVersion = OldDeprecated;
  1601. } else if (!versionsMatch(Obsoleted, OldObsoleted, Override)) {
  1602. Which = 2;
  1603. FirstVersion = Obsoleted;
  1604. SecondVersion = OldObsoleted;
  1605. }
  1606. if (Which == -1) {
  1607. Diag(OldAA->getLocation(),
  1608. diag::warn_mismatched_availability_override_unavail)
  1609. << AvailabilityAttr::getPrettyPlatformName(Platform->getName());
  1610. } else {
  1611. Diag(OldAA->getLocation(),
  1612. diag::warn_mismatched_availability_override)
  1613. << Which
  1614. << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
  1615. << FirstVersion.getAsString() << SecondVersion.getAsString();
  1616. }
  1617. Diag(Range.getBegin(), diag::note_overridden_method);
  1618. } else {
  1619. Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
  1620. Diag(Range.getBegin(), diag::note_previous_attribute);
  1621. }
  1622. Attrs.erase(Attrs.begin() + i);
  1623. --e;
  1624. continue;
  1625. }
  1626. VersionTuple MergedIntroduced2 = MergedIntroduced;
  1627. VersionTuple MergedDeprecated2 = MergedDeprecated;
  1628. VersionTuple MergedObsoleted2 = MergedObsoleted;
  1629. if (MergedIntroduced2.empty())
  1630. MergedIntroduced2 = OldIntroduced;
  1631. if (MergedDeprecated2.empty())
  1632. MergedDeprecated2 = OldDeprecated;
  1633. if (MergedObsoleted2.empty())
  1634. MergedObsoleted2 = OldObsoleted;
  1635. if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
  1636. MergedIntroduced2, MergedDeprecated2,
  1637. MergedObsoleted2)) {
  1638. Attrs.erase(Attrs.begin() + i);
  1639. --e;
  1640. continue;
  1641. }
  1642. MergedIntroduced = MergedIntroduced2;
  1643. MergedDeprecated = MergedDeprecated2;
  1644. MergedObsoleted = MergedObsoleted2;
  1645. ++i;
  1646. }
  1647. }
  1648. if (FoundAny &&
  1649. MergedIntroduced == Introduced &&
  1650. MergedDeprecated == Deprecated &&
  1651. MergedObsoleted == Obsoleted)
  1652. return nullptr;
  1653. // Only create a new attribute if !Override, but we want to do
  1654. // the checking.
  1655. if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
  1656. MergedDeprecated, MergedObsoleted) &&
  1657. !Override) {
  1658. return ::new (Context) AvailabilityAttr(Range, Context, Platform,
  1659. Introduced, Deprecated,
  1660. Obsoleted, IsUnavailable, Message,
  1661. AttrSpellingListIndex);
  1662. }
  1663. return nullptr;
  1664. }
  1665. static void handleAvailabilityAttr(Sema &S, Decl *D,
  1666. const AttributeList &Attr) {
  1667. if (!checkAttributeNumArgs(S, Attr, 1))
  1668. return;
  1669. IdentifierLoc *Platform = Attr.getArgAsIdent(0);
  1670. unsigned Index = Attr.getAttributeSpellingListIndex();
  1671. IdentifierInfo *II = Platform->Ident;
  1672. if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
  1673. S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
  1674. << Platform->Ident;
  1675. NamedDecl *ND = dyn_cast<NamedDecl>(D);
  1676. if (!ND) {
  1677. S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
  1678. return;
  1679. }
  1680. AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
  1681. AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
  1682. AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
  1683. bool IsUnavailable = Attr.getUnavailableLoc().isValid();
  1684. StringRef Str;
  1685. if (const StringLiteral *SE =
  1686. dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
  1687. Str = SE->getString();
  1688. AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
  1689. Introduced.Version,
  1690. Deprecated.Version,
  1691. Obsoleted.Version,
  1692. IsUnavailable, Str,
  1693. /*Override=*/false,
  1694. Index);
  1695. if (NewAttr)
  1696. D->addAttr(NewAttr);
  1697. }
  1698. template <class T>
  1699. static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
  1700. typename T::VisibilityType value,
  1701. unsigned attrSpellingListIndex) {
  1702. T *existingAttr = D->getAttr<T>();
  1703. if (existingAttr) {
  1704. typename T::VisibilityType existingValue = existingAttr->getVisibility();
  1705. if (existingValue == value)
  1706. return nullptr;
  1707. S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
  1708. S.Diag(range.getBegin(), diag::note_previous_attribute);
  1709. D->dropAttr<T>();
  1710. }
  1711. return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
  1712. }
  1713. VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
  1714. VisibilityAttr::VisibilityType Vis,
  1715. unsigned AttrSpellingListIndex) {
  1716. return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
  1717. AttrSpellingListIndex);
  1718. }
  1719. TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
  1720. TypeVisibilityAttr::VisibilityType Vis,
  1721. unsigned AttrSpellingListIndex) {
  1722. return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
  1723. AttrSpellingListIndex);
  1724. }
  1725. static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
  1726. bool isTypeVisibility) {
  1727. // Visibility attributes don't mean anything on a typedef.
  1728. if (isa<TypedefNameDecl>(D)) {
  1729. S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
  1730. << Attr.getName();
  1731. return;
  1732. }
  1733. // 'type_visibility' can only go on a type or namespace.
  1734. if (isTypeVisibility &&
  1735. !(isa<TagDecl>(D) ||
  1736. isa<ObjCInterfaceDecl>(D) ||
  1737. isa<NamespaceDecl>(D))) {
  1738. S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
  1739. << Attr.getName() << ExpectedTypeOrNamespace;
  1740. return;
  1741. }
  1742. // Check that the argument is a string literal.
  1743. StringRef TypeStr;
  1744. SourceLocation LiteralLoc;
  1745. if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
  1746. return;
  1747. VisibilityAttr::VisibilityType type;
  1748. if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
  1749. S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
  1750. << Attr.getName() << TypeStr;
  1751. return;
  1752. }
  1753. // Complain about attempts to use protected visibility on targets
  1754. // (like Darwin) that don't support it.
  1755. if (type == VisibilityAttr::Protected &&
  1756. !S.Context.getTargetInfo().hasProtectedVisibility()) {
  1757. S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
  1758. type = VisibilityAttr::Default;
  1759. }
  1760. unsigned Index = Attr.getAttributeSpellingListIndex();
  1761. clang::Attr *newAttr;
  1762. if (isTypeVisibility) {
  1763. newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
  1764. (TypeVisibilityAttr::VisibilityType) type,
  1765. Index);
  1766. } else {
  1767. newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
  1768. }
  1769. if (newAttr)
  1770. D->addAttr(newAttr);
  1771. }
  1772. static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
  1773. const AttributeList &Attr) {
  1774. ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
  1775. if (!Attr.isArgIdent(0)) {
  1776. S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
  1777. << Attr.getName() << 1 << AANT_ArgumentIdentifier;
  1778. return;
  1779. }
  1780. IdentifierLoc *IL = Attr.getArgAsIdent(0);
  1781. ObjCMethodFamilyAttr::FamilyKind F;
  1782. if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
  1783. S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
  1784. << IL->Ident;
  1785. return;
  1786. }
  1787. if (F == ObjCMethodFamilyAttr::OMF_init &&
  1788. !method->getReturnType()->isObjCObjectPointerType()) {
  1789. S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
  1790. << method->getReturnType();
  1791. // Ignore the attribute.
  1792. return;
  1793. }
  1794. method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
  1795. S.Context, F,
  1796. Attr.getAttributeSpellingListIndex()));
  1797. }
  1798. static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
  1799. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
  1800. QualType T = TD->getUnderlyingType();
  1801. if (!T->isCARCBridgableType()) {
  1802. S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
  1803. return;
  1804. }
  1805. }
  1806. else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
  1807. QualType T = PD->getType();
  1808. if (!T->isCARCBridgableType()) {
  1809. S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
  1810. return;
  1811. }
  1812. }
  1813. else {
  1814. // It is okay to include this attribute on properties, e.g.:
  1815. //
  1816. // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
  1817. //
  1818. // In this case it follows tradition and suppresses an error in the above
  1819. // case.
  1820. S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
  1821. }
  1822. D->addAttr(::new (S.Context)
  1823. ObjCNSObjectAttr(Attr.getRange(), S.Context,
  1824. Attr.getAttributeSpellingListIndex()));
  1825. }
  1826. static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
  1827. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
  1828. QualType T = TD->getUnderlyingType();
  1829. if (!T->isObjCObjectPointerType()) {
  1830. S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
  1831. return;
  1832. }
  1833. } else {
  1834. S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
  1835. return;
  1836. }
  1837. D->addAttr(::new (S.Context)
  1838. ObjCIndependentClassAttr(Attr.getRange(), S.Context,
  1839. Attr.getAttributeSpellingListIndex()));
  1840. }
  1841. static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1842. if (!Attr.isArgIdent(0)) {
  1843. S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
  1844. << Attr.getName() << 1 << AANT_ArgumentIdentifier;
  1845. return;
  1846. }
  1847. IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
  1848. BlocksAttr::BlockType type;
  1849. if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
  1850. S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
  1851. << Attr.getName() << II;
  1852. return;
  1853. }
  1854. D->addAttr(::new (S.Context)
  1855. BlocksAttr(Attr.getRange(), S.Context, type,
  1856. Attr.getAttributeSpellingListIndex()));
  1857. }
  1858. static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1859. unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
  1860. if (Attr.getNumArgs() > 0) {
  1861. Expr *E = Attr.getArgAsExpr(0);
  1862. llvm::APSInt Idx(32);
  1863. if (E->isTypeDependent() || E->isValueDependent() ||
  1864. !E->isIntegerConstantExpr(Idx, S.Context)) {
  1865. S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
  1866. << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
  1867. << E->getSourceRange();
  1868. return;
  1869. }
  1870. if (Idx.isSigned() && Idx.isNegative()) {
  1871. S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
  1872. << E->getSourceRange();
  1873. return;
  1874. }
  1875. sentinel = Idx.getZExtValue();
  1876. }
  1877. unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
  1878. if (Attr.getNumArgs() > 1) {
  1879. Expr *E = Attr.getArgAsExpr(1);
  1880. llvm::APSInt Idx(32);
  1881. if (E->isTypeDependent() || E->isValueDependent() ||
  1882. !E->isIntegerConstantExpr(Idx, S.Context)) {
  1883. S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
  1884. << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
  1885. << E->getSourceRange();
  1886. return;
  1887. }
  1888. nullPos = Idx.getZExtValue();
  1889. if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
  1890. // FIXME: This error message could be improved, it would be nice
  1891. // to say what the bounds actually are.
  1892. S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
  1893. << E->getSourceRange();
  1894. return;
  1895. }
  1896. }
  1897. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1898. const FunctionType *FT = FD->getType()->castAs<FunctionType>();
  1899. if (isa<FunctionNoProtoType>(FT)) {
  1900. S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
  1901. return;
  1902. }
  1903. if (!cast<FunctionProtoType>(FT)->isVariadic()) {
  1904. S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
  1905. return;
  1906. }
  1907. } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  1908. if (!MD->isVariadic()) {
  1909. S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
  1910. return;
  1911. }
  1912. } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  1913. if (!BD->isVariadic()) {
  1914. S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
  1915. return;
  1916. }
  1917. } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
  1918. QualType Ty = V->getType();
  1919. if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
  1920. const FunctionType *FT = Ty->isFunctionPointerType()
  1921. ? D->getFunctionType()
  1922. : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
  1923. if (!cast<FunctionProtoType>(FT)->isVariadic()) {
  1924. int m = Ty->isFunctionPointerType() ? 0 : 1;
  1925. S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
  1926. return;
  1927. }
  1928. } else {
  1929. S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
  1930. << Attr.getName() << ExpectedFunctionMethodOrBlock;
  1931. return;
  1932. }
  1933. } else {
  1934. S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
  1935. << Attr.getName() << ExpectedFunctionMethodOrBlock;
  1936. return;
  1937. }
  1938. D->addAttr(::new (S.Context)
  1939. SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
  1940. Attr.getAttributeSpellingListIndex()));
  1941. }
  1942. static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
  1943. if (D->getFunctionType() &&
  1944. D->getFunctionType()->getReturnType()->isVoidType()) {
  1945. S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
  1946. << Attr.getName() << 0;
  1947. return;
  1948. }
  1949. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
  1950. if (MD->getReturnType()->isVoidType()) {
  1951. S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
  1952. << Attr.getName() << 1;
  1953. return;
  1954. }
  1955. D->addAttr(::new (S.Context)
  1956. WarnUnusedResultAttr(Attr.getRange(), S.Context,
  1957. Attr.getAttributeSpellingListIndex()));
  1958. }
  1959. static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  1960. // weak_import only applies to variable & function declarations.
  1961. bool isDef = false;
  1962. if (!D->canBeWeakImported(isDef)) {
  1963. if (isDef)
  1964. S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
  1965. << "weak_import";
  1966. else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
  1967. (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
  1968. (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
  1969. // Nothing to warn about here.
  1970. } else
  1971. S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
  1972. << Attr.getName() << ExpectedVariableOrFunction;
  1973. return;
  1974. }
  1975. D->addAttr(::new (S.Context)
  1976. WeakImportAttr(Attr.getRange(), S.Context,
  1977. Attr.getAttributeSpellingListIndex()));
  1978. }
  1979. // Handles reqd_work_group_size and work_group_size_hint.
  1980. template <typename WorkGroupAttr>
  1981. static void handleWorkGroupSize(Sema &S, Decl *D,
  1982. const AttributeList &Attr) {
  1983. uint32_t WGSize[3];
  1984. for (unsigned i = 0; i < 3; ++i) {
  1985. const Expr *E = Attr.getArgAsExpr(i);
  1986. if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
  1987. return;
  1988. if (WGSize[i] == 0) {
  1989. S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
  1990. << Attr.getName() << E->getSourceRange();
  1991. return;
  1992. }
  1993. }
  1994. WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
  1995. if (Existing && !(Existing->getXDim() == WGSize[0] &&
  1996. Existing->getYDim() == WGSize[1] &&
  1997. Existing->getZDim() == WGSize[2]))
  1998. S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
  1999. D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
  2000. WGSize[0], WGSize[1], WGSize[2],
  2001. Attr.getAttributeSpellingListIndex()));
  2002. }
  2003. static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
  2004. if (!Attr.hasParsedType()) {
  2005. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
  2006. << Attr.getName() << 1;
  2007. return;
  2008. }
  2009. TypeSourceInfo *ParmTSI = nullptr;
  2010. QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
  2011. assert(ParmTSI && "no type source info for attribute argument");
  2012. if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
  2013. (ParmType->isBooleanType() ||
  2014. !ParmType->isIntegralType(S.getASTContext()))) {
  2015. S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
  2016. << ParmType;
  2017. return;
  2018. }
  2019. if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
  2020. if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
  2021. S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
  2022. return;
  2023. }
  2024. }
  2025. D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
  2026. ParmTSI,
  2027. Attr.getAttributeSpellingListIndex()));
  2028. }
  2029. SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
  2030. StringRef Name,
  2031. unsigned AttrSpellingListIndex) {
  2032. if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
  2033. if (ExistingAttr->getName() == Name)
  2034. return nullptr;
  2035. Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
  2036. Diag(Range.getBegin(), diag::note_previous_attribute);
  2037. return nullptr;
  2038. }
  2039. return ::new (Context) SectionAttr(Range, Context, Name,
  2040. AttrSpellingListIndex);
  2041. }
  2042. bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
  2043. std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
  2044. if (!Error.empty()) {
  2045. Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
  2046. return false;
  2047. }
  2048. return true;
  2049. }
  2050. static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  2051. // Make sure that there is a string literal as the sections's single
  2052. // argument.
  2053. StringRef Str;
  2054. SourceLocation LiteralLoc;
  2055. if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
  2056. return;
  2057. if (!S.checkSectionName(LiteralLoc, Str))
  2058. return;
  2059. // If the target wants to validate the section specifier, make it happen.
  2060. std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
  2061. if (!Error.empty()) {
  2062. S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
  2063. << Error;
  2064. return;
  2065. }
  2066. unsigned Index = Attr.getAttributeSpellingListIndex();
  2067. SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
  2068. if (NewAttr)
  2069. D->addAttr(NewAttr);
  2070. }
  2071. // Check for things we'd like to warn about, no errors or validation for now.
  2072. // TODO: Validation should use a backend target library that specifies
  2073. // the allowable subtarget features and cpus. We could use something like a
  2074. // TargetCodeGenInfo hook here to do validation.
  2075. void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
  2076. for (auto Str : {"tune=", "fpmath="})
  2077. if (AttrStr.find(Str) != StringRef::npos)
  2078. Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
  2079. }
  2080. static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  2081. StringRef Str;
  2082. SourceLocation LiteralLoc;
  2083. if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
  2084. return;
  2085. S.checkTargetAttr(LiteralLoc, Str);
  2086. unsigned Index = Attr.getAttributeSpellingListIndex();
  2087. TargetAttr *NewAttr =
  2088. ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
  2089. D->addAttr(NewAttr);
  2090. }
  2091. static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  2092. VarDecl *VD = cast<VarDecl>(D);
  2093. if (!VD->hasLocalStorage()) {
  2094. S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
  2095. return;
  2096. }
  2097. Expr *E = Attr.getArgAsExpr(0);
  2098. SourceLocation Loc = E->getExprLoc();
  2099. FunctionDecl *FD = nullptr;
  2100. DeclarationNameInfo NI;
  2101. // gcc only allows for simple identifiers. Since we support more than gcc, we
  2102. // will warn the user.
  2103. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  2104. if (DRE->hasQualifier())
  2105. S.Diag(Loc, diag::warn_cleanup_ext);
  2106. FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  2107. NI = DRE->getNameInfo();
  2108. if (!FD) {
  2109. S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
  2110. << NI.getName();
  2111. return;
  2112. }
  2113. } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  2114. if (ULE->hasExplicitTemplateArgs())
  2115. S.Diag(Loc, diag::warn_cleanup_ext);
  2116. FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
  2117. NI = ULE->getNameInfo();
  2118. if (!FD) {
  2119. S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
  2120. << NI.getName();
  2121. if (ULE->getType() == S.Context.OverloadTy)
  2122. S.NoteAllOverloadCandidates(ULE);
  2123. return;
  2124. }
  2125. } else {
  2126. S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
  2127. return;
  2128. }
  2129. if (FD->getNumParams() != 1) {
  2130. S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
  2131. << NI.getName();
  2132. return;
  2133. }
  2134. // We're currently more strict than GCC about what function types we accept.
  2135. // If this ever proves to be a problem it should be easy to fix.
  2136. QualType Ty = S.Context.getPointerType(VD->getType());
  2137. QualType ParamTy = FD->getParamDecl(0)->getType();
  2138. if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
  2139. ParamTy, Ty) != Sema::Compatible) {
  2140. S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
  2141. << NI.getName() << ParamTy << Ty;
  2142. return;
  2143. }
  2144. D->addAttr(::new (S.Context)
  2145. CleanupAttr(Attr.getRange(), S.Context, FD,
  2146. Attr.getAttributeSpellingListIndex()));
  2147. }
  2148. /// Handle __attribute__((format_arg((idx)))) attribute based on
  2149. /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
  2150. static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  2151. Expr *IdxExpr = Attr.getArgAsExpr(0);
  2152. uint64_t Idx;
  2153. if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
  2154. return;
  2155. // make sure the format string is really a string
  2156. QualType Ty = getFunctionOrMethodParamType(D, Idx);
  2157. bool not_nsstring_type = !isNSStringType(Ty, S.Context);
  2158. if (not_nsstring_type &&
  2159. !isCFStringType(Ty, S.Context) &&
  2160. (!Ty->isPointerType() ||
  2161. !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
  2162. S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
  2163. << (not_nsstring_type ? "a string type" : "an NSString")
  2164. << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
  2165. return;
  2166. }
  2167. Ty = getFunctionOrMethodResultType(D);
  2168. if (!isNSStringType(Ty, S.Context) &&
  2169. !isCFStringType(Ty, S.Context) &&
  2170. (!Ty->isPointerType() ||
  2171. !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
  2172. S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
  2173. << (not_nsstring_type ? "string type" : "NSString")
  2174. << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
  2175. return;
  2176. }
  2177. // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
  2178. // because that has corrected for the implicit this parameter, and is zero-
  2179. // based. The attribute expects what the user wrote explicitly.
  2180. llvm::APSInt Val;
  2181. IdxExpr->EvaluateAsInt(Val, S.Context);
  2182. D->addAttr(::new (S.Context)
  2183. FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
  2184. Attr.getAttributeSpellingListIndex()));
  2185. }
  2186. enum FormatAttrKind {
  2187. CFStringFormat,
  2188. NSStringFormat,
  2189. StrftimeFormat,
  2190. SupportedFormat,
  2191. IgnoredFormat,
  2192. InvalidFormat
  2193. };
  2194. /// getFormatAttrKind - Map from format attribute names to supported format
  2195. /// types.
  2196. static FormatAttrKind getFormatAttrKind(StringRef Format) {
  2197. return llvm::StringSwitch<FormatAttrKind>(Format)
  2198. // Check for formats that get handled specially.
  2199. .Case("NSString", NSStringFormat)
  2200. .Case("CFString", CFStringFormat)
  2201. .Case("strftime", StrftimeFormat)
  2202. // Otherwise, check for supported formats.
  2203. .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
  2204. .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
  2205. .Case("kprintf", SupportedFormat) // OpenBSD.
  2206. .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
  2207. .Case("os_trace", SupportedFormat)
  2208. .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
  2209. .Default(InvalidFormat);
  2210. }
  2211. /// Handle __attribute__((init_priority(priority))) attributes based on
  2212. /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
  2213. static void handleInitPriorityAttr(Sema &S, Decl *D,
  2214. const AttributeList &Attr) {
  2215. if (!S.getLangOpts().CPlusPlus) {
  2216. S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
  2217. return;
  2218. }
  2219. if (S.getCurFunctionOrMethodDecl()) {
  2220. S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
  2221. Attr.setInvalid();
  2222. return;
  2223. }
  2224. QualType T = cast<VarDecl>(D)->getType();
  2225. if (S.Context.getAsArrayType(T))
  2226. T = S.Context.getBaseElementType(T);
  2227. if (!T->getAs<RecordType>()) {
  2228. S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
  2229. Attr.setInvalid();
  2230. return;
  2231. }
  2232. Expr *E = Attr.getArgAsExpr(0);
  2233. uint32_t prioritynum;
  2234. if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
  2235. Attr.setInvalid();
  2236. return;
  2237. }
  2238. if (prioritynum < 101 || prioritynum > 65535) {
  2239. S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
  2240. << E->getSourceRange();
  2241. Attr.setInvalid();
  2242. return;
  2243. }
  2244. D->addAttr(::new (S.Context)
  2245. InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
  2246. Attr.getAttributeSpellingListIndex()));
  2247. }
  2248. FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
  2249. IdentifierInfo *Format, int FormatIdx,
  2250. int FirstArg,
  2251. unsigned AttrSpellingListIndex) {
  2252. // Check whether we already have an equivalent format attribute.
  2253. for (auto *F : D->specific_attrs<FormatAttr>()) {
  2254. if (F->getType() == Format &&
  2255. F->getFormatIdx() == FormatIdx &&
  2256. F->getFirstArg() == FirstArg) {
  2257. // If we don't have a valid location for this attribute, adopt the
  2258. // location.
  2259. if (F->getLocation().isInvalid())
  2260. F->setRange(Range);
  2261. return nullptr;
  2262. }
  2263. }
  2264. return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
  2265. FirstArg, AttrSpellingListIndex);
  2266. }
  2267. /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
  2268. /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
  2269. static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  2270. if (!Attr.isArgIdent(0)) {
  2271. S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
  2272. << Attr.getName() << 1 << AANT_ArgumentIdentifier;
  2273. return;
  2274. }
  2275. // In C++ the implicit 'this' function parameter also counts, and they are
  2276. // counted from one.
  2277. bool HasImplicitThisParam = isInstanceMethod(D);
  2278. unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
  2279. IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
  2280. StringRef Format = II->getName();
  2281. // Normalize the argument, __foo__ becomes foo.
  2282. if (Format.startswith("__") && Format.endswith("__")) {
  2283. Format = Format.substr(2, Format.size() - 4);
  2284. // If we've modified the string name, we need a new identifier for it.
  2285. II = &S.Context.Idents.get(Format);
  2286. }
  2287. // Check for supported formats.
  2288. FormatAttrKind Kind = getFormatAttrKind(Format);
  2289. if (Kind == IgnoredFormat)
  2290. return;
  2291. if (Kind == InvalidFormat) {
  2292. S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
  2293. << Attr.getName() << II->getName();
  2294. return;
  2295. }
  2296. // checks for the 2nd argument
  2297. Expr *IdxExpr = Attr.getArgAsExpr(1);
  2298. uint32_t Idx;
  2299. if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
  2300. return;
  2301. if (Idx < 1 || Idx > NumArgs) {
  2302. S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
  2303. << Attr.getName() << 2 << IdxExpr->getSourceRange();
  2304. return;
  2305. }
  2306. // FIXME: Do we need to bounds check?
  2307. unsigned ArgIdx = Idx - 1;
  2308. if (HasImplicitThisParam) {
  2309. if (ArgIdx == 0) {
  2310. S.Diag(Attr.getLoc(),
  2311. diag::err_format_attribute_implicit_this_format_string)
  2312. << IdxExpr->getSourceRange();
  2313. return;
  2314. }
  2315. ArgIdx--;
  2316. }
  2317. // make sure the format string is really a string
  2318. QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
  2319. if (Kind == CFStringFormat) {
  2320. if (!isCFStringType(Ty, S.Context)) {
  2321. S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
  2322. << "a CFString" << IdxExpr->getSourceRange()
  2323. << getFunctionOrMethodParamRange(D, ArgIdx);
  2324. return;
  2325. }
  2326. } else if (Kind == NSStringFormat) {
  2327. // FIXME: do we need to check if the type is NSString*? What are the
  2328. // semantics?
  2329. if (!isNSStringType(Ty, S.Context)) {
  2330. S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
  2331. << "an NSString" << IdxExpr->getSourceRange()
  2332. << getFunctionOrMethodParamRange(D, ArgIdx);
  2333. return;
  2334. }
  2335. } else if (!Ty->isPointerType() ||
  2336. !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
  2337. S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
  2338. << "a string type" << IdxExpr->getSourceRange()
  2339. << getFunctionOrMethodParamRange(D, ArgIdx);
  2340. return;
  2341. }
  2342. // check the 3rd argument
  2343. Expr *FirstArgExpr = Attr.getArgAsExpr(2);
  2344. uint32_t FirstArg;
  2345. if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
  2346. return;
  2347. // check if the function is variadic if the 3rd argument non-zero
  2348. if (FirstArg != 0) {
  2349. if (isFunctionOrMethodVariadic(D)) {
  2350. ++NumArgs; // +1 for ...
  2351. } else {
  2352. S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
  2353. return;
  2354. }
  2355. }
  2356. // strftime requires FirstArg to be 0 because it doesn't read from any
  2357. // variable the input is just the current time + the format string.
  2358. if (Kind == StrftimeFormat) {
  2359. if (FirstArg != 0) {
  2360. S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
  2361. << FirstArgExpr->getSourceRange();
  2362. return;
  2363. }
  2364. // if 0 it disables parameter checking (to use with e.g. va_list)
  2365. } else if (FirstArg != 0 && FirstArg != NumArgs) {
  2366. S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
  2367. << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
  2368. return;
  2369. }
  2370. FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
  2371. Idx, FirstArg,
  2372. Attr.getAttributeSpellingListIndex());
  2373. if (NewAttr)
  2374. D->addAttr(NewAttr);
  2375. }
  2376. static void handleTransparentUnionAttr(Sema &S, Decl *D,
  2377. const AttributeList &Attr) {
  2378. // Try to find the underlying union declaration.
  2379. RecordDecl *RD = nullptr;
  2380. TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
  2381. if (TD && TD->getUnderlyingType()->isUnionType())
  2382. RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
  2383. else
  2384. RD = dyn_cast<RecordDecl>(D);
  2385. if (!RD || !RD->isUnion()) {
  2386. S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
  2387. << Attr.getName() << ExpectedUnion;
  2388. return;
  2389. }
  2390. if (!RD->isCompleteDefinition()) {
  2391. S.Diag(Attr.getLoc(),
  2392. diag::warn_transparent_union_attribute_not_definition);
  2393. return;
  2394. }
  2395. RecordDecl::field_iterator Field = RD->field_begin(),
  2396. FieldEnd = RD->field_end();
  2397. if (Field == FieldEnd) {
  2398. S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
  2399. return;
  2400. }
  2401. FieldDecl *FirstField = *Field;
  2402. QualType FirstType = FirstField->getType();
  2403. if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
  2404. S.Diag(FirstField->getLocation(),
  2405. diag::warn_transparent_union_attribute_floating)
  2406. << FirstType->isVectorType() << FirstType;
  2407. return;
  2408. }
  2409. uint64_t FirstSize = S.Context.getTypeSize(FirstType);
  2410. uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
  2411. for (; Field != FieldEnd; ++Field) {
  2412. QualType FieldType = Field->getType();
  2413. // FIXME: this isn't fully correct; we also need to test whether the
  2414. // members of the union would all have the same calling convention as the
  2415. // first member of the union. Checking just the size and alignment isn't
  2416. // sufficient (consider structs passed on the stack instead of in registers
  2417. // as an example).
  2418. if (S.Context.getTypeSize(FieldType) != FirstSize ||
  2419. S.Context.getTypeAlign(FieldType) > FirstAlign) {
  2420. // Warn if we drop the attribute.
  2421. bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
  2422. unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
  2423. : S.Context.getTypeAlign(FieldType);
  2424. S.Diag(Field->getLocation(),
  2425. diag::warn_transparent_union_attribute_field_size_align)
  2426. << isSize << Field->getDeclName() << FieldBits;
  2427. unsigned FirstBits = isSize? FirstSize : FirstAlign;
  2428. S.Diag(FirstField->getLocation(),
  2429. diag::note_transparent_union_first_field_size_align)
  2430. << isSize << FirstBits;
  2431. return;
  2432. }
  2433. }
  2434. RD->addAttr(::new (S.Context)
  2435. TransparentUnionAttr(Attr.getRange(), S.Context,
  2436. Attr.getAttributeSpellingListIndex()));
  2437. }
  2438. static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  2439. // Make sure that there is a string literal as the annotation's single
  2440. // argument.
  2441. StringRef Str;
  2442. if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
  2443. return;
  2444. // Don't duplicate annotations that are already set.
  2445. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  2446. if (I->getAnnotation() == Str)
  2447. return;
  2448. }
  2449. D->addAttr(::new (S.Context)
  2450. AnnotateAttr(Attr.getRange(), S.Context, Str,
  2451. Attr.getAttributeSpellingListIndex()));
  2452. }
  2453. static void handleAlignValueAttr(Sema &S, Decl *D,
  2454. const AttributeList &Attr) {
  2455. S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
  2456. Attr.getAttributeSpellingListIndex());
  2457. }
  2458. void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
  2459. unsigned SpellingListIndex) {
  2460. AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
  2461. SourceLocation AttrLoc = AttrRange.getBegin();
  2462. QualType T;
  2463. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
  2464. T = TD->getUnderlyingType();
  2465. else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
  2466. T = VD->getType();
  2467. else
  2468. llvm_unreachable("Unknown decl type for align_value");
  2469. if (!T->isDependentType() && !T->isAnyPointerType() &&
  2470. !T->isReferenceType() && !T->isMemberPointerType()) {
  2471. Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
  2472. << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
  2473. return;
  2474. }
  2475. if (!E->isValueDependent()) {
  2476. llvm::APSInt Alignment(32);
  2477. ExprResult ICE
  2478. = VerifyIntegerConstantExpression(E, &Alignment,
  2479. diag::err_align_value_attribute_argument_not_int,
  2480. /*AllowFold*/ false);
  2481. if (ICE.isInvalid())
  2482. return;
  2483. if (!Alignment.isPowerOf2()) {
  2484. Diag(AttrLoc, diag::err_alignment_not_power_of_two)
  2485. << E->getSourceRange();
  2486. return;
  2487. }
  2488. D->addAttr(::new (Context)
  2489. AlignValueAttr(AttrRange, Context, ICE.get(),
  2490. SpellingListIndex));
  2491. return;
  2492. }
  2493. // Save dependent expressions in the AST to be instantiated.
  2494. D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
  2495. return;
  2496. }
  2497. static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  2498. // check the attribute arguments.
  2499. if (Attr.getNumArgs() > 1) {
  2500. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
  2501. << Attr.getName() << 1;
  2502. return;
  2503. }
  2504. if (Attr.getNumArgs() == 0) {
  2505. D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
  2506. true, nullptr, Attr.getAttributeSpellingListIndex()));
  2507. return;
  2508. }
  2509. Expr *E = Attr.getArgAsExpr(0);
  2510. if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
  2511. S.Diag(Attr.getEllipsisLoc(),
  2512. diag::err_pack_expansion_without_parameter_packs);
  2513. return;
  2514. }
  2515. if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
  2516. return;
  2517. if (E->isValueDependent()) {
  2518. if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
  2519. if (!TND->getUnderlyingType()->isDependentType()) {
  2520. S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
  2521. << E->getSourceRange();
  2522. return;
  2523. }
  2524. }
  2525. }
  2526. S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
  2527. Attr.isPackExpansion());
  2528. }
  2529. void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
  2530. unsigned SpellingListIndex, bool IsPackExpansion) {
  2531. AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
  2532. SourceLocation AttrLoc = AttrRange.getBegin();
  2533. // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
  2534. if (TmpAttr.isAlignas()) {
  2535. // C++11 [dcl.align]p1:
  2536. // An alignment-specifier may be applied to a variable or to a class
  2537. // data member, but it shall not be applied to a bit-field, a function
  2538. // parameter, the formal parameter of a catch clause, or a variable
  2539. // declared with the register storage class specifier. An
  2540. // alignment-specifier may also be applied to the declaration of a class
  2541. // or enumeration type.
  2542. // C11 6.7.5/2:
  2543. // An alignment attribute shall not be specified in a declaration of
  2544. // a typedef, or a bit-field, or a function, or a parameter, or an
  2545. // object declared with the register storage-class specifier.
  2546. int DiagKind = -1;
  2547. if (isa<ParmVarDecl>(D)) {
  2548. DiagKind = 0;
  2549. } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2550. if (VD->getStorageClass() == SC_Register)
  2551. DiagKind = 1;
  2552. if (VD->isExceptionVariable())
  2553. DiagKind = 2;
  2554. } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  2555. if (FD->isBitField())
  2556. DiagKind = 3;
  2557. } else if (!isa<TagDecl>(D)) {
  2558. Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
  2559. << (TmpAttr.isC11() ? ExpectedVariableOrField
  2560. : ExpectedVariableFieldOrTag);
  2561. return;
  2562. }
  2563. if (DiagKind != -1) {
  2564. Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
  2565. << &TmpAttr << DiagKind;
  2566. return;
  2567. }
  2568. }
  2569. if (E->isTypeDependent() || E->isValueDependent()) {
  2570. // Save dependent expressions in the AST to be instantiated.
  2571. AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
  2572. AA->setPackExpansion(IsPackExpansion);
  2573. D->addAttr(AA);
  2574. return;
  2575. }
  2576. // FIXME: Cache the number on the Attr object?
  2577. llvm::APSInt Alignment(32);
  2578. ExprResult ICE
  2579. = VerifyIntegerConstantExpression(E, &Alignment,
  2580. diag::err_aligned_attribute_argument_not_int,
  2581. /*AllowFold*/ false);
  2582. if (ICE.isInvalid())
  2583. return;
  2584. // C++11 [dcl.align]p2:
  2585. // -- if the constant expression evaluates to zero, the alignment
  2586. // specifier shall have no effect
  2587. // C11 6.7.5p6:
  2588. // An alignment specification of zero has no effect.
  2589. if (!(TmpAttr.isAlignas() && !Alignment)) {
  2590. if(!llvm::isPowerOf2_64(Alignment.getZExtValue())) {
  2591. Diag(AttrLoc, diag::err_alignment_not_power_of_two)
  2592. << E->getSourceRange();
  2593. return;
  2594. }
  2595. if (Context.getTargetInfo().isTLSSupported()) {
  2596. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  2597. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2598. if (VD->getTLSKind()) {
  2599. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  2600. if (Alignment.getSExtValue() > MaxAlignChars.getQuantity()) {
  2601. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  2602. << (unsigned)Alignment.getZExtValue() << VD
  2603. << (unsigned)MaxAlignChars.getQuantity();
  2604. return;
  2605. }
  2606. }
  2607. }
  2608. }
  2609. }
  2610. }
  2611. // Alignment calculations can wrap around if it's greater than 2**28.
  2612. unsigned MaxValidAlignment = TmpAttr.isDeclspec() ? 8192 : 268435456;
  2613. if (Alignment.getZExtValue() > MaxValidAlignment) {
  2614. Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
  2615. << E->getSourceRange();
  2616. return;
  2617. }
  2618. AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
  2619. ICE.get(), SpellingListIndex);
  2620. AA->setPackExpansion(IsPackExpansion);
  2621. D->addAttr(AA);
  2622. }
  2623. void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
  2624. unsigned SpellingListIndex, bool IsPackExpansion) {
  2625. // FIXME: Cache the number on the Attr object if non-dependent?
  2626. // FIXME: Perform checking of type validity
  2627. AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
  2628. SpellingListIndex);
  2629. AA->setPackExpansion(IsPackExpansion);
  2630. D->addAttr(AA);
  2631. }
  2632. void Sema::CheckAlignasUnderalignment(Decl *D) {
  2633. assert(D->hasAttrs() && "no attributes on decl");
  2634. QualType UnderlyingTy, DiagTy;
  2635. if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
  2636. UnderlyingTy = DiagTy = VD->getType();
  2637. } else {
  2638. UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
  2639. if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
  2640. UnderlyingTy = ED->getIntegerType();
  2641. }
  2642. if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
  2643. return;
  2644. // C++11 [dcl.align]p5, C11 6.7.5/4:
  2645. // The combined effect of all alignment attributes in a declaration shall
  2646. // not specify an alignment that is less strict than the alignment that
  2647. // would otherwise be required for the entity being declared.
  2648. AlignedAttr *AlignasAttr = nullptr;
  2649. unsigned Align = 0;
  2650. for (auto *I : D->specific_attrs<AlignedAttr>()) {
  2651. if (I->isAlignmentDependent())
  2652. return;
  2653. if (I->isAlignas())
  2654. AlignasAttr = I;
  2655. Align = std::max(Align, I->getAlignment(Context));
  2656. }
  2657. if (AlignasAttr && Align) {
  2658. CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
  2659. CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
  2660. if (NaturalAlign > RequestedAlign)
  2661. Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
  2662. << DiagTy << (unsigned)NaturalAlign.getQuantity();
  2663. }
  2664. }
  2665. bool Sema::checkMSInheritanceAttrOnDefinition(
  2666. CXXRecordDecl *RD, SourceRange Range, bool BestCase,
  2667. MSInheritanceAttr::Spelling SemanticSpelling) {
  2668. assert(RD->hasDefinition() && "RD has no definition!");
  2669. // We may not have seen base specifiers or any virtual methods yet. We will
  2670. // have to wait until the record is defined to catch any mismatches.
  2671. if (!RD->getDefinition()->isCompleteDefinition())
  2672. return false;
  2673. // The unspecified model never matches what a definition could need.
  2674. if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
  2675. return false;
  2676. if (BestCase) {
  2677. if (RD->calculateInheritanceModel() == SemanticSpelling)
  2678. return false;
  2679. } else {
  2680. if (RD->calculateInheritanceModel() <= SemanticSpelling)
  2681. return false;
  2682. }
  2683. Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
  2684. << 0 /*definition*/;
  2685. Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
  2686. << RD->getNameAsString();
  2687. return true;
  2688. }
  2689. /// handleModeAttr - This attribute modifies the width of a decl with primitive
  2690. /// type.
  2691. ///
  2692. /// Despite what would be logical, the mode attribute is a decl attribute, not a
  2693. /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
  2694. /// HImode, not an intermediate pointer.
  2695. static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  2696. // This attribute isn't documented, but glibc uses it. It changes
  2697. // the width of an int or unsigned int to the specified size.
  2698. if (!Attr.isArgIdent(0)) {
  2699. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
  2700. << AANT_ArgumentIdentifier;
  2701. return;
  2702. }
  2703. IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
  2704. StringRef Str = Name->getName();
  2705. // Normalize the attribute name, __foo__ becomes foo.
  2706. if (Str.startswith("__") && Str.endswith("__"))
  2707. Str = Str.substr(2, Str.size() - 4);
  2708. unsigned DestWidth = 0;
  2709. bool IntegerMode = true;
  2710. bool ComplexMode = false;
  2711. switch (Str.size()) {
  2712. case 2:
  2713. switch (Str[0]) {
  2714. case 'Q': DestWidth = 8; break;
  2715. case 'H': DestWidth = 16; break;
  2716. case 'S': DestWidth = 32; break;
  2717. case 'D': DestWidth = 64; break;
  2718. case 'X': DestWidth = 96; break;
  2719. case 'T': DestWidth = 128; break;
  2720. }
  2721. if (Str[1] == 'F') {
  2722. IntegerMode = false;
  2723. } else if (Str[1] == 'C') {
  2724. IntegerMode = false;
  2725. ComplexMode = true;
  2726. } else if (Str[1] != 'I') {
  2727. DestWidth = 0;
  2728. }
  2729. break;
  2730. case 4:
  2731. // FIXME: glibc uses 'word' to define register_t; this is narrower than a
  2732. // pointer on PIC16 and other embedded platforms.
  2733. if (Str == "word")
  2734. DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
  2735. else if (Str == "byte")
  2736. DestWidth = S.Context.getTargetInfo().getCharWidth();
  2737. break;
  2738. case 7:
  2739. if (Str == "pointer")
  2740. DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
  2741. break;
  2742. case 11:
  2743. if (Str == "unwind_word")
  2744. DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
  2745. break;
  2746. }
  2747. QualType OldTy;
  2748. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
  2749. OldTy = TD->getUnderlyingType();
  2750. else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
  2751. OldTy = VD->getType();
  2752. else {
  2753. S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
  2754. << Attr.getName() << Attr.getRange();
  2755. return;
  2756. }
  2757. // Base type can also be a vector type (see PR17453).
  2758. // Distinguish between base type and base element type.
  2759. QualType OldElemTy = OldTy;
  2760. if (const VectorType *VT = OldTy->getAs<VectorType>())
  2761. OldElemTy = VT->getElementType();
  2762. if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType())
  2763. S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
  2764. else if (IntegerMode) {
  2765. if (!OldElemTy->isIntegralOrEnumerationType())
  2766. S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
  2767. } else if (ComplexMode) {
  2768. if (!OldElemTy->isComplexType())
  2769. S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
  2770. } else {
  2771. if (!OldElemTy->isFloatingType())
  2772. S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
  2773. }
  2774. // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
  2775. // and friends, at least with glibc.
  2776. // FIXME: Make sure floating-point mappings are accurate
  2777. // FIXME: Support XF and TF types
  2778. if (!DestWidth) {
  2779. S.Diag(Attr.getLoc(), diag::err_machine_mode) << 0 /*Unknown*/ << Name;
  2780. return;
  2781. }
  2782. QualType NewElemTy;
  2783. if (IntegerMode)
  2784. NewElemTy = S.Context.getIntTypeForBitwidth(
  2785. DestWidth, OldElemTy->isSignedIntegerType());
  2786. else
  2787. NewElemTy = S.Context.getRealTypeForBitwidth(DestWidth);
  2788. if (NewElemTy.isNull()) {
  2789. S.Diag(Attr.getLoc(), diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
  2790. return;
  2791. }
  2792. if (ComplexMode) {
  2793. NewElemTy = S.Context.getComplexType(NewElemTy);
  2794. }
  2795. QualType NewTy = NewElemTy;
  2796. if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
  2797. // Complex machine mode does not support base vector types.
  2798. if (ComplexMode) {
  2799. S.Diag(Attr.getLoc(), diag::err_complex_mode_vector_type);
  2800. return;
  2801. }
  2802. unsigned NumElements = S.Context.getTypeSize(OldElemTy) *
  2803. OldVT->getNumElements() /
  2804. S.Context.getTypeSize(NewElemTy);
  2805. NewTy =
  2806. S.Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
  2807. }
  2808. if (NewTy.isNull()) {
  2809. S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
  2810. return;
  2811. }
  2812. // Install the new type.
  2813. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
  2814. TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
  2815. else
  2816. cast<ValueDecl>(D)->setType(NewTy);
  2817. D->addAttr(::new (S.Context)
  2818. ModeAttr(Attr.getRange(), S.Context, Name,
  2819. Attr.getAttributeSpellingListIndex()));
  2820. }
  2821. static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  2822. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2823. if (!VD->hasGlobalStorage())
  2824. S.Diag(Attr.getLoc(),
  2825. diag::warn_attribute_requires_functions_or_static_globals)
  2826. << Attr.getName();
  2827. } else if (!isFunctionOrMethod(D)) {
  2828. S.Diag(Attr.getLoc(),
  2829. diag::warn_attribute_requires_functions_or_static_globals)
  2830. << Attr.getName();
  2831. return;
  2832. }
  2833. D->addAttr(::new (S.Context)
  2834. NoDebugAttr(Attr.getRange(), S.Context,
  2835. Attr.getAttributeSpellingListIndex()));
  2836. }
  2837. AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
  2838. IdentifierInfo *Ident,
  2839. unsigned AttrSpellingListIndex) {
  2840. if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
  2841. Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
  2842. Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
  2843. return nullptr;
  2844. }
  2845. if (D->hasAttr<AlwaysInlineAttr>())
  2846. return nullptr;
  2847. return ::new (Context) AlwaysInlineAttr(Range, Context,
  2848. AttrSpellingListIndex);
  2849. }
  2850. MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
  2851. unsigned AttrSpellingListIndex) {
  2852. if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
  2853. Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
  2854. Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
  2855. return nullptr;
  2856. }
  2857. if (D->hasAttr<MinSizeAttr>())
  2858. return nullptr;
  2859. return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
  2860. }
  2861. OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
  2862. unsigned AttrSpellingListIndex) {
  2863. if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
  2864. Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
  2865. Diag(Range.getBegin(), diag::note_conflicting_attribute);
  2866. D->dropAttr<AlwaysInlineAttr>();
  2867. }
  2868. if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
  2869. Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
  2870. Diag(Range.getBegin(), diag::note_conflicting_attribute);
  2871. D->dropAttr<MinSizeAttr>();
  2872. }
  2873. if (D->hasAttr<OptimizeNoneAttr>())
  2874. return nullptr;
  2875. return ::new (Context) OptimizeNoneAttr(Range, Context,
  2876. AttrSpellingListIndex);
  2877. }
  2878. static void handleAlwaysInlineAttr(Sema &S, Decl *D,
  2879. const AttributeList &Attr) {
  2880. if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
  2881. D, Attr.getRange(), Attr.getName(),
  2882. Attr.getAttributeSpellingListIndex()))
  2883. D->addAttr(Inline);
  2884. }
  2885. static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  2886. if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
  2887. D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
  2888. D->addAttr(MinSize);
  2889. }
  2890. static void handleOptimizeNoneAttr(Sema &S, Decl *D,
  2891. const AttributeList &Attr) {
  2892. if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
  2893. D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
  2894. D->addAttr(Optnone);
  2895. }
  2896. static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  2897. FunctionDecl *FD = cast<FunctionDecl>(D);
  2898. if (!FD->getReturnType()->isVoidType()) {
  2899. SourceRange RTRange = FD->getReturnTypeSourceRange();
  2900. S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
  2901. << FD->getType()
  2902. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  2903. : FixItHint());
  2904. return;
  2905. }
  2906. D->addAttr(::new (S.Context)
  2907. CUDAGlobalAttr(Attr.getRange(), S.Context,
  2908. Attr.getAttributeSpellingListIndex()));
  2909. }
  2910. static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  2911. FunctionDecl *Fn = cast<FunctionDecl>(D);
  2912. if (!Fn->isInlineSpecified()) {
  2913. S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
  2914. return;
  2915. }
  2916. D->addAttr(::new (S.Context)
  2917. GNUInlineAttr(Attr.getRange(), S.Context,
  2918. Attr.getAttributeSpellingListIndex()));
  2919. }
  2920. static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  2921. if (hasDeclarator(D)) return;
  2922. // Diagnostic is emitted elsewhere: here we store the (valid) Attr
  2923. // in the Decl node for syntactic reasoning, e.g., pretty-printing.
  2924. CallingConv CC;
  2925. if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
  2926. return;
  2927. if (!isa<ObjCMethodDecl>(D)) {
  2928. S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
  2929. << Attr.getName() << ExpectedFunctionOrMethod;
  2930. return;
  2931. }
  2932. switch (Attr.getKind()) {
  2933. case AttributeList::AT_FastCall:
  2934. D->addAttr(::new (S.Context)
  2935. FastCallAttr(Attr.getRange(), S.Context,
  2936. Attr.getAttributeSpellingListIndex()));
  2937. return;
  2938. case AttributeList::AT_StdCall:
  2939. D->addAttr(::new (S.Context)
  2940. StdCallAttr(Attr.getRange(), S.Context,
  2941. Attr.getAttributeSpellingListIndex()));
  2942. return;
  2943. case AttributeList::AT_ThisCall:
  2944. D->addAttr(::new (S.Context)
  2945. ThisCallAttr(Attr.getRange(), S.Context,
  2946. Attr.getAttributeSpellingListIndex()));
  2947. return;
  2948. case AttributeList::AT_CDecl:
  2949. D->addAttr(::new (S.Context)
  2950. CDeclAttr(Attr.getRange(), S.Context,
  2951. Attr.getAttributeSpellingListIndex()));
  2952. return;
  2953. case AttributeList::AT_Pascal:
  2954. D->addAttr(::new (S.Context)
  2955. PascalAttr(Attr.getRange(), S.Context,
  2956. Attr.getAttributeSpellingListIndex()));
  2957. return;
  2958. case AttributeList::AT_VectorCall:
  2959. D->addAttr(::new (S.Context)
  2960. VectorCallAttr(Attr.getRange(), S.Context,
  2961. Attr.getAttributeSpellingListIndex()));
  2962. return;
  2963. case AttributeList::AT_MSABI:
  2964. D->addAttr(::new (S.Context)
  2965. MSABIAttr(Attr.getRange(), S.Context,
  2966. Attr.getAttributeSpellingListIndex()));
  2967. return;
  2968. case AttributeList::AT_SysVABI:
  2969. D->addAttr(::new (S.Context)
  2970. SysVABIAttr(Attr.getRange(), S.Context,
  2971. Attr.getAttributeSpellingListIndex()));
  2972. return;
  2973. case AttributeList::AT_Pcs: {
  2974. PcsAttr::PCSType PCS;
  2975. switch (CC) {
  2976. case CC_AAPCS:
  2977. PCS = PcsAttr::AAPCS;
  2978. break;
  2979. case CC_AAPCS_VFP:
  2980. PCS = PcsAttr::AAPCS_VFP;
  2981. break;
  2982. default:
  2983. llvm_unreachable("unexpected calling convention in pcs attribute");
  2984. }
  2985. D->addAttr(::new (S.Context)
  2986. PcsAttr(Attr.getRange(), S.Context, PCS,
  2987. Attr.getAttributeSpellingListIndex()));
  2988. return;
  2989. }
  2990. case AttributeList::AT_IntelOclBicc:
  2991. D->addAttr(::new (S.Context)
  2992. IntelOclBiccAttr(Attr.getRange(), S.Context,
  2993. Attr.getAttributeSpellingListIndex()));
  2994. return;
  2995. default:
  2996. llvm_unreachable("unexpected attribute kind");
  2997. }
  2998. }
  2999. bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
  3000. const FunctionDecl *FD) {
  3001. if (attr.isInvalid())
  3002. return true;
  3003. unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
  3004. if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
  3005. attr.setInvalid();
  3006. return true;
  3007. }
  3008. // TODO: diagnose uses of these conventions on the wrong target.
  3009. switch (attr.getKind()) {
  3010. case AttributeList::AT_CDecl: CC = CC_C; break;
  3011. case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
  3012. case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
  3013. case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
  3014. case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
  3015. case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
  3016. case AttributeList::AT_MSABI:
  3017. CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
  3018. CC_X86_64Win64;
  3019. break;
  3020. case AttributeList::AT_SysVABI:
  3021. CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
  3022. CC_C;
  3023. break;
  3024. case AttributeList::AT_Pcs: {
  3025. StringRef StrRef;
  3026. if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
  3027. attr.setInvalid();
  3028. return true;
  3029. }
  3030. if (StrRef == "aapcs") {
  3031. CC = CC_AAPCS;
  3032. break;
  3033. } else if (StrRef == "aapcs-vfp") {
  3034. CC = CC_AAPCS_VFP;
  3035. break;
  3036. }
  3037. attr.setInvalid();
  3038. Diag(attr.getLoc(), diag::err_invalid_pcs);
  3039. return true;
  3040. }
  3041. case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
  3042. default: llvm_unreachable("unexpected attribute kind");
  3043. }
  3044. const TargetInfo &TI = Context.getTargetInfo();
  3045. TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
  3046. if (A != TargetInfo::CCCR_OK) {
  3047. if (A == TargetInfo::CCCR_Warning)
  3048. Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
  3049. // This convention is not valid for the target. Use the default function or
  3050. // method calling convention.
  3051. TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
  3052. if (FD)
  3053. MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
  3054. TargetInfo::CCMT_NonMember;
  3055. CC = TI.getDefaultCallingConv(MT);
  3056. }
  3057. return false;
  3058. }
  3059. /// Checks a regparm attribute, returning true if it is ill-formed and
  3060. /// otherwise setting numParams to the appropriate value.
  3061. bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
  3062. if (Attr.isInvalid())
  3063. return true;
  3064. if (!checkAttributeNumArgs(*this, Attr, 1)) {
  3065. Attr.setInvalid();
  3066. return true;
  3067. }
  3068. uint32_t NP;
  3069. Expr *NumParamsExpr = Attr.getArgAsExpr(0);
  3070. if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
  3071. Attr.setInvalid();
  3072. return true;
  3073. }
  3074. if (Context.getTargetInfo().getRegParmMax() == 0) {
  3075. Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
  3076. << NumParamsExpr->getSourceRange();
  3077. Attr.setInvalid();
  3078. return true;
  3079. }
  3080. numParams = NP;
  3081. if (numParams > Context.getTargetInfo().getRegParmMax()) {
  3082. Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
  3083. << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
  3084. Attr.setInvalid();
  3085. return true;
  3086. }
  3087. return false;
  3088. }
  3089. // Checks whether an argument of launch_bounds attribute is acceptable
  3090. // May output an error.
  3091. static bool checkLaunchBoundsArgument(Sema &S, Expr *E,
  3092. const CUDALaunchBoundsAttr &Attr,
  3093. const unsigned Idx) {
  3094. if (S.DiagnoseUnexpandedParameterPack(E))
  3095. return false;
  3096. // Accept template arguments for now as they depend on something else.
  3097. // We'll get to check them when they eventually get instantiated.
  3098. if (E->isValueDependent())
  3099. return true;
  3100. llvm::APSInt I(64);
  3101. if (!E->isIntegerConstantExpr(I, S.Context)) {
  3102. S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
  3103. << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
  3104. return false;
  3105. }
  3106. // Make sure we can fit it in 32 bits.
  3107. if (!I.isIntN(32)) {
  3108. S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
  3109. << 32 << /* Unsigned */ 1;
  3110. return false;
  3111. }
  3112. if (I < 0)
  3113. S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
  3114. << &Attr << Idx << E->getSourceRange();
  3115. return true;
  3116. }
  3117. void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
  3118. Expr *MinBlocks, unsigned SpellingListIndex) {
  3119. CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
  3120. SpellingListIndex);
  3121. if (!checkLaunchBoundsArgument(*this, MaxThreads, TmpAttr, 0))
  3122. return;
  3123. if (MinBlocks && !checkLaunchBoundsArgument(*this, MinBlocks, TmpAttr, 1))
  3124. return;
  3125. D->addAttr(::new (Context) CUDALaunchBoundsAttr(
  3126. AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
  3127. }
  3128. static void handleLaunchBoundsAttr(Sema &S, Decl *D,
  3129. const AttributeList &Attr) {
  3130. if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
  3131. !checkAttributeAtMostNumArgs(S, Attr, 2))
  3132. return;
  3133. S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
  3134. Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
  3135. Attr.getAttributeSpellingListIndex());
  3136. }
  3137. static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
  3138. const AttributeList &Attr) {
  3139. if (!Attr.isArgIdent(0)) {
  3140. S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
  3141. << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
  3142. return;
  3143. }
  3144. if (!checkAttributeNumArgs(S, Attr, 3))
  3145. return;
  3146. IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
  3147. if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
  3148. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
  3149. << Attr.getName() << ExpectedFunctionOrMethod;
  3150. return;
  3151. }
  3152. uint64_t ArgumentIdx;
  3153. if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
  3154. ArgumentIdx))
  3155. return;
  3156. uint64_t TypeTagIdx;
  3157. if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
  3158. TypeTagIdx))
  3159. return;
  3160. bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
  3161. if (IsPointer) {
  3162. // Ensure that buffer has a pointer type.
  3163. QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
  3164. if (!BufferTy->isPointerType()) {
  3165. S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
  3166. << Attr.getName();
  3167. }
  3168. }
  3169. D->addAttr(::new (S.Context)
  3170. ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
  3171. ArgumentIdx, TypeTagIdx, IsPointer,
  3172. Attr.getAttributeSpellingListIndex()));
  3173. }
  3174. static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
  3175. const AttributeList &Attr) {
  3176. if (!Attr.isArgIdent(0)) {
  3177. S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
  3178. << Attr.getName() << 1 << AANT_ArgumentIdentifier;
  3179. return;
  3180. }
  3181. if (!checkAttributeNumArgs(S, Attr, 1))
  3182. return;
  3183. if (!isa<VarDecl>(D)) {
  3184. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
  3185. << Attr.getName() << ExpectedVariable;
  3186. return;
  3187. }
  3188. IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
  3189. TypeSourceInfo *MatchingCTypeLoc = nullptr;
  3190. S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
  3191. assert(MatchingCTypeLoc && "no type source info for attribute argument");
  3192. D->addAttr(::new (S.Context)
  3193. TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
  3194. MatchingCTypeLoc,
  3195. Attr.getLayoutCompatible(),
  3196. Attr.getMustBeNull(),
  3197. Attr.getAttributeSpellingListIndex()));
  3198. }
  3199. //===----------------------------------------------------------------------===//
  3200. // Checker-specific attribute handlers.
  3201. //===----------------------------------------------------------------------===//
  3202. static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
  3203. return type->isDependentType() ||
  3204. type->isObjCRetainableType();
  3205. }
  3206. static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
  3207. return type->isDependentType() ||
  3208. type->isObjCObjectPointerType() ||
  3209. S.Context.isObjCNSObjectType(type);
  3210. }
  3211. static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
  3212. return type->isDependentType() ||
  3213. type->isPointerType() ||
  3214. isValidSubjectOfNSAttribute(S, type);
  3215. }
  3216. static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  3217. ParmVarDecl *param = cast<ParmVarDecl>(D);
  3218. bool typeOK, cf;
  3219. if (Attr.getKind() == AttributeList::AT_NSConsumed) {
  3220. typeOK = isValidSubjectOfNSAttribute(S, param->getType());
  3221. cf = false;
  3222. } else {
  3223. typeOK = isValidSubjectOfCFAttribute(S, param->getType());
  3224. cf = true;
  3225. }
  3226. if (!typeOK) {
  3227. S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
  3228. << Attr.getRange() << Attr.getName() << cf;
  3229. return;
  3230. }
  3231. if (cf)
  3232. param->addAttr(::new (S.Context)
  3233. CFConsumedAttr(Attr.getRange(), S.Context,
  3234. Attr.getAttributeSpellingListIndex()));
  3235. else
  3236. param->addAttr(::new (S.Context)
  3237. NSConsumedAttr(Attr.getRange(), S.Context,
  3238. Attr.getAttributeSpellingListIndex()));
  3239. }
  3240. static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
  3241. const AttributeList &Attr) {
  3242. QualType returnType;
  3243. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
  3244. returnType = MD->getReturnType();
  3245. else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
  3246. (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
  3247. return; // ignore: was handled as a type attribute
  3248. else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
  3249. returnType = PD->getType();
  3250. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  3251. returnType = FD->getReturnType();
  3252. else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
  3253. returnType = Param->getType()->getPointeeType();
  3254. if (returnType.isNull()) {
  3255. S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
  3256. << Attr.getName() << /*pointer-to-CF*/2
  3257. << Attr.getRange();
  3258. return;
  3259. }
  3260. } else {
  3261. AttributeDeclKind ExpectedDeclKind;
  3262. switch (Attr.getKind()) {
  3263. default: llvm_unreachable("invalid ownership attribute");
  3264. case AttributeList::AT_NSReturnsRetained:
  3265. case AttributeList::AT_NSReturnsAutoreleased:
  3266. case AttributeList::AT_NSReturnsNotRetained:
  3267. ExpectedDeclKind = ExpectedFunctionOrMethod;
  3268. break;
  3269. case AttributeList::AT_CFReturnsRetained:
  3270. case AttributeList::AT_CFReturnsNotRetained:
  3271. ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
  3272. break;
  3273. }
  3274. S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
  3275. << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
  3276. return;
  3277. }
  3278. bool typeOK;
  3279. bool cf;
  3280. switch (Attr.getKind()) {
  3281. default: llvm_unreachable("invalid ownership attribute");
  3282. case AttributeList::AT_NSReturnsRetained:
  3283. typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
  3284. cf = false;
  3285. break;
  3286. case AttributeList::AT_NSReturnsAutoreleased:
  3287. case AttributeList::AT_NSReturnsNotRetained:
  3288. typeOK = isValidSubjectOfNSAttribute(S, returnType);
  3289. cf = false;
  3290. break;
  3291. case AttributeList::AT_CFReturnsRetained:
  3292. case AttributeList::AT_CFReturnsNotRetained:
  3293. typeOK = isValidSubjectOfCFAttribute(S, returnType);
  3294. cf = true;
  3295. break;
  3296. }
  3297. if (!typeOK) {
  3298. if (isa<ParmVarDecl>(D)) {
  3299. S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
  3300. << Attr.getName() << /*pointer-to-CF*/2
  3301. << Attr.getRange();
  3302. } else {
  3303. // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
  3304. enum : unsigned {
  3305. Function,
  3306. Method,
  3307. Property
  3308. } SubjectKind = Function;
  3309. if (isa<ObjCMethodDecl>(D))
  3310. SubjectKind = Method;
  3311. else if (isa<ObjCPropertyDecl>(D))
  3312. SubjectKind = Property;
  3313. S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
  3314. << Attr.getName() << SubjectKind << cf
  3315. << Attr.getRange();
  3316. }
  3317. return;
  3318. }
  3319. switch (Attr.getKind()) {
  3320. default:
  3321. llvm_unreachable("invalid ownership attribute");
  3322. case AttributeList::AT_NSReturnsAutoreleased:
  3323. D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
  3324. Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
  3325. return;
  3326. case AttributeList::AT_CFReturnsNotRetained:
  3327. D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
  3328. Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
  3329. return;
  3330. case AttributeList::AT_NSReturnsNotRetained:
  3331. D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
  3332. Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
  3333. return;
  3334. case AttributeList::AT_CFReturnsRetained:
  3335. D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
  3336. Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
  3337. return;
  3338. case AttributeList::AT_NSReturnsRetained:
  3339. D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
  3340. Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
  3341. return;
  3342. };
  3343. }
  3344. static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
  3345. const AttributeList &attr) {
  3346. const int EP_ObjCMethod = 1;
  3347. const int EP_ObjCProperty = 2;
  3348. SourceLocation loc = attr.getLoc();
  3349. QualType resultType;
  3350. if (isa<ObjCMethodDecl>(D))
  3351. resultType = cast<ObjCMethodDecl>(D)->getReturnType();
  3352. else
  3353. resultType = cast<ObjCPropertyDecl>(D)->getType();
  3354. if (!resultType->isReferenceType() &&
  3355. (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
  3356. S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
  3357. << SourceRange(loc)
  3358. << attr.getName()
  3359. << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
  3360. << /*non-retainable pointer*/ 2;
  3361. // Drop the attribute.
  3362. return;
  3363. }
  3364. D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
  3365. attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
  3366. }
  3367. static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
  3368. const AttributeList &attr) {
  3369. ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
  3370. DeclContext *DC = method->getDeclContext();
  3371. if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
  3372. S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
  3373. << attr.getName() << 0;
  3374. S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
  3375. return;
  3376. }
  3377. if (method->getMethodFamily() == OMF_dealloc) {
  3378. S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
  3379. << attr.getName() << 1;
  3380. return;
  3381. }
  3382. method->addAttr(::new (S.Context)
  3383. ObjCRequiresSuperAttr(attr.getRange(), S.Context,
  3384. attr.getAttributeSpellingListIndex()));
  3385. }
  3386. static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
  3387. const AttributeList &Attr) {
  3388. if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr))
  3389. return;
  3390. D->addAttr(::new (S.Context)
  3391. CFAuditedTransferAttr(Attr.getRange(), S.Context,
  3392. Attr.getAttributeSpellingListIndex()));
  3393. }
  3394. static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
  3395. const AttributeList &Attr) {
  3396. if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr))
  3397. return;
  3398. D->addAttr(::new (S.Context)
  3399. CFUnknownTransferAttr(Attr.getRange(), S.Context,
  3400. Attr.getAttributeSpellingListIndex()));
  3401. }
  3402. static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
  3403. const AttributeList &Attr) {
  3404. IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
  3405. if (!Parm) {
  3406. S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
  3407. return;
  3408. }
  3409. // Typedefs only allow objc_bridge(id) and have some additional checking.
  3410. if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
  3411. if (!Parm->Ident->isStr("id")) {
  3412. S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
  3413. << Attr.getName();
  3414. return;
  3415. }
  3416. // Only allow 'cv void *'.
  3417. QualType T = TD->getUnderlyingType();
  3418. if (!T->isVoidPointerType()) {
  3419. S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
  3420. return;
  3421. }
  3422. }
  3423. D->addAttr(::new (S.Context)
  3424. ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
  3425. Attr.getAttributeSpellingListIndex()));
  3426. }
  3427. static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
  3428. const AttributeList &Attr) {
  3429. IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
  3430. if (!Parm) {
  3431. S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
  3432. return;
  3433. }
  3434. D->addAttr(::new (S.Context)
  3435. ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
  3436. Attr.getAttributeSpellingListIndex()));
  3437. }
  3438. static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
  3439. const AttributeList &Attr) {
  3440. IdentifierInfo *RelatedClass =
  3441. Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
  3442. if (!RelatedClass) {
  3443. S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
  3444. return;
  3445. }
  3446. IdentifierInfo *ClassMethod =
  3447. Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
  3448. IdentifierInfo *InstanceMethod =
  3449. Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
  3450. D->addAttr(::new (S.Context)
  3451. ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
  3452. ClassMethod, InstanceMethod,
  3453. Attr.getAttributeSpellingListIndex()));
  3454. }
  3455. static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
  3456. const AttributeList &Attr) {
  3457. ObjCInterfaceDecl *IFace;
  3458. if (ObjCCategoryDecl *CatDecl =
  3459. dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
  3460. IFace = CatDecl->getClassInterface();
  3461. else
  3462. IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
  3463. if (!IFace)
  3464. return;
  3465. IFace->setHasDesignatedInitializers();
  3466. D->addAttr(::new (S.Context)
  3467. ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
  3468. Attr.getAttributeSpellingListIndex()));
  3469. }
  3470. static void handleObjCRuntimeName(Sema &S, Decl *D,
  3471. const AttributeList &Attr) {
  3472. StringRef MetaDataName;
  3473. if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
  3474. return;
  3475. D->addAttr(::new (S.Context)
  3476. ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
  3477. MetaDataName,
  3478. Attr.getAttributeSpellingListIndex()));
  3479. }
  3480. // when a user wants to use objc_boxable with a union or struct
  3481. // but she doesn't have access to the declaration (legacy/third-party code)
  3482. // then she can 'enable' this feature via trick with a typedef
  3483. // e.g.:
  3484. // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
  3485. static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
  3486. bool notify = false;
  3487. RecordDecl *RD = dyn_cast<RecordDecl>(D);
  3488. if (RD && RD->getDefinition()) {
  3489. RD = RD->getDefinition();
  3490. notify = true;
  3491. }
  3492. if (RD) {
  3493. ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
  3494. ObjCBoxableAttr(Attr.getRange(), S.Context,
  3495. Attr.getAttributeSpellingListIndex());
  3496. RD->addAttr(BoxableAttr);
  3497. if (notify) {
  3498. // we need to notify ASTReader/ASTWriter about
  3499. // modification of existing declaration
  3500. if (ASTMutationListener *L = S.getASTMutationListener())
  3501. L->AddedAttributeToRecord(BoxableAttr, RD);
  3502. }
  3503. }
  3504. }
  3505. static void handleObjCOwnershipAttr(Sema &S, Decl *D,
  3506. const AttributeList &Attr) {
  3507. if (hasDeclarator(D)) return;
  3508. S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
  3509. << Attr.getRange() << Attr.getName() << ExpectedVariable;
  3510. }
  3511. static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
  3512. const AttributeList &Attr) {
  3513. ValueDecl *vd = cast<ValueDecl>(D);
  3514. QualType type = vd->getType();
  3515. if (!type->isDependentType() &&
  3516. !type->isObjCLifetimeType()) {
  3517. S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
  3518. << type;
  3519. return;
  3520. }
  3521. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  3522. // If we have no lifetime yet, check the lifetime we're presumably
  3523. // going to infer.
  3524. if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
  3525. lifetime = type->getObjCARCImplicitLifetime();
  3526. switch (lifetime) {
  3527. case Qualifiers::OCL_None:
  3528. assert(type->isDependentType() &&
  3529. "didn't infer lifetime for non-dependent type?");
  3530. break;
  3531. case Qualifiers::OCL_Weak: // meaningful
  3532. case Qualifiers::OCL_Strong: // meaningful
  3533. break;
  3534. case Qualifiers::OCL_ExplicitNone:
  3535. case Qualifiers::OCL_Autoreleasing:
  3536. S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
  3537. << (lifetime == Qualifiers::OCL_Autoreleasing);
  3538. break;
  3539. }
  3540. D->addAttr(::new (S.Context)
  3541. ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
  3542. Attr.getAttributeSpellingListIndex()));
  3543. }
  3544. //===----------------------------------------------------------------------===//
  3545. // Microsoft specific attribute handlers.
  3546. //===----------------------------------------------------------------------===//
  3547. static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  3548. if (!S.LangOpts.CPlusPlus) {
  3549. S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
  3550. << Attr.getName() << AttributeLangSupport::C;
  3551. return;
  3552. }
  3553. if (!isa<CXXRecordDecl>(D)) {
  3554. S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
  3555. << Attr.getName() << ExpectedClass;
  3556. return;
  3557. }
  3558. StringRef StrRef;
  3559. SourceLocation LiteralLoc;
  3560. if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
  3561. return;
  3562. // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
  3563. // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
  3564. if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
  3565. StrRef = StrRef.drop_front().drop_back();
  3566. // Validate GUID length.
  3567. if (StrRef.size() != 36) {
  3568. S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
  3569. return;
  3570. }
  3571. for (unsigned i = 0; i < 36; ++i) {
  3572. if (i == 8 || i == 13 || i == 18 || i == 23) {
  3573. if (StrRef[i] != '-') {
  3574. S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
  3575. return;
  3576. }
  3577. } else if (!isHexDigit(StrRef[i])) {
  3578. S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
  3579. return;
  3580. }
  3581. }
  3582. D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
  3583. Attr.getAttributeSpellingListIndex()));
  3584. }
  3585. static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  3586. if (!S.LangOpts.CPlusPlus) {
  3587. S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
  3588. << Attr.getName() << AttributeLangSupport::C;
  3589. return;
  3590. }
  3591. MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
  3592. D, Attr.getRange(), /*BestCase=*/true,
  3593. Attr.getAttributeSpellingListIndex(),
  3594. (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
  3595. if (IA)
  3596. D->addAttr(IA);
  3597. }
  3598. static void handleDeclspecThreadAttr(Sema &S, Decl *D,
  3599. const AttributeList &Attr) {
  3600. VarDecl *VD = cast<VarDecl>(D);
  3601. if (!S.Context.getTargetInfo().isTLSSupported()) {
  3602. S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
  3603. return;
  3604. }
  3605. if (VD->getTSCSpec() != TSCS_unspecified) {
  3606. S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
  3607. return;
  3608. }
  3609. if (VD->hasLocalStorage()) {
  3610. S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
  3611. return;
  3612. }
  3613. VD->addAttr(::new (S.Context) ThreadAttr(
  3614. Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
  3615. }
  3616. static void handleARMInterruptAttr(Sema &S, Decl *D,
  3617. const AttributeList &Attr) {
  3618. // Check the attribute arguments.
  3619. if (Attr.getNumArgs() > 1) {
  3620. S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
  3621. << Attr.getName() << 1;
  3622. return;
  3623. }
  3624. StringRef Str;
  3625. SourceLocation ArgLoc;
  3626. if (Attr.getNumArgs() == 0)
  3627. Str = "";
  3628. else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
  3629. return;
  3630. ARMInterruptAttr::InterruptType Kind;
  3631. if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
  3632. S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
  3633. << Attr.getName() << Str << ArgLoc;
  3634. return;
  3635. }
  3636. unsigned Index = Attr.getAttributeSpellingListIndex();
  3637. D->addAttr(::new (S.Context)
  3638. ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
  3639. }
  3640. static void handleMSP430InterruptAttr(Sema &S, Decl *D,
  3641. const AttributeList &Attr) {
  3642. if (!checkAttributeNumArgs(S, Attr, 1))
  3643. return;
  3644. if (!Attr.isArgExpr(0)) {
  3645. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
  3646. << AANT_ArgumentIntegerConstant;
  3647. return;
  3648. }
  3649. // FIXME: Check for decl - it should be void ()(void).
  3650. Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
  3651. llvm::APSInt NumParams(32);
  3652. if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
  3653. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  3654. << Attr.getName() << AANT_ArgumentIntegerConstant
  3655. << NumParamsExpr->getSourceRange();
  3656. return;
  3657. }
  3658. unsigned Num = NumParams.getLimitedValue(255);
  3659. if ((Num & 1) || Num > 30) {
  3660. S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
  3661. << Attr.getName() << (int)NumParams.getSExtValue()
  3662. << NumParamsExpr->getSourceRange();
  3663. return;
  3664. }
  3665. D->addAttr(::new (S.Context)
  3666. MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
  3667. Attr.getAttributeSpellingListIndex()));
  3668. D->addAttr(UsedAttr::CreateImplicit(S.Context));
  3669. }
  3670. static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  3671. // Dispatch the interrupt attribute based on the current target.
  3672. if (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::msp430)
  3673. handleMSP430InterruptAttr(S, D, Attr);
  3674. else
  3675. handleARMInterruptAttr(S, D, Attr);
  3676. }
  3677. static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
  3678. const AttributeList &Attr) {
  3679. uint32_t NumRegs;
  3680. Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
  3681. if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
  3682. return;
  3683. D->addAttr(::new (S.Context)
  3684. AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context,
  3685. NumRegs,
  3686. Attr.getAttributeSpellingListIndex()));
  3687. }
  3688. static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
  3689. const AttributeList &Attr) {
  3690. uint32_t NumRegs;
  3691. Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
  3692. if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
  3693. return;
  3694. D->addAttr(::new (S.Context)
  3695. AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context,
  3696. NumRegs,
  3697. Attr.getAttributeSpellingListIndex()));
  3698. }
  3699. static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
  3700. const AttributeList& Attr) {
  3701. // If we try to apply it to a function pointer, don't warn, but don't
  3702. // do anything, either. It doesn't matter anyway, because there's nothing
  3703. // special about calling a force_align_arg_pointer function.
  3704. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  3705. if (VD && VD->getType()->isFunctionPointerType())
  3706. return;
  3707. // Also don't warn on function pointer typedefs.
  3708. TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
  3709. if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
  3710. TD->getUnderlyingType()->isFunctionType()))
  3711. return;
  3712. // Attribute can only be applied to function types.
  3713. if (!isa<FunctionDecl>(D)) {
  3714. S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
  3715. << Attr.getName() << /* function */0;
  3716. return;
  3717. }
  3718. D->addAttr(::new (S.Context)
  3719. X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
  3720. Attr.getAttributeSpellingListIndex()));
  3721. }
  3722. DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
  3723. unsigned AttrSpellingListIndex) {
  3724. if (D->hasAttr<DLLExportAttr>()) {
  3725. Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
  3726. return nullptr;
  3727. }
  3728. if (D->hasAttr<DLLImportAttr>())
  3729. return nullptr;
  3730. return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
  3731. }
  3732. DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
  3733. unsigned AttrSpellingListIndex) {
  3734. if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
  3735. Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
  3736. D->dropAttr<DLLImportAttr>();
  3737. }
  3738. if (D->hasAttr<DLLExportAttr>())
  3739. return nullptr;
  3740. return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
  3741. }
  3742. static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
  3743. if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
  3744. S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  3745. S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
  3746. << A.getName();
  3747. return;
  3748. }
  3749. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  3750. if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
  3751. !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  3752. // MinGW doesn't allow dllimport on inline functions.
  3753. S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
  3754. << A.getName();
  3755. return;
  3756. }
  3757. }
  3758. unsigned Index = A.getAttributeSpellingListIndex();
  3759. Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
  3760. ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
  3761. : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
  3762. if (NewAttr)
  3763. D->addAttr(NewAttr);
  3764. }
  3765. MSInheritanceAttr *
  3766. Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
  3767. unsigned AttrSpellingListIndex,
  3768. MSInheritanceAttr::Spelling SemanticSpelling) {
  3769. if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
  3770. if (IA->getSemanticSpelling() == SemanticSpelling)
  3771. return nullptr;
  3772. Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
  3773. << 1 /*previous declaration*/;
  3774. Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
  3775. D->dropAttr<MSInheritanceAttr>();
  3776. }
  3777. CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
  3778. if (RD->hasDefinition()) {
  3779. if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
  3780. SemanticSpelling)) {
  3781. return nullptr;
  3782. }
  3783. } else {
  3784. if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
  3785. Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
  3786. << 1 /*partial specialization*/;
  3787. return nullptr;
  3788. }
  3789. if (RD->getDescribedClassTemplate()) {
  3790. Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
  3791. << 0 /*primary template*/;
  3792. return nullptr;
  3793. }
  3794. }
  3795. return ::new (Context)
  3796. MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
  3797. }
  3798. static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  3799. // The capability attributes take a single string parameter for the name of
  3800. // the capability they represent. The lockable attribute does not take any
  3801. // parameters. However, semantically, both attributes represent the same
  3802. // concept, and so they use the same semantic attribute. Eventually, the
  3803. // lockable attribute will be removed.
  3804. //
  3805. // For backward compatibility, any capability which has no specified string
  3806. // literal will be considered a "mutex."
  3807. StringRef N("mutex");
  3808. SourceLocation LiteralLoc;
  3809. if (Attr.getKind() == AttributeList::AT_Capability &&
  3810. !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
  3811. return;
  3812. // Currently, there are only two names allowed for a capability: role and
  3813. // mutex (case insensitive). Diagnose other capability names.
  3814. if (!N.equals_lower("mutex") && !N.equals_lower("role"))
  3815. S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
  3816. D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
  3817. Attr.getAttributeSpellingListIndex()));
  3818. }
  3819. static void handleAssertCapabilityAttr(Sema &S, Decl *D,
  3820. const AttributeList &Attr) {
  3821. D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
  3822. Attr.getArgAsExpr(0),
  3823. Attr.getAttributeSpellingListIndex()));
  3824. }
  3825. static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
  3826. const AttributeList &Attr) {
  3827. SmallVector<Expr*, 1> Args;
  3828. if (!checkLockFunAttrCommon(S, D, Attr, Args))
  3829. return;
  3830. D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
  3831. S.Context,
  3832. Args.data(), Args.size(),
  3833. Attr.getAttributeSpellingListIndex()));
  3834. }
  3835. static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
  3836. const AttributeList &Attr) {
  3837. SmallVector<Expr*, 2> Args;
  3838. if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
  3839. return;
  3840. D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
  3841. S.Context,
  3842. Attr.getArgAsExpr(0),
  3843. Args.data(),
  3844. Args.size(),
  3845. Attr.getAttributeSpellingListIndex()));
  3846. }
  3847. static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
  3848. const AttributeList &Attr) {
  3849. // Check that all arguments are lockable objects.
  3850. SmallVector<Expr *, 1> Args;
  3851. checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
  3852. D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
  3853. Attr.getRange(), S.Context, Args.data(), Args.size(),
  3854. Attr.getAttributeSpellingListIndex()));
  3855. }
  3856. static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
  3857. const AttributeList &Attr) {
  3858. if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
  3859. return;
  3860. // check that all arguments are lockable objects
  3861. SmallVector<Expr*, 1> Args;
  3862. checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
  3863. if (Args.empty())
  3864. return;
  3865. RequiresCapabilityAttr *RCA = ::new (S.Context)
  3866. RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
  3867. Args.size(), Attr.getAttributeSpellingListIndex());
  3868. D->addAttr(RCA);
  3869. }
  3870. static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  3871. if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
  3872. if (NSD->isAnonymousNamespace()) {
  3873. S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
  3874. // Do not want to attach the attribute to the namespace because that will
  3875. // cause confusing diagnostic reports for uses of declarations within the
  3876. // namespace.
  3877. return;
  3878. }
  3879. }
  3880. if (!S.getLangOpts().CPlusPlus14)
  3881. if (Attr.isCXX11Attribute() &&
  3882. !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
  3883. S.Diag(Attr.getLoc(), diag::ext_deprecated_attr_is_a_cxx14_extension);
  3884. handleAttrWithMessage<DeprecatedAttr>(S, D, Attr);
  3885. }
  3886. static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
  3887. if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
  3888. return;
  3889. std::vector<std::string> Sanitizers;
  3890. for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
  3891. StringRef SanitizerName;
  3892. SourceLocation LiteralLoc;
  3893. if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
  3894. return;
  3895. if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
  3896. S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
  3897. Sanitizers.push_back(SanitizerName);
  3898. }
  3899. D->addAttr(::new (S.Context) NoSanitizeAttr(
  3900. Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
  3901. Attr.getAttributeSpellingListIndex()));
  3902. }
  3903. static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
  3904. const AttributeList &Attr) {
  3905. std::string SanitizerName =
  3906. llvm::StringSwitch<std::string>(Attr.getName()->getName())
  3907. .Case("no_address_safety_analysis", "address")
  3908. .Case("no_sanitize_address", "address")
  3909. .Case("no_sanitize_thread", "thread")
  3910. .Case("no_sanitize_memory", "memory");
  3911. D->addAttr(::new (S.Context)
  3912. NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
  3913. Attr.getAttributeSpellingListIndex()));
  3914. }
  3915. /// Handles semantic checking for features that are common to all attributes,
  3916. /// such as checking whether a parameter was properly specified, or the correct
  3917. /// number of arguments were passed, etc.
  3918. static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
  3919. const AttributeList &Attr) {
  3920. // Several attributes carry different semantics than the parsing requires, so
  3921. // those are opted out of the common handling.
  3922. //
  3923. // We also bail on unknown and ignored attributes because those are handled
  3924. // as part of the target-specific handling logic.
  3925. if (Attr.hasCustomParsing() ||
  3926. Attr.getKind() == AttributeList::UnknownAttribute)
  3927. return false;
  3928. // Check whether the attribute requires specific language extensions to be
  3929. // enabled.
  3930. if (!Attr.diagnoseLangOpts(S))
  3931. return true;
  3932. if (Attr.getMinArgs() == Attr.getMaxArgs()) {
  3933. // If there are no optional arguments, then checking for the argument count
  3934. // is trivial.
  3935. if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
  3936. return true;
  3937. } else {
  3938. // There are optional arguments, so checking is slightly more involved.
  3939. if (Attr.getMinArgs() &&
  3940. !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
  3941. return true;
  3942. else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
  3943. !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
  3944. return true;
  3945. }
  3946. // Check whether the attribute appertains to the given subject.
  3947. if (!Attr.diagnoseAppertainsTo(S, D))
  3948. return true;
  3949. return false;
  3950. }
  3951. //===----------------------------------------------------------------------===//
  3952. // Top Level Sema Entry Points
  3953. //===----------------------------------------------------------------------===//
  3954. /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
  3955. /// the attribute applies to decls. If the attribute is a type attribute, just
  3956. /// silently ignore it if a GNU attribute.
  3957. static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
  3958. const AttributeList &Attr,
  3959. bool IncludeCXX11Attributes) {
  3960. if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
  3961. return;
  3962. // Ignore C++11 attributes on declarator chunks: they appertain to the type
  3963. // instead.
  3964. if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
  3965. return;
  3966. // Unknown attributes are automatically warned on. Target-specific attributes
  3967. // which do not apply to the current target architecture are treated as
  3968. // though they were unknown attributes.
  3969. if (Attr.getKind() == AttributeList::UnknownAttribute ||
  3970. !Attr.existsInTarget(S.Context.getTargetInfo().getTriple())) {
  3971. S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
  3972. ? diag::warn_unhandled_ms_attribute_ignored
  3973. : diag::warn_unknown_attribute_ignored)
  3974. << Attr.getName();
  3975. return;
  3976. }
  3977. if (handleCommonAttributeFeatures(S, scope, D, Attr))
  3978. return;
  3979. switch (Attr.getKind()) {
  3980. default:
  3981. // HLSL Change Starts
  3982. if (S.LangOpts.HLSL)
  3983. {
  3984. bool Handled = false;
  3985. hlsl::HandleDeclAttributeForHLSL(S, D, Attr, Handled);
  3986. if (Handled) break;
  3987. }
  3988. // HLSL Change Ends
  3989. // Type attributes are handled elsewhere; silently move on.
  3990. assert(Attr.isTypeAttr() && "Non-type attribute not handled");
  3991. break;
  3992. case AttributeList::AT_Interrupt:
  3993. handleInterruptAttr(S, D, Attr);
  3994. break;
  3995. case AttributeList::AT_X86ForceAlignArgPointer:
  3996. handleX86ForceAlignArgPointerAttr(S, D, Attr);
  3997. break;
  3998. case AttributeList::AT_DLLExport:
  3999. case AttributeList::AT_DLLImport:
  4000. handleDLLAttr(S, D, Attr);
  4001. break;
  4002. case AttributeList::AT_Mips16:
  4003. handleSimpleAttribute<Mips16Attr>(S, D, Attr);
  4004. break;
  4005. case AttributeList::AT_NoMips16:
  4006. handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
  4007. break;
  4008. case AttributeList::AT_AMDGPUNumVGPR:
  4009. handleAMDGPUNumVGPRAttr(S, D, Attr);
  4010. break;
  4011. case AttributeList::AT_AMDGPUNumSGPR:
  4012. handleAMDGPUNumSGPRAttr(S, D, Attr);
  4013. break;
  4014. case AttributeList::AT_IBAction:
  4015. handleSimpleAttribute<IBActionAttr>(S, D, Attr);
  4016. break;
  4017. case AttributeList::AT_IBOutlet:
  4018. handleIBOutlet(S, D, Attr);
  4019. break;
  4020. case AttributeList::AT_IBOutletCollection:
  4021. handleIBOutletCollection(S, D, Attr);
  4022. break;
  4023. case AttributeList::AT_Alias:
  4024. handleAliasAttr(S, D, Attr);
  4025. break;
  4026. case AttributeList::AT_Aligned:
  4027. handleAlignedAttr(S, D, Attr);
  4028. break;
  4029. case AttributeList::AT_AlignValue:
  4030. handleAlignValueAttr(S, D, Attr);
  4031. break;
  4032. case AttributeList::AT_AlwaysInline:
  4033. handleAlwaysInlineAttr(S, D, Attr);
  4034. break;
  4035. case AttributeList::AT_AnalyzerNoReturn:
  4036. handleAnalyzerNoReturnAttr(S, D, Attr);
  4037. break;
  4038. case AttributeList::AT_TLSModel:
  4039. handleTLSModelAttr(S, D, Attr);
  4040. break;
  4041. case AttributeList::AT_Annotate:
  4042. handleAnnotateAttr(S, D, Attr);
  4043. break;
  4044. case AttributeList::AT_Availability:
  4045. handleAvailabilityAttr(S, D, Attr);
  4046. break;
  4047. case AttributeList::AT_CarriesDependency:
  4048. handleDependencyAttr(S, scope, D, Attr);
  4049. break;
  4050. case AttributeList::AT_Common:
  4051. handleCommonAttr(S, D, Attr);
  4052. break;
  4053. case AttributeList::AT_CUDAConstant:
  4054. handleSimpleAttribute<CUDAConstantAttr>(S, D, Attr);
  4055. break;
  4056. case AttributeList::AT_Constructor:
  4057. handleConstructorAttr(S, D, Attr);
  4058. break;
  4059. case AttributeList::AT_CXX11NoReturn:
  4060. handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
  4061. break;
  4062. case AttributeList::AT_Deprecated:
  4063. handleDeprecatedAttr(S, D, Attr);
  4064. break;
  4065. case AttributeList::AT_Destructor:
  4066. handleDestructorAttr(S, D, Attr);
  4067. break;
  4068. case AttributeList::AT_EnableIf:
  4069. handleEnableIfAttr(S, D, Attr);
  4070. break;
  4071. case AttributeList::AT_ExtVectorType:
  4072. handleExtVectorTypeAttr(S, scope, D, Attr);
  4073. break;
  4074. case AttributeList::AT_MinSize:
  4075. handleMinSizeAttr(S, D, Attr);
  4076. break;
  4077. case AttributeList::AT_OptimizeNone:
  4078. handleOptimizeNoneAttr(S, D, Attr);
  4079. break;
  4080. case AttributeList::AT_FlagEnum:
  4081. handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
  4082. break;
  4083. case AttributeList::AT_Flatten:
  4084. handleSimpleAttribute<FlattenAttr>(S, D, Attr);
  4085. break;
  4086. case AttributeList::AT_Format:
  4087. handleFormatAttr(S, D, Attr);
  4088. break;
  4089. case AttributeList::AT_FormatArg:
  4090. handleFormatArgAttr(S, D, Attr);
  4091. break;
  4092. case AttributeList::AT_CUDAGlobal:
  4093. handleGlobalAttr(S, D, Attr);
  4094. break;
  4095. case AttributeList::AT_CUDADevice:
  4096. handleSimpleAttribute<CUDADeviceAttr>(S, D, Attr);
  4097. break;
  4098. case AttributeList::AT_CUDAHost:
  4099. handleSimpleAttribute<CUDAHostAttr>(S, D, Attr);
  4100. break;
  4101. case AttributeList::AT_GNUInline:
  4102. handleGNUInlineAttr(S, D, Attr);
  4103. break;
  4104. case AttributeList::AT_CUDALaunchBounds:
  4105. handleLaunchBoundsAttr(S, D, Attr);
  4106. break;
  4107. case AttributeList::AT_Restrict:
  4108. handleRestrictAttr(S, D, Attr);
  4109. break;
  4110. case AttributeList::AT_MayAlias:
  4111. handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
  4112. break;
  4113. case AttributeList::AT_Mode:
  4114. handleModeAttr(S, D, Attr);
  4115. break;
  4116. case AttributeList::AT_NoCommon:
  4117. handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
  4118. break;
  4119. case AttributeList::AT_NoSplitStack:
  4120. handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
  4121. break;
  4122. case AttributeList::AT_NonNull:
  4123. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
  4124. handleNonNullAttrParameter(S, PVD, Attr);
  4125. else
  4126. handleNonNullAttr(S, D, Attr);
  4127. break;
  4128. case AttributeList::AT_ReturnsNonNull:
  4129. handleReturnsNonNullAttr(S, D, Attr);
  4130. break;
  4131. case AttributeList::AT_AssumeAligned:
  4132. handleAssumeAlignedAttr(S, D, Attr);
  4133. break;
  4134. case AttributeList::AT_Overloadable:
  4135. handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
  4136. break;
  4137. case AttributeList::AT_Ownership:
  4138. handleOwnershipAttr(S, D, Attr);
  4139. break;
  4140. case AttributeList::AT_Cold:
  4141. handleColdAttr(S, D, Attr);
  4142. break;
  4143. case AttributeList::AT_Hot:
  4144. handleHotAttr(S, D, Attr);
  4145. break;
  4146. case AttributeList::AT_Naked:
  4147. handleSimpleAttribute<NakedAttr>(S, D, Attr);
  4148. break;
  4149. case AttributeList::AT_NoReturn:
  4150. handleNoReturnAttr(S, D, Attr);
  4151. break;
  4152. case AttributeList::AT_NoThrow:
  4153. handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
  4154. break;
  4155. case AttributeList::AT_CUDAShared:
  4156. handleSimpleAttribute<CUDASharedAttr>(S, D, Attr);
  4157. break;
  4158. case AttributeList::AT_VecReturn:
  4159. handleVecReturnAttr(S, D, Attr);
  4160. break;
  4161. case AttributeList::AT_ObjCOwnership:
  4162. handleObjCOwnershipAttr(S, D, Attr);
  4163. break;
  4164. case AttributeList::AT_ObjCPreciseLifetime:
  4165. handleObjCPreciseLifetimeAttr(S, D, Attr);
  4166. break;
  4167. case AttributeList::AT_ObjCReturnsInnerPointer:
  4168. handleObjCReturnsInnerPointerAttr(S, D, Attr);
  4169. break;
  4170. case AttributeList::AT_ObjCRequiresSuper:
  4171. handleObjCRequiresSuperAttr(S, D, Attr);
  4172. break;
  4173. case AttributeList::AT_ObjCBridge:
  4174. handleObjCBridgeAttr(S, scope, D, Attr);
  4175. break;
  4176. case AttributeList::AT_ObjCBridgeMutable:
  4177. handleObjCBridgeMutableAttr(S, scope, D, Attr);
  4178. break;
  4179. case AttributeList::AT_ObjCBridgeRelated:
  4180. handleObjCBridgeRelatedAttr(S, scope, D, Attr);
  4181. break;
  4182. case AttributeList::AT_ObjCDesignatedInitializer:
  4183. handleObjCDesignatedInitializer(S, D, Attr);
  4184. break;
  4185. case AttributeList::AT_ObjCRuntimeName:
  4186. handleObjCRuntimeName(S, D, Attr);
  4187. break;
  4188. case AttributeList::AT_ObjCBoxable:
  4189. handleObjCBoxable(S, D, Attr);
  4190. break;
  4191. case AttributeList::AT_CFAuditedTransfer:
  4192. handleCFAuditedTransferAttr(S, D, Attr);
  4193. break;
  4194. case AttributeList::AT_CFUnknownTransfer:
  4195. handleCFUnknownTransferAttr(S, D, Attr);
  4196. break;
  4197. case AttributeList::AT_CFConsumed:
  4198. case AttributeList::AT_NSConsumed:
  4199. handleNSConsumedAttr(S, D, Attr);
  4200. break;
  4201. case AttributeList::AT_NSConsumesSelf:
  4202. handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
  4203. break;
  4204. case AttributeList::AT_NSReturnsAutoreleased:
  4205. case AttributeList::AT_NSReturnsNotRetained:
  4206. case AttributeList::AT_CFReturnsNotRetained:
  4207. case AttributeList::AT_NSReturnsRetained:
  4208. case AttributeList::AT_CFReturnsRetained:
  4209. handleNSReturnsRetainedAttr(S, D, Attr);
  4210. break;
  4211. case AttributeList::AT_WorkGroupSizeHint:
  4212. handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
  4213. break;
  4214. case AttributeList::AT_ReqdWorkGroupSize:
  4215. handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
  4216. break;
  4217. case AttributeList::AT_VecTypeHint:
  4218. handleVecTypeHint(S, D, Attr);
  4219. break;
  4220. case AttributeList::AT_InitPriority:
  4221. handleInitPriorityAttr(S, D, Attr);
  4222. break;
  4223. case AttributeList::AT_Packed:
  4224. handlePackedAttr(S, D, Attr);
  4225. break;
  4226. case AttributeList::AT_Section:
  4227. handleSectionAttr(S, D, Attr);
  4228. break;
  4229. case AttributeList::AT_Target:
  4230. handleTargetAttr(S, D, Attr);
  4231. break;
  4232. case AttributeList::AT_Unavailable:
  4233. handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
  4234. break;
  4235. case AttributeList::AT_ArcWeakrefUnavailable:
  4236. handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
  4237. break;
  4238. case AttributeList::AT_ObjCRootClass:
  4239. handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
  4240. break;
  4241. case AttributeList::AT_ObjCExplicitProtocolImpl:
  4242. handleObjCSuppresProtocolAttr(S, D, Attr);
  4243. break;
  4244. case AttributeList::AT_ObjCRequiresPropertyDefs:
  4245. handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
  4246. break;
  4247. case AttributeList::AT_Unused:
  4248. handleSimpleAttribute<UnusedAttr>(S, D, Attr);
  4249. break;
  4250. case AttributeList::AT_ReturnsTwice:
  4251. handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
  4252. break;
  4253. case AttributeList::AT_Used:
  4254. handleUsedAttr(S, D, Attr);
  4255. break;
  4256. case AttributeList::AT_Visibility:
  4257. handleVisibilityAttr(S, D, Attr, false);
  4258. break;
  4259. case AttributeList::AT_TypeVisibility:
  4260. handleVisibilityAttr(S, D, Attr, true);
  4261. break;
  4262. case AttributeList::AT_WarnUnused:
  4263. handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
  4264. break;
  4265. case AttributeList::AT_WarnUnusedResult:
  4266. handleWarnUnusedResult(S, D, Attr);
  4267. break;
  4268. case AttributeList::AT_Weak:
  4269. handleSimpleAttribute<WeakAttr>(S, D, Attr);
  4270. break;
  4271. case AttributeList::AT_WeakRef:
  4272. handleWeakRefAttr(S, D, Attr);
  4273. break;
  4274. case AttributeList::AT_WeakImport:
  4275. handleWeakImportAttr(S, D, Attr);
  4276. break;
  4277. case AttributeList::AT_TransparentUnion:
  4278. handleTransparentUnionAttr(S, D, Attr);
  4279. break;
  4280. case AttributeList::AT_ObjCException:
  4281. handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
  4282. break;
  4283. case AttributeList::AT_ObjCMethodFamily:
  4284. handleObjCMethodFamilyAttr(S, D, Attr);
  4285. break;
  4286. case AttributeList::AT_ObjCNSObject:
  4287. handleObjCNSObject(S, D, Attr);
  4288. break;
  4289. case AttributeList::AT_ObjCIndependentClass:
  4290. handleObjCIndependentClass(S, D, Attr);
  4291. break;
  4292. case AttributeList::AT_Blocks:
  4293. handleBlocksAttr(S, D, Attr);
  4294. break;
  4295. case AttributeList::AT_Sentinel:
  4296. handleSentinelAttr(S, D, Attr);
  4297. break;
  4298. case AttributeList::AT_Const:
  4299. handleSimpleAttribute<ConstAttr>(S, D, Attr);
  4300. break;
  4301. case AttributeList::AT_Pure:
  4302. handleSimpleAttribute<PureAttr>(S, D, Attr);
  4303. break;
  4304. case AttributeList::AT_Cleanup:
  4305. handleCleanupAttr(S, D, Attr);
  4306. break;
  4307. case AttributeList::AT_NoDebug:
  4308. handleNoDebugAttr(S, D, Attr);
  4309. break;
  4310. case AttributeList::AT_NoDuplicate:
  4311. handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
  4312. break;
  4313. case AttributeList::AT_NoInline:
  4314. handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
  4315. break;
  4316. case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
  4317. handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
  4318. break;
  4319. case AttributeList::AT_StdCall:
  4320. case AttributeList::AT_CDecl:
  4321. case AttributeList::AT_FastCall:
  4322. case AttributeList::AT_ThisCall:
  4323. case AttributeList::AT_Pascal:
  4324. case AttributeList::AT_VectorCall:
  4325. case AttributeList::AT_MSABI:
  4326. case AttributeList::AT_SysVABI:
  4327. case AttributeList::AT_Pcs:
  4328. case AttributeList::AT_IntelOclBicc:
  4329. handleCallConvAttr(S, D, Attr);
  4330. break;
  4331. case AttributeList::AT_OpenCLKernel:
  4332. handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
  4333. break;
  4334. case AttributeList::AT_OpenCLImageAccess:
  4335. handleSimpleAttribute<OpenCLImageAccessAttr>(S, D, Attr);
  4336. break;
  4337. // Microsoft attributes:
  4338. case AttributeList::AT_MSNoVTable:
  4339. handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
  4340. break;
  4341. case AttributeList::AT_MSStruct:
  4342. handleSimpleAttribute<MSStructAttr>(S, D, Attr);
  4343. break;
  4344. case AttributeList::AT_Uuid:
  4345. handleUuidAttr(S, D, Attr);
  4346. break;
  4347. case AttributeList::AT_MSInheritance:
  4348. handleMSInheritanceAttr(S, D, Attr);
  4349. break;
  4350. case AttributeList::AT_SelectAny:
  4351. handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
  4352. break;
  4353. case AttributeList::AT_Thread:
  4354. handleDeclspecThreadAttr(S, D, Attr);
  4355. break;
  4356. // Thread safety attributes:
  4357. case AttributeList::AT_AssertExclusiveLock:
  4358. handleAssertExclusiveLockAttr(S, D, Attr);
  4359. break;
  4360. case AttributeList::AT_AssertSharedLock:
  4361. handleAssertSharedLockAttr(S, D, Attr);
  4362. break;
  4363. case AttributeList::AT_GuardedVar:
  4364. handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
  4365. break;
  4366. case AttributeList::AT_PtGuardedVar:
  4367. handlePtGuardedVarAttr(S, D, Attr);
  4368. break;
  4369. case AttributeList::AT_ScopedLockable:
  4370. handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
  4371. break;
  4372. case AttributeList::AT_NoSanitize:
  4373. handleNoSanitizeAttr(S, D, Attr);
  4374. break;
  4375. case AttributeList::AT_NoSanitizeSpecific:
  4376. handleNoSanitizeSpecificAttr(S, D, Attr);
  4377. break;
  4378. case AttributeList::AT_NoThreadSafetyAnalysis:
  4379. handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
  4380. break;
  4381. case AttributeList::AT_GuardedBy:
  4382. handleGuardedByAttr(S, D, Attr);
  4383. break;
  4384. case AttributeList::AT_PtGuardedBy:
  4385. handlePtGuardedByAttr(S, D, Attr);
  4386. break;
  4387. case AttributeList::AT_ExclusiveTrylockFunction:
  4388. handleExclusiveTrylockFunctionAttr(S, D, Attr);
  4389. break;
  4390. case AttributeList::AT_LockReturned:
  4391. handleLockReturnedAttr(S, D, Attr);
  4392. break;
  4393. case AttributeList::AT_LocksExcluded:
  4394. handleLocksExcludedAttr(S, D, Attr);
  4395. break;
  4396. case AttributeList::AT_SharedTrylockFunction:
  4397. handleSharedTrylockFunctionAttr(S, D, Attr);
  4398. break;
  4399. case AttributeList::AT_AcquiredBefore:
  4400. handleAcquiredBeforeAttr(S, D, Attr);
  4401. break;
  4402. case AttributeList::AT_AcquiredAfter:
  4403. handleAcquiredAfterAttr(S, D, Attr);
  4404. break;
  4405. // Capability analysis attributes.
  4406. case AttributeList::AT_Capability:
  4407. case AttributeList::AT_Lockable:
  4408. handleCapabilityAttr(S, D, Attr);
  4409. break;
  4410. case AttributeList::AT_RequiresCapability:
  4411. handleRequiresCapabilityAttr(S, D, Attr);
  4412. break;
  4413. case AttributeList::AT_AssertCapability:
  4414. handleAssertCapabilityAttr(S, D, Attr);
  4415. break;
  4416. case AttributeList::AT_AcquireCapability:
  4417. handleAcquireCapabilityAttr(S, D, Attr);
  4418. break;
  4419. case AttributeList::AT_ReleaseCapability:
  4420. handleReleaseCapabilityAttr(S, D, Attr);
  4421. break;
  4422. case AttributeList::AT_TryAcquireCapability:
  4423. handleTryAcquireCapabilityAttr(S, D, Attr);
  4424. break;
  4425. // Consumed analysis attributes.
  4426. case AttributeList::AT_Consumable:
  4427. handleConsumableAttr(S, D, Attr);
  4428. break;
  4429. case AttributeList::AT_ConsumableAutoCast:
  4430. handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
  4431. break;
  4432. case AttributeList::AT_ConsumableSetOnRead:
  4433. handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
  4434. break;
  4435. case AttributeList::AT_CallableWhen:
  4436. handleCallableWhenAttr(S, D, Attr);
  4437. break;
  4438. case AttributeList::AT_ParamTypestate:
  4439. handleParamTypestateAttr(S, D, Attr);
  4440. break;
  4441. case AttributeList::AT_ReturnTypestate:
  4442. handleReturnTypestateAttr(S, D, Attr);
  4443. break;
  4444. case AttributeList::AT_SetTypestate:
  4445. handleSetTypestateAttr(S, D, Attr);
  4446. break;
  4447. case AttributeList::AT_TestTypestate:
  4448. handleTestTypestateAttr(S, D, Attr);
  4449. break;
  4450. // Type safety attributes.
  4451. case AttributeList::AT_ArgumentWithTypeTag:
  4452. handleArgumentWithTypeTagAttr(S, D, Attr);
  4453. break;
  4454. case AttributeList::AT_TypeTagForDatatype:
  4455. handleTypeTagForDatatypeAttr(S, D, Attr);
  4456. break;
  4457. }
  4458. }
  4459. /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
  4460. /// attribute list to the specified decl, ignoring any type attributes.
  4461. void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
  4462. const AttributeList *AttrList,
  4463. bool IncludeCXX11Attributes) {
  4464. for (const AttributeList* l = AttrList; l; l = l->getNext())
  4465. ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
  4466. // FIXME: We should be able to handle these cases in TableGen.
  4467. // GCC accepts
  4468. // static int a9 __attribute__((weakref));
  4469. // but that looks really pointless. We reject it.
  4470. if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
  4471. Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
  4472. << cast<NamedDecl>(D);
  4473. D->dropAttr<WeakRefAttr>();
  4474. return;
  4475. }
  4476. // FIXME: We should be able to handle this in TableGen as well. It would be
  4477. // good to have a way to specify "these attributes must appear as a group",
  4478. // for these. Additionally, it would be good to have a way to specify "these
  4479. // attribute must never appear as a group" for attributes like cold and hot.
  4480. if (!D->hasAttr<OpenCLKernelAttr>()) {
  4481. // These attributes cannot be applied to a non-kernel function.
  4482. if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
  4483. // FIXME: This emits a different error message than
  4484. // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
  4485. Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
  4486. D->setInvalidDecl();
  4487. } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
  4488. Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
  4489. D->setInvalidDecl();
  4490. } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
  4491. Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
  4492. D->setInvalidDecl();
  4493. } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
  4494. Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  4495. << A << ExpectedKernelFunction;
  4496. D->setInvalidDecl();
  4497. } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
  4498. Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  4499. << A << ExpectedKernelFunction;
  4500. D->setInvalidDecl();
  4501. }
  4502. }
  4503. }
  4504. // Annotation attributes are the only attributes allowed after an access
  4505. // specifier.
  4506. bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
  4507. const AttributeList *AttrList) {
  4508. for (const AttributeList* l = AttrList; l; l = l->getNext()) {
  4509. if (l->getKind() == AttributeList::AT_Annotate) {
  4510. ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
  4511. } else {
  4512. Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
  4513. return true;
  4514. }
  4515. }
  4516. return false;
  4517. }
  4518. /// checkUnusedDeclAttributes - Check a list of attributes to see if it
  4519. /// contains any decl attributes that we should warn about.
  4520. static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
  4521. for ( ; A; A = A->getNext()) {
  4522. // Only warn if the attribute is an unignored, non-type attribute.
  4523. if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
  4524. if (A->getKind() == AttributeList::IgnoredAttribute) continue;
  4525. if (A->getKind() == AttributeList::UnknownAttribute) {
  4526. S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
  4527. << A->getName() << A->getRange();
  4528. } else {
  4529. S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
  4530. << A->getName() << A->getRange();
  4531. }
  4532. }
  4533. }
  4534. /// checkUnusedDeclAttributes - Given a declarator which is not being
  4535. /// used to build a declaration, complain about any decl attributes
  4536. /// which might be lying around on it.
  4537. void Sema::checkUnusedDeclAttributes(Declarator &D) {
  4538. ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
  4539. ::checkUnusedDeclAttributes(*this, D.getAttributes());
  4540. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
  4541. ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
  4542. }
  4543. /// DeclClonePragmaWeak - clone existing decl (maybe definition),
  4544. /// \#pragma weak needs a non-definition decl and source may not have one.
  4545. NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
  4546. SourceLocation Loc) {
  4547. assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
  4548. NamedDecl *NewD = nullptr;
  4549. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  4550. FunctionDecl *NewFD;
  4551. // FIXME: Missing call to CheckFunctionDeclaration().
  4552. // FIXME: Mangling?
  4553. // FIXME: Is the qualifier info correct?
  4554. // FIXME: Is the DeclContext correct?
  4555. NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
  4556. Loc, Loc, DeclarationName(II),
  4557. FD->getType(), FD->getTypeSourceInfo(),
  4558. SC_None, false/*isInlineSpecified*/,
  4559. FD->hasPrototype(),
  4560. false/*isConstexprSpecified*/);
  4561. NewD = NewFD;
  4562. if (FD->getQualifier())
  4563. NewFD->setQualifierInfo(FD->getQualifierLoc());
  4564. // Fake up parameter variables; they are declared as if this were
  4565. // a typedef.
  4566. QualType FDTy = FD->getType();
  4567. if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
  4568. SmallVector<ParmVarDecl*, 16> Params;
  4569. for (const auto &AI : FT->param_types()) {
  4570. ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
  4571. Param->setScopeInfo(0, Params.size());
  4572. Params.push_back(Param);
  4573. }
  4574. NewFD->setParams(Params);
  4575. }
  4576. } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
  4577. NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
  4578. VD->getInnerLocStart(), VD->getLocation(), II,
  4579. VD->getType(), VD->getTypeSourceInfo(),
  4580. VD->getStorageClass());
  4581. if (VD->getQualifier()) {
  4582. VarDecl *NewVD = cast<VarDecl>(NewD);
  4583. NewVD->setQualifierInfo(VD->getQualifierLoc());
  4584. }
  4585. }
  4586. return NewD;
  4587. }
  4588. /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
  4589. /// applied to it, possibly with an alias.
  4590. void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
  4591. if (W.getUsed()) return; // only do this once
  4592. W.setUsed(true);
  4593. if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
  4594. IdentifierInfo *NDId = ND->getIdentifier();
  4595. NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
  4596. NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
  4597. W.getLocation()));
  4598. NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
  4599. WeakTopLevelDecl.push_back(NewD);
  4600. // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
  4601. // to insert Decl at TU scope, sorry.
  4602. DeclContext *SavedContext = CurContext;
  4603. CurContext = Context.getTranslationUnitDecl();
  4604. NewD->setDeclContext(CurContext);
  4605. NewD->setLexicalDeclContext(CurContext);
  4606. PushOnScopeChains(NewD, S);
  4607. CurContext = SavedContext;
  4608. } else { // just add weak to existing
  4609. ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
  4610. }
  4611. }
  4612. void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
  4613. // It's valid to "forward-declare" #pragma weak, in which case we
  4614. // have to do this.
  4615. LoadExternalWeakUndeclaredIdentifiers();
  4616. if (!WeakUndeclaredIdentifiers.empty()) {
  4617. NamedDecl *ND = nullptr;
  4618. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  4619. if (VD->isExternC())
  4620. ND = VD;
  4621. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  4622. if (FD->isExternC())
  4623. ND = FD;
  4624. if (ND) {
  4625. if (IdentifierInfo *Id = ND->getIdentifier()) {
  4626. auto I = WeakUndeclaredIdentifiers.find(Id);
  4627. if (I != WeakUndeclaredIdentifiers.end()) {
  4628. WeakInfo W = I->second;
  4629. DeclApplyPragmaWeak(S, ND, W);
  4630. WeakUndeclaredIdentifiers[Id] = W;
  4631. }
  4632. }
  4633. }
  4634. }
  4635. }
  4636. /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
  4637. /// it, apply them to D. This is a bit tricky because PD can have attributes
  4638. /// specified in many different places, and we need to find and apply them all.
  4639. void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
  4640. // Apply decl attributes from the DeclSpec if present.
  4641. if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
  4642. ProcessDeclAttributeList(S, D, Attrs);
  4643. // Walk the declarator structure, applying decl attributes that were in a type
  4644. // position to the decl itself. This handles cases like:
  4645. // int *__attr__(x)** D;
  4646. // when X is a decl attribute.
  4647. for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
  4648. if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
  4649. ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
  4650. // Finally, apply any attributes on the decl itself.
  4651. if (const AttributeList *Attrs = PD.getAttributes())
  4652. ProcessDeclAttributeList(S, D, Attrs);
  4653. // HLSL Change Starts - Get custom attributes from our declarator object and append to AST Decl object
  4654. for (std::vector<InheritableAttr*>::const_iterator
  4655. i = PD.customAttributesList.begin(),
  4656. e = PD.customAttributesList.end();
  4657. i != e; ++i) {
  4658. D->addAttr(*i);
  4659. }
  4660. // HLSL Change Ends
  4661. }
  4662. /// Is the given declaration allowed to use a forbidden type?
  4663. static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) {
  4664. // Private ivars are always okay. Unfortunately, people don't
  4665. // always properly make their ivars private, even in system headers.
  4666. // Plus we need to make fields okay, too.
  4667. // Function declarations in sys headers will be marked unavailable.
  4668. if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
  4669. !isa<FunctionDecl>(decl))
  4670. return false;
  4671. // Require it to be declared in a system header.
  4672. return S.Context.getSourceManager().isInSystemHeader(decl->getLocation());
  4673. }
  4674. /// Handle a delayed forbidden-type diagnostic.
  4675. static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
  4676. Decl *decl) {
  4677. if (decl && isForbiddenTypeAllowed(S, decl)) {
  4678. decl->addAttr(UnavailableAttr::CreateImplicit(S.Context,
  4679. "this system declaration uses an unsupported type",
  4680. diag.Loc));
  4681. return;
  4682. }
  4683. if (S.getLangOpts().ObjCAutoRefCount)
  4684. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
  4685. // FIXME: we may want to suppress diagnostics for all
  4686. // kind of forbidden type messages on unavailable functions.
  4687. if (FD->hasAttr<UnavailableAttr>() &&
  4688. diag.getForbiddenTypeDiagnostic() ==
  4689. diag::err_arc_array_param_no_ownership) {
  4690. diag.Triggered = true;
  4691. return;
  4692. }
  4693. }
  4694. S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
  4695. << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
  4696. diag.Triggered = true;
  4697. }
  4698. static bool isDeclDeprecated(Decl *D) {
  4699. do {
  4700. if (D->isDeprecated())
  4701. return true;
  4702. // A category implicitly has the availability of the interface.
  4703. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
  4704. if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
  4705. return Interface->isDeprecated();
  4706. } while ((D = cast_or_null<Decl>(D->getDeclContext())));
  4707. return false;
  4708. }
  4709. static bool isDeclUnavailable(Decl *D) {
  4710. do {
  4711. if (D->isUnavailable())
  4712. return true;
  4713. // A category implicitly has the availability of the interface.
  4714. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
  4715. if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
  4716. return Interface->isUnavailable();
  4717. } while ((D = cast_or_null<Decl>(D->getDeclContext())));
  4718. return false;
  4719. }
  4720. static void DoEmitAvailabilityWarning(Sema &S, Sema::AvailabilityDiagnostic K,
  4721. Decl *Ctx, const NamedDecl *D,
  4722. StringRef Message, SourceLocation Loc,
  4723. const ObjCInterfaceDecl *UnknownObjCClass,
  4724. const ObjCPropertyDecl *ObjCProperty,
  4725. bool ObjCPropertyAccess) {
  4726. // Diagnostics for deprecated or unavailable.
  4727. unsigned diag, diag_message, diag_fwdclass_message;
  4728. // Matches 'diag::note_property_attribute' options.
  4729. unsigned property_note_select;
  4730. // Matches diag::note_availability_specified_here.
  4731. unsigned available_here_select_kind;
  4732. // Don't warn if our current context is deprecated or unavailable.
  4733. switch (K) {
  4734. case Sema::AD_Deprecation:
  4735. if (isDeclDeprecated(Ctx) || isDeclUnavailable(Ctx))
  4736. return;
  4737. diag = !ObjCPropertyAccess ? diag::warn_deprecated
  4738. : diag::warn_property_method_deprecated;
  4739. diag_message = diag::warn_deprecated_message;
  4740. diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
  4741. property_note_select = /* deprecated */ 0;
  4742. available_here_select_kind = /* deprecated */ 2;
  4743. break;
  4744. case Sema::AD_Unavailable:
  4745. if (isDeclUnavailable(Ctx))
  4746. return;
  4747. diag = !ObjCPropertyAccess ? diag::err_unavailable
  4748. : diag::err_property_method_unavailable;
  4749. diag_message = diag::err_unavailable_message;
  4750. diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
  4751. property_note_select = /* unavailable */ 1;
  4752. available_here_select_kind = /* unavailable */ 0;
  4753. break;
  4754. case Sema::AD_Partial:
  4755. diag = diag::warn_partial_availability;
  4756. diag_message = diag::warn_partial_message;
  4757. diag_fwdclass_message = diag::warn_partial_fwdclass_message;
  4758. property_note_select = /* partial */ 2;
  4759. available_here_select_kind = /* partial */ 3;
  4760. break;
  4761. }
  4762. if (!Message.empty()) {
  4763. S.Diag(Loc, diag_message) << D << Message;
  4764. if (ObjCProperty)
  4765. S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
  4766. << ObjCProperty->getDeclName() << property_note_select;
  4767. } else if (!UnknownObjCClass) {
  4768. S.Diag(Loc, diag) << D;
  4769. if (ObjCProperty)
  4770. S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
  4771. << ObjCProperty->getDeclName() << property_note_select;
  4772. } else {
  4773. S.Diag(Loc, diag_fwdclass_message) << D;
  4774. S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
  4775. }
  4776. S.Diag(D->getLocation(), diag::note_availability_specified_here)
  4777. << D << available_here_select_kind;
  4778. if (K == Sema::AD_Partial)
  4779. S.Diag(Loc, diag::note_partial_availability_silence) << D;
  4780. }
  4781. static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
  4782. Decl *Ctx) {
  4783. assert(DD.Kind == DelayedDiagnostic::Deprecation ||
  4784. DD.Kind == DelayedDiagnostic::Unavailable);
  4785. Sema::AvailabilityDiagnostic AD = DD.Kind == DelayedDiagnostic::Deprecation
  4786. ? Sema::AD_Deprecation
  4787. : Sema::AD_Unavailable;
  4788. DD.Triggered = true;
  4789. DoEmitAvailabilityWarning(
  4790. S, AD, Ctx, DD.getDeprecationDecl(), DD.getDeprecationMessage(), DD.Loc,
  4791. DD.getUnknownObjCClass(), DD.getObjCProperty(), false);
  4792. }
  4793. void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
  4794. assert(DelayedDiagnostics.getCurrentPool());
  4795. DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
  4796. DelayedDiagnostics.popWithoutEmitting(state);
  4797. // When delaying diagnostics to run in the context of a parsed
  4798. // declaration, we only want to actually emit anything if parsing
  4799. // succeeds.
  4800. if (!decl) return;
  4801. // We emit all the active diagnostics in this pool or any of its
  4802. // parents. In general, we'll get one pool for the decl spec
  4803. // and a child pool for each declarator; in a decl group like:
  4804. // deprecated_typedef foo, *bar, baz();
  4805. // only the declarator pops will be passed decls. This is correct;
  4806. // we really do need to consider delayed diagnostics from the decl spec
  4807. // for each of the different declarations.
  4808. const DelayedDiagnosticPool *pool = &poppedPool;
  4809. do {
  4810. for (DelayedDiagnosticPool::pool_iterator
  4811. i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
  4812. // This const_cast is a bit lame. Really, Triggered should be mutable.
  4813. DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
  4814. if (diag.Triggered)
  4815. continue;
  4816. switch (diag.Kind) {
  4817. case DelayedDiagnostic::Deprecation:
  4818. case DelayedDiagnostic::Unavailable:
  4819. // Don't bother giving deprecation/unavailable diagnostics if
  4820. // the decl is invalid.
  4821. if (!decl->isInvalidDecl())
  4822. handleDelayedAvailabilityCheck(*this, diag, decl);
  4823. break;
  4824. case DelayedDiagnostic::Access:
  4825. HandleDelayedAccessCheck(diag, decl);
  4826. break;
  4827. case DelayedDiagnostic::ForbiddenType:
  4828. handleDelayedForbiddenType(*this, diag, decl);
  4829. break;
  4830. }
  4831. }
  4832. } while ((pool = pool->getParent()));
  4833. }
  4834. /// Given a set of delayed diagnostics, re-emit them as if they had
  4835. /// been delayed in the current context instead of in the given pool.
  4836. /// Essentially, this just moves them to the current pool.
  4837. void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
  4838. DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
  4839. assert(curPool && "re-emitting in undelayed context not supported");
  4840. curPool->steal(pool);
  4841. }
  4842. void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD,
  4843. NamedDecl *D, StringRef Message,
  4844. SourceLocation Loc,
  4845. const ObjCInterfaceDecl *UnknownObjCClass,
  4846. const ObjCPropertyDecl *ObjCProperty,
  4847. bool ObjCPropertyAccess) {
  4848. // Delay if we're currently parsing a declaration.
  4849. if (DelayedDiagnostics.shouldDelayDiagnostics() && AD != AD_Partial) {
  4850. DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
  4851. AD, Loc, D, UnknownObjCClass, ObjCProperty, Message,
  4852. ObjCPropertyAccess));
  4853. return;
  4854. }
  4855. Decl *Ctx = cast<Decl>(getCurLexicalContext());
  4856. DoEmitAvailabilityWarning(*this, AD, Ctx, D, Message, Loc, UnknownObjCClass,
  4857. ObjCProperty, ObjCPropertyAccess);
  4858. }