SemaChecking.cpp 678 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128
  1. //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements extra semantic analysis beyond what is enforced
  10. // by the C type system.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/APValue.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/AttrIterator.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclBase.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclarationName.h"
  23. #include "clang/AST/EvaluatedExprVisitor.h"
  24. #include "clang/AST/Expr.h"
  25. #include "clang/AST/ExprCXX.h"
  26. #include "clang/AST/ExprObjC.h"
  27. #include "clang/AST/ExprOpenMP.h"
  28. #include "clang/AST/FormatString.h"
  29. #include "clang/AST/NSAPI.h"
  30. #include "clang/AST/NonTrivialTypeVisitor.h"
  31. #include "clang/AST/OperationKinds.h"
  32. #include "clang/AST/RecordLayout.h"
  33. #include "clang/AST/Stmt.h"
  34. #include "clang/AST/TemplateBase.h"
  35. #include "clang/AST/Type.h"
  36. #include "clang/AST/TypeLoc.h"
  37. #include "clang/AST/UnresolvedSet.h"
  38. #include "clang/Basic/AddressSpaces.h"
  39. #include "clang/Basic/CharInfo.h"
  40. #include "clang/Basic/Diagnostic.h"
  41. #include "clang/Basic/IdentifierTable.h"
  42. #include "clang/Basic/LLVM.h"
  43. #include "clang/Basic/LangOptions.h"
  44. #include "clang/Basic/OpenCLOptions.h"
  45. #include "clang/Basic/OperatorKinds.h"
  46. #include "clang/Basic/PartialDiagnostic.h"
  47. #include "clang/Basic/SourceLocation.h"
  48. #include "clang/Basic/SourceManager.h"
  49. #include "clang/Basic/Specifiers.h"
  50. #include "clang/Basic/SyncScope.h"
  51. #include "clang/Basic/TargetBuiltins.h"
  52. #include "clang/Basic/TargetCXXABI.h"
  53. #include "clang/Basic/TargetInfo.h"
  54. #include "clang/Basic/TypeTraits.h"
  55. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  56. #include "clang/Sema/Initialization.h"
  57. #include "clang/Sema/Lookup.h"
  58. #include "clang/Sema/Ownership.h"
  59. #include "clang/Sema/Scope.h"
  60. #include "clang/Sema/ScopeInfo.h"
  61. #include "clang/Sema/Sema.h"
  62. #include "clang/Sema/SemaInternal.h"
  63. #include "llvm/ADT/APFloat.h"
  64. #include "llvm/ADT/APInt.h"
  65. #include "llvm/ADT/APSInt.h"
  66. #include "llvm/ADT/ArrayRef.h"
  67. #include "llvm/ADT/DenseMap.h"
  68. #include "llvm/ADT/FoldingSet.h"
  69. #include "llvm/ADT/STLExtras.h"
  70. #include "llvm/ADT/SmallBitVector.h"
  71. #include "llvm/ADT/SmallPtrSet.h"
  72. #include "llvm/ADT/SmallString.h"
  73. #include "llvm/ADT/SmallVector.h"
  74. #include "llvm/ADT/StringRef.h"
  75. #include "llvm/ADT/StringSet.h"
  76. #include "llvm/ADT/StringSwitch.h"
  77. #include "llvm/ADT/Triple.h"
  78. #include "llvm/Support/AtomicOrdering.h"
  79. #include "llvm/Support/Casting.h"
  80. #include "llvm/Support/Compiler.h"
  81. #include "llvm/Support/ConvertUTF.h"
  82. #include "llvm/Support/ErrorHandling.h"
  83. #include "llvm/Support/Format.h"
  84. #include "llvm/Support/Locale.h"
  85. #include "llvm/Support/MathExtras.h"
  86. #include "llvm/Support/SaveAndRestore.h"
  87. #include "llvm/Support/raw_ostream.h"
  88. #include <algorithm>
  89. #include <bitset>
  90. #include <cassert>
  91. #include <cctype>
  92. #include <cstddef>
  93. #include <cstdint>
  94. #include <functional>
  95. #include <limits>
  96. #include <optional>
  97. #include <string>
  98. #include <tuple>
  99. #include <utility>
  100. using namespace clang;
  101. using namespace sema;
  102. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  103. unsigned ByteNo) const {
  104. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  105. Context.getTargetInfo());
  106. }
  107. static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
  108. Sema::FormatArgumentPassingKind B) {
  109. return (A << 8) | B;
  110. }
  111. /// Checks that a call expression's argument count is at least the desired
  112. /// number. This is useful when doing custom type-checking on a variadic
  113. /// function. Returns true on error.
  114. static bool checkArgCountAtLeast(Sema &S, CallExpr *Call,
  115. unsigned MinArgCount) {
  116. unsigned ArgCount = Call->getNumArgs();
  117. if (ArgCount >= MinArgCount)
  118. return false;
  119. return S.Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
  120. << 0 /*function call*/ << MinArgCount << ArgCount
  121. << Call->getSourceRange();
  122. }
  123. /// Checks that a call expression's argument count is at most the desired
  124. /// number. This is useful when doing custom type-checking on a variadic
  125. /// function. Returns true on error.
  126. static bool checkArgCountAtMost(Sema &S, CallExpr *Call, unsigned MaxArgCount) {
  127. unsigned ArgCount = Call->getNumArgs();
  128. if (ArgCount <= MaxArgCount)
  129. return false;
  130. return S.Diag(Call->getEndLoc(),
  131. diag::err_typecheck_call_too_many_args_at_most)
  132. << 0 /*function call*/ << MaxArgCount << ArgCount
  133. << Call->getSourceRange();
  134. }
  135. /// Checks that a call expression's argument count is in the desired range. This
  136. /// is useful when doing custom type-checking on a variadic function. Returns
  137. /// true on error.
  138. static bool checkArgCountRange(Sema &S, CallExpr *Call, unsigned MinArgCount,
  139. unsigned MaxArgCount) {
  140. return checkArgCountAtLeast(S, Call, MinArgCount) ||
  141. checkArgCountAtMost(S, Call, MaxArgCount);
  142. }
  143. /// Checks that a call expression's argument count is the desired number.
  144. /// This is useful when doing custom type-checking. Returns true on error.
  145. static bool checkArgCount(Sema &S, CallExpr *Call, unsigned DesiredArgCount) {
  146. unsigned ArgCount = Call->getNumArgs();
  147. if (ArgCount == DesiredArgCount)
  148. return false;
  149. if (checkArgCountAtLeast(S, Call, DesiredArgCount))
  150. return true;
  151. assert(ArgCount > DesiredArgCount && "should have diagnosed this");
  152. // Highlight all the excess arguments.
  153. SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
  154. Call->getArg(ArgCount - 1)->getEndLoc());
  155. return S.Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
  156. << 0 /*function call*/ << DesiredArgCount << ArgCount
  157. << Call->getArg(1)->getSourceRange();
  158. }
  159. static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty) {
  160. if (Value->isTypeDependent())
  161. return false;
  162. InitializedEntity Entity =
  163. InitializedEntity::InitializeParameter(S.Context, Ty, false);
  164. ExprResult Result =
  165. S.PerformCopyInitialization(Entity, SourceLocation(), Value);
  166. if (Result.isInvalid())
  167. return true;
  168. Value = Result.get();
  169. return false;
  170. }
  171. /// Check that the first argument to __builtin_annotation is an integer
  172. /// and the second argument is a non-wide string literal.
  173. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  174. if (checkArgCount(S, TheCall, 2))
  175. return true;
  176. // First argument should be an integer.
  177. Expr *ValArg = TheCall->getArg(0);
  178. QualType Ty = ValArg->getType();
  179. if (!Ty->isIntegerType()) {
  180. S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
  181. << ValArg->getSourceRange();
  182. return true;
  183. }
  184. // Second argument should be a constant string.
  185. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  186. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  187. if (!Literal || !Literal->isOrdinary()) {
  188. S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
  189. << StrArg->getSourceRange();
  190. return true;
  191. }
  192. TheCall->setType(Ty);
  193. return false;
  194. }
  195. static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
  196. // We need at least one argument.
  197. if (TheCall->getNumArgs() < 1) {
  198. S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  199. << 0 << 1 << TheCall->getNumArgs()
  200. << TheCall->getCallee()->getSourceRange();
  201. return true;
  202. }
  203. // All arguments should be wide string literals.
  204. for (Expr *Arg : TheCall->arguments()) {
  205. auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  206. if (!Literal || !Literal->isWide()) {
  207. S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
  208. << Arg->getSourceRange();
  209. return true;
  210. }
  211. }
  212. return false;
  213. }
  214. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  215. /// result type to the corresponding pointer type.
  216. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  217. if (checkArgCount(S, TheCall, 1))
  218. return true;
  219. ExprResult Arg(TheCall->getArg(0));
  220. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
  221. if (ResultType.isNull())
  222. return true;
  223. TheCall->setArg(0, Arg.get());
  224. TheCall->setType(ResultType);
  225. return false;
  226. }
  227. /// Check that the argument to __builtin_function_start is a function.
  228. static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
  229. if (checkArgCount(S, TheCall, 1))
  230. return true;
  231. ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
  232. if (Arg.isInvalid())
  233. return true;
  234. TheCall->setArg(0, Arg.get());
  235. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
  236. Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext()));
  237. if (!FD) {
  238. S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
  239. << TheCall->getSourceRange();
  240. return true;
  241. }
  242. return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  243. TheCall->getBeginLoc());
  244. }
  245. /// Check the number of arguments and set the result type to
  246. /// the argument type.
  247. static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
  248. if (checkArgCount(S, TheCall, 1))
  249. return true;
  250. TheCall->setType(TheCall->getArg(0)->getType());
  251. return false;
  252. }
  253. /// Check that the value argument for __builtin_is_aligned(value, alignment) and
  254. /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
  255. /// type (but not a function pointer) and that the alignment is a power-of-two.
  256. static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
  257. if (checkArgCount(S, TheCall, 2))
  258. return true;
  259. clang::Expr *Source = TheCall->getArg(0);
  260. bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
  261. auto IsValidIntegerType = [](QualType Ty) {
  262. return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
  263. };
  264. QualType SrcTy = Source->getType();
  265. // We should also be able to use it with arrays (but not functions!).
  266. if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
  267. SrcTy = S.Context.getDecayedType(SrcTy);
  268. }
  269. if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
  270. SrcTy->isFunctionPointerType()) {
  271. // FIXME: this is not quite the right error message since we don't allow
  272. // floating point types, or member pointers.
  273. S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
  274. << SrcTy;
  275. return true;
  276. }
  277. clang::Expr *AlignOp = TheCall->getArg(1);
  278. if (!IsValidIntegerType(AlignOp->getType())) {
  279. S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
  280. << AlignOp->getType();
  281. return true;
  282. }
  283. Expr::EvalResult AlignResult;
  284. unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
  285. // We can't check validity of alignment if it is value dependent.
  286. if (!AlignOp->isValueDependent() &&
  287. AlignOp->EvaluateAsInt(AlignResult, S.Context,
  288. Expr::SE_AllowSideEffects)) {
  289. llvm::APSInt AlignValue = AlignResult.Val.getInt();
  290. llvm::APSInt MaxValue(
  291. llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
  292. if (AlignValue < 1) {
  293. S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
  294. return true;
  295. }
  296. if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
  297. S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
  298. << toString(MaxValue, 10);
  299. return true;
  300. }
  301. if (!AlignValue.isPowerOf2()) {
  302. S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
  303. return true;
  304. }
  305. if (AlignValue == 1) {
  306. S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
  307. << IsBooleanAlignBuiltin;
  308. }
  309. }
  310. ExprResult SrcArg = S.PerformCopyInitialization(
  311. InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
  312. SourceLocation(), Source);
  313. if (SrcArg.isInvalid())
  314. return true;
  315. TheCall->setArg(0, SrcArg.get());
  316. ExprResult AlignArg =
  317. S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
  318. S.Context, AlignOp->getType(), false),
  319. SourceLocation(), AlignOp);
  320. if (AlignArg.isInvalid())
  321. return true;
  322. TheCall->setArg(1, AlignArg.get());
  323. // For align_up/align_down, the return type is the same as the (potentially
  324. // decayed) argument type including qualifiers. For is_aligned(), the result
  325. // is always bool.
  326. TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
  327. return false;
  328. }
  329. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
  330. unsigned BuiltinID) {
  331. if (checkArgCount(S, TheCall, 3))
  332. return true;
  333. // First two arguments should be integers.
  334. for (unsigned I = 0; I < 2; ++I) {
  335. ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
  336. if (Arg.isInvalid()) return true;
  337. TheCall->setArg(I, Arg.get());
  338. QualType Ty = Arg.get()->getType();
  339. if (!Ty->isIntegerType()) {
  340. S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
  341. << Ty << Arg.get()->getSourceRange();
  342. return true;
  343. }
  344. }
  345. // Third argument should be a pointer to a non-const integer.
  346. // IRGen correctly handles volatile, restrict, and address spaces, and
  347. // the other qualifiers aren't possible.
  348. {
  349. ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
  350. if (Arg.isInvalid()) return true;
  351. TheCall->setArg(2, Arg.get());
  352. QualType Ty = Arg.get()->getType();
  353. const auto *PtrTy = Ty->getAs<PointerType>();
  354. if (!PtrTy ||
  355. !PtrTy->getPointeeType()->isIntegerType() ||
  356. PtrTy->getPointeeType().isConstQualified()) {
  357. S.Diag(Arg.get()->getBeginLoc(),
  358. diag::err_overflow_builtin_must_be_ptr_int)
  359. << Ty << Arg.get()->getSourceRange();
  360. return true;
  361. }
  362. }
  363. // Disallow signed bit-precise integer args larger than 128 bits to mul
  364. // function until we improve backend support.
  365. if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
  366. for (unsigned I = 0; I < 3; ++I) {
  367. const auto Arg = TheCall->getArg(I);
  368. // Third argument will be a pointer.
  369. auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
  370. if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
  371. S.getASTContext().getIntWidth(Ty) > 128)
  372. return S.Diag(Arg->getBeginLoc(),
  373. diag::err_overflow_builtin_bit_int_max_size)
  374. << 128;
  375. }
  376. }
  377. return false;
  378. }
  379. namespace {
  380. struct BuiltinDumpStructGenerator {
  381. Sema &S;
  382. CallExpr *TheCall;
  383. SourceLocation Loc = TheCall->getBeginLoc();
  384. SmallVector<Expr *, 32> Actions;
  385. DiagnosticErrorTrap ErrorTracker;
  386. PrintingPolicy Policy;
  387. BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
  388. : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
  389. Policy(S.Context.getPrintingPolicy()) {
  390. Policy.AnonymousTagLocations = false;
  391. }
  392. Expr *makeOpaqueValueExpr(Expr *Inner) {
  393. auto *OVE = new (S.Context)
  394. OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
  395. Inner->getObjectKind(), Inner);
  396. Actions.push_back(OVE);
  397. return OVE;
  398. }
  399. Expr *getStringLiteral(llvm::StringRef Str) {
  400. Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Str);
  401. // Wrap the literal in parentheses to attach a source location.
  402. return new (S.Context) ParenExpr(Loc, Loc, Lit);
  403. }
  404. bool callPrintFunction(llvm::StringRef Format,
  405. llvm::ArrayRef<Expr *> Exprs = {}) {
  406. SmallVector<Expr *, 8> Args;
  407. assert(TheCall->getNumArgs() >= 2);
  408. Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
  409. Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
  410. Args.push_back(getStringLiteral(Format));
  411. Args.insert(Args.end(), Exprs.begin(), Exprs.end());
  412. // Register a note to explain why we're performing the call.
  413. Sema::CodeSynthesisContext Ctx;
  414. Ctx.Kind = Sema::CodeSynthesisContext::BuildingBuiltinDumpStructCall;
  415. Ctx.PointOfInstantiation = Loc;
  416. Ctx.CallArgs = Args.data();
  417. Ctx.NumCallArgs = Args.size();
  418. S.pushCodeSynthesisContext(Ctx);
  419. ExprResult RealCall =
  420. S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
  421. TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
  422. S.popCodeSynthesisContext();
  423. if (!RealCall.isInvalid())
  424. Actions.push_back(RealCall.get());
  425. // Bail out if we've hit any errors, even if we managed to build the
  426. // call. We don't want to produce more than one error.
  427. return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
  428. }
  429. Expr *getIndentString(unsigned Depth) {
  430. if (!Depth)
  431. return nullptr;
  432. llvm::SmallString<32> Indent;
  433. Indent.resize(Depth * Policy.Indentation, ' ');
  434. return getStringLiteral(Indent);
  435. }
  436. Expr *getTypeString(QualType T) {
  437. return getStringLiteral(T.getAsString(Policy));
  438. }
  439. bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
  440. llvm::raw_svector_ostream OS(Str);
  441. // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
  442. // than trying to print a single character.
  443. if (auto *BT = T->getAs<BuiltinType>()) {
  444. switch (BT->getKind()) {
  445. case BuiltinType::Bool:
  446. OS << "%d";
  447. return true;
  448. case BuiltinType::Char_U:
  449. case BuiltinType::UChar:
  450. OS << "%hhu";
  451. return true;
  452. case BuiltinType::Char_S:
  453. case BuiltinType::SChar:
  454. OS << "%hhd";
  455. return true;
  456. default:
  457. break;
  458. }
  459. }
  460. analyze_printf::PrintfSpecifier Specifier;
  461. if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
  462. // We were able to guess how to format this.
  463. if (Specifier.getConversionSpecifier().getKind() ==
  464. analyze_printf::PrintfConversionSpecifier::sArg) {
  465. // Wrap double-quotes around a '%s' specifier and limit its maximum
  466. // length. Ideally we'd also somehow escape special characters in the
  467. // contents but printf doesn't support that.
  468. // FIXME: '%s' formatting is not safe in general.
  469. OS << '"';
  470. Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
  471. Specifier.toString(OS);
  472. OS << '"';
  473. // FIXME: It would be nice to include a '...' if the string doesn't fit
  474. // in the length limit.
  475. } else {
  476. Specifier.toString(OS);
  477. }
  478. return true;
  479. }
  480. if (T->isPointerType()) {
  481. // Format all pointers with '%p'.
  482. OS << "%p";
  483. return true;
  484. }
  485. return false;
  486. }
  487. bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
  488. Expr *IndentLit = getIndentString(Depth);
  489. Expr *TypeLit = getTypeString(S.Context.getRecordType(RD));
  490. if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
  491. : callPrintFunction("%s", {TypeLit}))
  492. return true;
  493. return dumpRecordValue(RD, E, IndentLit, Depth);
  494. }
  495. // Dump a record value. E should be a pointer or lvalue referring to an RD.
  496. bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
  497. unsigned Depth) {
  498. // FIXME: Decide what to do if RD is a union. At least we should probably
  499. // turn off printing `const char*` members with `%s`, because that is very
  500. // likely to crash if that's not the active member. Whatever we decide, we
  501. // should document it.
  502. // Build an OpaqueValueExpr so we can refer to E more than once without
  503. // triggering re-evaluation.
  504. Expr *RecordArg = makeOpaqueValueExpr(E);
  505. bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
  506. if (callPrintFunction(" {\n"))
  507. return true;
  508. // Dump each base class, regardless of whether they're aggregates.
  509. if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  510. for (const auto &Base : CXXRD->bases()) {
  511. QualType BaseType =
  512. RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
  513. : S.Context.getLValueReferenceType(Base.getType());
  514. ExprResult BasePtr = S.BuildCStyleCastExpr(
  515. Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
  516. RecordArg);
  517. if (BasePtr.isInvalid() ||
  518. dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
  519. Depth + 1))
  520. return true;
  521. }
  522. }
  523. Expr *FieldIndentArg = getIndentString(Depth + 1);
  524. // Dump each field.
  525. for (auto *D : RD->decls()) {
  526. auto *IFD = dyn_cast<IndirectFieldDecl>(D);
  527. auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
  528. if (!FD || FD->isUnnamedBitfield() || FD->isAnonymousStructOrUnion())
  529. continue;
  530. llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
  531. llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
  532. getTypeString(FD->getType()),
  533. getStringLiteral(FD->getName())};
  534. if (FD->isBitField()) {
  535. Format += ": %zu ";
  536. QualType SizeT = S.Context.getSizeType();
  537. llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
  538. FD->getBitWidthValue(S.Context));
  539. Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
  540. }
  541. Format += "=";
  542. ExprResult Field =
  543. IFD ? S.BuildAnonymousStructUnionMemberReference(
  544. CXXScopeSpec(), Loc, IFD,
  545. DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
  546. : S.BuildFieldReferenceExpr(
  547. RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
  548. DeclAccessPair::make(FD, AS_public),
  549. DeclarationNameInfo(FD->getDeclName(), Loc));
  550. if (Field.isInvalid())
  551. return true;
  552. auto *InnerRD = FD->getType()->getAsRecordDecl();
  553. auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
  554. if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
  555. // Recursively print the values of members of aggregate record type.
  556. if (callPrintFunction(Format, Args) ||
  557. dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
  558. return true;
  559. } else {
  560. Format += " ";
  561. if (appendFormatSpecifier(FD->getType(), Format)) {
  562. // We know how to print this field.
  563. Args.push_back(Field.get());
  564. } else {
  565. // We don't know how to print this field. Print out its address
  566. // with a format specifier that a smart tool will be able to
  567. // recognize and treat specially.
  568. Format += "*%p";
  569. ExprResult FieldAddr =
  570. S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
  571. if (FieldAddr.isInvalid())
  572. return true;
  573. Args.push_back(FieldAddr.get());
  574. }
  575. Format += "\n";
  576. if (callPrintFunction(Format, Args))
  577. return true;
  578. }
  579. }
  580. return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
  581. : callPrintFunction("}\n");
  582. }
  583. Expr *buildWrapper() {
  584. auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
  585. PseudoObjectExpr::NoResult);
  586. TheCall->setType(Wrapper->getType());
  587. TheCall->setValueKind(Wrapper->getValueKind());
  588. return Wrapper;
  589. }
  590. };
  591. } // namespace
  592. static ExprResult SemaBuiltinDumpStruct(Sema &S, CallExpr *TheCall) {
  593. if (checkArgCountAtLeast(S, TheCall, 2))
  594. return ExprError();
  595. ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
  596. if (PtrArgResult.isInvalid())
  597. return ExprError();
  598. TheCall->setArg(0, PtrArgResult.get());
  599. // First argument should be a pointer to a struct.
  600. QualType PtrArgType = PtrArgResult.get()->getType();
  601. if (!PtrArgType->isPointerType() ||
  602. !PtrArgType->getPointeeType()->isRecordType()) {
  603. S.Diag(PtrArgResult.get()->getBeginLoc(),
  604. diag::err_expected_struct_pointer_argument)
  605. << 1 << TheCall->getDirectCallee() << PtrArgType;
  606. return ExprError();
  607. }
  608. const RecordDecl *RD = PtrArgType->getPointeeType()->getAsRecordDecl();
  609. // Second argument is a callable, but we can't fully validate it until we try
  610. // calling it.
  611. QualType FnArgType = TheCall->getArg(1)->getType();
  612. if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
  613. !FnArgType->isBlockPointerType() &&
  614. !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
  615. auto *BT = FnArgType->getAs<BuiltinType>();
  616. switch (BT ? BT->getKind() : BuiltinType::Void) {
  617. case BuiltinType::Dependent:
  618. case BuiltinType::Overload:
  619. case BuiltinType::BoundMember:
  620. case BuiltinType::PseudoObject:
  621. case BuiltinType::UnknownAny:
  622. case BuiltinType::BuiltinFn:
  623. // This might be a callable.
  624. break;
  625. default:
  626. S.Diag(TheCall->getArg(1)->getBeginLoc(),
  627. diag::err_expected_callable_argument)
  628. << 2 << TheCall->getDirectCallee() << FnArgType;
  629. return ExprError();
  630. }
  631. }
  632. BuiltinDumpStructGenerator Generator(S, TheCall);
  633. // Wrap parentheses around the given pointer. This is not necessary for
  634. // correct code generation, but it means that when we pretty-print the call
  635. // arguments in our diagnostics we will produce '(&s)->n' instead of the
  636. // incorrect '&s->n'.
  637. Expr *PtrArg = PtrArgResult.get();
  638. PtrArg = new (S.Context)
  639. ParenExpr(PtrArg->getBeginLoc(),
  640. S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
  641. if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
  642. return ExprError();
  643. return Generator.buildWrapper();
  644. }
  645. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  646. if (checkArgCount(S, BuiltinCall, 2))
  647. return true;
  648. SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
  649. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  650. Expr *Call = BuiltinCall->getArg(0);
  651. Expr *Chain = BuiltinCall->getArg(1);
  652. if (Call->getStmtClass() != Stmt::CallExprClass) {
  653. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  654. << Call->getSourceRange();
  655. return true;
  656. }
  657. auto CE = cast<CallExpr>(Call);
  658. if (CE->getCallee()->getType()->isBlockPointerType()) {
  659. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  660. << Call->getSourceRange();
  661. return true;
  662. }
  663. const Decl *TargetDecl = CE->getCalleeDecl();
  664. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  665. if (FD->getBuiltinID()) {
  666. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  667. << Call->getSourceRange();
  668. return true;
  669. }
  670. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  671. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  672. << Call->getSourceRange();
  673. return true;
  674. }
  675. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  676. if (ChainResult.isInvalid())
  677. return true;
  678. if (!ChainResult.get()->getType()->isPointerType()) {
  679. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  680. << Chain->getSourceRange();
  681. return true;
  682. }
  683. QualType ReturnTy = CE->getCallReturnType(S.Context);
  684. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  685. QualType BuiltinTy = S.Context.getFunctionType(
  686. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  687. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  688. Builtin =
  689. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  690. BuiltinCall->setType(CE->getType());
  691. BuiltinCall->setValueKind(CE->getValueKind());
  692. BuiltinCall->setObjectKind(CE->getObjectKind());
  693. BuiltinCall->setCallee(Builtin);
  694. BuiltinCall->setArg(1, ChainResult.get());
  695. return false;
  696. }
  697. namespace {
  698. class ScanfDiagnosticFormatHandler
  699. : public analyze_format_string::FormatStringHandler {
  700. // Accepts the argument index (relative to the first destination index) of the
  701. // argument whose size we want.
  702. using ComputeSizeFunction =
  703. llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
  704. // Accepts the argument index (relative to the first destination index), the
  705. // destination size, and the source size).
  706. using DiagnoseFunction =
  707. llvm::function_ref<void(unsigned, unsigned, unsigned)>;
  708. ComputeSizeFunction ComputeSizeArgument;
  709. DiagnoseFunction Diagnose;
  710. public:
  711. ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
  712. DiagnoseFunction Diagnose)
  713. : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
  714. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  715. const char *StartSpecifier,
  716. unsigned specifierLen) override {
  717. if (!FS.consumesDataArgument())
  718. return true;
  719. unsigned NulByte = 0;
  720. switch ((FS.getConversionSpecifier().getKind())) {
  721. default:
  722. return true;
  723. case analyze_format_string::ConversionSpecifier::sArg:
  724. case analyze_format_string::ConversionSpecifier::ScanListArg:
  725. NulByte = 1;
  726. break;
  727. case analyze_format_string::ConversionSpecifier::cArg:
  728. break;
  729. }
  730. analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
  731. if (FW.getHowSpecified() !=
  732. analyze_format_string::OptionalAmount::HowSpecified::Constant)
  733. return true;
  734. unsigned SourceSize = FW.getConstantAmount() + NulByte;
  735. std::optional<llvm::APSInt> DestSizeAPS =
  736. ComputeSizeArgument(FS.getArgIndex());
  737. if (!DestSizeAPS)
  738. return true;
  739. unsigned DestSize = DestSizeAPS->getZExtValue();
  740. if (DestSize < SourceSize)
  741. Diagnose(FS.getArgIndex(), DestSize, SourceSize);
  742. return true;
  743. }
  744. };
  745. class EstimateSizeFormatHandler
  746. : public analyze_format_string::FormatStringHandler {
  747. size_t Size;
  748. public:
  749. EstimateSizeFormatHandler(StringRef Format)
  750. : Size(std::min(Format.find(0), Format.size()) +
  751. 1 /* null byte always written by sprintf */) {}
  752. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  753. const char *, unsigned SpecifierLen,
  754. const TargetInfo &) override {
  755. const size_t FieldWidth = computeFieldWidth(FS);
  756. const size_t Precision = computePrecision(FS);
  757. // The actual format.
  758. switch (FS.getConversionSpecifier().getKind()) {
  759. // Just a char.
  760. case analyze_format_string::ConversionSpecifier::cArg:
  761. case analyze_format_string::ConversionSpecifier::CArg:
  762. Size += std::max(FieldWidth, (size_t)1);
  763. break;
  764. // Just an integer.
  765. case analyze_format_string::ConversionSpecifier::dArg:
  766. case analyze_format_string::ConversionSpecifier::DArg:
  767. case analyze_format_string::ConversionSpecifier::iArg:
  768. case analyze_format_string::ConversionSpecifier::oArg:
  769. case analyze_format_string::ConversionSpecifier::OArg:
  770. case analyze_format_string::ConversionSpecifier::uArg:
  771. case analyze_format_string::ConversionSpecifier::UArg:
  772. case analyze_format_string::ConversionSpecifier::xArg:
  773. case analyze_format_string::ConversionSpecifier::XArg:
  774. Size += std::max(FieldWidth, Precision);
  775. break;
  776. // %g style conversion switches between %f or %e style dynamically.
  777. // %f always takes less space, so default to it.
  778. case analyze_format_string::ConversionSpecifier::gArg:
  779. case analyze_format_string::ConversionSpecifier::GArg:
  780. // Floating point number in the form '[+]ddd.ddd'.
  781. case analyze_format_string::ConversionSpecifier::fArg:
  782. case analyze_format_string::ConversionSpecifier::FArg:
  783. Size += std::max(FieldWidth, 1 /* integer part */ +
  784. (Precision ? 1 + Precision
  785. : 0) /* period + decimal */);
  786. break;
  787. // Floating point number in the form '[-]d.ddde[+-]dd'.
  788. case analyze_format_string::ConversionSpecifier::eArg:
  789. case analyze_format_string::ConversionSpecifier::EArg:
  790. Size +=
  791. std::max(FieldWidth,
  792. 1 /* integer part */ +
  793. (Precision ? 1 + Precision : 0) /* period + decimal */ +
  794. 1 /* e or E letter */ + 2 /* exponent */);
  795. break;
  796. // Floating point number in the form '[-]0xh.hhhhp±dd'.
  797. case analyze_format_string::ConversionSpecifier::aArg:
  798. case analyze_format_string::ConversionSpecifier::AArg:
  799. Size +=
  800. std::max(FieldWidth,
  801. 2 /* 0x */ + 1 /* integer part */ +
  802. (Precision ? 1 + Precision : 0) /* period + decimal */ +
  803. 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
  804. break;
  805. // Just a string.
  806. case analyze_format_string::ConversionSpecifier::sArg:
  807. case analyze_format_string::ConversionSpecifier::SArg:
  808. Size += FieldWidth;
  809. break;
  810. // Just a pointer in the form '0xddd'.
  811. case analyze_format_string::ConversionSpecifier::pArg:
  812. Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
  813. break;
  814. // A plain percent.
  815. case analyze_format_string::ConversionSpecifier::PercentArg:
  816. Size += 1;
  817. break;
  818. default:
  819. break;
  820. }
  821. Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
  822. if (FS.hasAlternativeForm()) {
  823. switch (FS.getConversionSpecifier().getKind()) {
  824. default:
  825. break;
  826. // Force a leading '0'.
  827. case analyze_format_string::ConversionSpecifier::oArg:
  828. Size += 1;
  829. break;
  830. // Force a leading '0x'.
  831. case analyze_format_string::ConversionSpecifier::xArg:
  832. case analyze_format_string::ConversionSpecifier::XArg:
  833. Size += 2;
  834. break;
  835. // Force a period '.' before decimal, even if precision is 0.
  836. case analyze_format_string::ConversionSpecifier::aArg:
  837. case analyze_format_string::ConversionSpecifier::AArg:
  838. case analyze_format_string::ConversionSpecifier::eArg:
  839. case analyze_format_string::ConversionSpecifier::EArg:
  840. case analyze_format_string::ConversionSpecifier::fArg:
  841. case analyze_format_string::ConversionSpecifier::FArg:
  842. case analyze_format_string::ConversionSpecifier::gArg:
  843. case analyze_format_string::ConversionSpecifier::GArg:
  844. Size += (Precision ? 0 : 1);
  845. break;
  846. }
  847. }
  848. assert(SpecifierLen <= Size && "no underflow");
  849. Size -= SpecifierLen;
  850. return true;
  851. }
  852. size_t getSizeLowerBound() const { return Size; }
  853. private:
  854. static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
  855. const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
  856. size_t FieldWidth = 0;
  857. if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
  858. FieldWidth = FW.getConstantAmount();
  859. return FieldWidth;
  860. }
  861. static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
  862. const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
  863. size_t Precision = 0;
  864. // See man 3 printf for default precision value based on the specifier.
  865. switch (FW.getHowSpecified()) {
  866. case analyze_format_string::OptionalAmount::NotSpecified:
  867. switch (FS.getConversionSpecifier().getKind()) {
  868. default:
  869. break;
  870. case analyze_format_string::ConversionSpecifier::dArg: // %d
  871. case analyze_format_string::ConversionSpecifier::DArg: // %D
  872. case analyze_format_string::ConversionSpecifier::iArg: // %i
  873. Precision = 1;
  874. break;
  875. case analyze_format_string::ConversionSpecifier::oArg: // %d
  876. case analyze_format_string::ConversionSpecifier::OArg: // %D
  877. case analyze_format_string::ConversionSpecifier::uArg: // %d
  878. case analyze_format_string::ConversionSpecifier::UArg: // %D
  879. case analyze_format_string::ConversionSpecifier::xArg: // %d
  880. case analyze_format_string::ConversionSpecifier::XArg: // %D
  881. Precision = 1;
  882. break;
  883. case analyze_format_string::ConversionSpecifier::fArg: // %f
  884. case analyze_format_string::ConversionSpecifier::FArg: // %F
  885. case analyze_format_string::ConversionSpecifier::eArg: // %e
  886. case analyze_format_string::ConversionSpecifier::EArg: // %E
  887. case analyze_format_string::ConversionSpecifier::gArg: // %g
  888. case analyze_format_string::ConversionSpecifier::GArg: // %G
  889. Precision = 6;
  890. break;
  891. case analyze_format_string::ConversionSpecifier::pArg: // %d
  892. Precision = 1;
  893. break;
  894. }
  895. break;
  896. case analyze_format_string::OptionalAmount::Constant:
  897. Precision = FW.getConstantAmount();
  898. break;
  899. default:
  900. break;
  901. }
  902. return Precision;
  903. }
  904. };
  905. } // namespace
  906. void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
  907. CallExpr *TheCall) {
  908. if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
  909. isConstantEvaluated())
  910. return;
  911. bool UseDABAttr = false;
  912. const FunctionDecl *UseDecl = FD;
  913. const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
  914. if (DABAttr) {
  915. UseDecl = DABAttr->getFunction();
  916. assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
  917. UseDABAttr = true;
  918. }
  919. unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
  920. if (!BuiltinID)
  921. return;
  922. const TargetInfo &TI = getASTContext().getTargetInfo();
  923. unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
  924. auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
  925. // If we refer to a diagnose_as_builtin attribute, we need to change the
  926. // argument index to refer to the arguments of the called function. Unless
  927. // the index is out of bounds, which presumably means it's a variadic
  928. // function.
  929. if (!UseDABAttr)
  930. return Index;
  931. unsigned DABIndices = DABAttr->argIndices_size();
  932. unsigned NewIndex = Index < DABIndices
  933. ? DABAttr->argIndices_begin()[Index]
  934. : Index - DABIndices + FD->getNumParams();
  935. if (NewIndex >= TheCall->getNumArgs())
  936. return std::nullopt;
  937. return NewIndex;
  938. };
  939. auto ComputeExplicitObjectSizeArgument =
  940. [&](unsigned Index) -> std::optional<llvm::APSInt> {
  941. std::optional<unsigned> IndexOptional = TranslateIndex(Index);
  942. if (!IndexOptional)
  943. return std::nullopt;
  944. unsigned NewIndex = *IndexOptional;
  945. Expr::EvalResult Result;
  946. Expr *SizeArg = TheCall->getArg(NewIndex);
  947. if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
  948. return std::nullopt;
  949. llvm::APSInt Integer = Result.Val.getInt();
  950. Integer.setIsUnsigned(true);
  951. return Integer;
  952. };
  953. auto ComputeSizeArgument =
  954. [&](unsigned Index) -> std::optional<llvm::APSInt> {
  955. // If the parameter has a pass_object_size attribute, then we should use its
  956. // (potentially) more strict checking mode. Otherwise, conservatively assume
  957. // type 0.
  958. int BOSType = 0;
  959. // This check can fail for variadic functions.
  960. if (Index < FD->getNumParams()) {
  961. if (const auto *POS =
  962. FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
  963. BOSType = POS->getType();
  964. }
  965. std::optional<unsigned> IndexOptional = TranslateIndex(Index);
  966. if (!IndexOptional)
  967. return std::nullopt;
  968. unsigned NewIndex = *IndexOptional;
  969. if (NewIndex >= TheCall->getNumArgs())
  970. return std::nullopt;
  971. const Expr *ObjArg = TheCall->getArg(NewIndex);
  972. uint64_t Result;
  973. if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
  974. return std::nullopt;
  975. // Get the object size in the target's size_t width.
  976. return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
  977. };
  978. auto ComputeStrLenArgument =
  979. [&](unsigned Index) -> std::optional<llvm::APSInt> {
  980. std::optional<unsigned> IndexOptional = TranslateIndex(Index);
  981. if (!IndexOptional)
  982. return std::nullopt;
  983. unsigned NewIndex = *IndexOptional;
  984. const Expr *ObjArg = TheCall->getArg(NewIndex);
  985. uint64_t Result;
  986. if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
  987. return std::nullopt;
  988. // Add 1 for null byte.
  989. return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
  990. };
  991. std::optional<llvm::APSInt> SourceSize;
  992. std::optional<llvm::APSInt> DestinationSize;
  993. unsigned DiagID = 0;
  994. bool IsChkVariant = false;
  995. auto GetFunctionName = [&]() {
  996. StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
  997. // Skim off the details of whichever builtin was called to produce a better
  998. // diagnostic, as it's unlikely that the user wrote the __builtin
  999. // explicitly.
  1000. if (IsChkVariant) {
  1001. FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
  1002. FunctionName = FunctionName.drop_back(std::strlen("_chk"));
  1003. } else if (FunctionName.startswith("__builtin_")) {
  1004. FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
  1005. }
  1006. return FunctionName;
  1007. };
  1008. switch (BuiltinID) {
  1009. default:
  1010. return;
  1011. case Builtin::BI__builtin_strcpy:
  1012. case Builtin::BIstrcpy: {
  1013. DiagID = diag::warn_fortify_strlen_overflow;
  1014. SourceSize = ComputeStrLenArgument(1);
  1015. DestinationSize = ComputeSizeArgument(0);
  1016. break;
  1017. }
  1018. case Builtin::BI__builtin___strcpy_chk: {
  1019. DiagID = diag::warn_fortify_strlen_overflow;
  1020. SourceSize = ComputeStrLenArgument(1);
  1021. DestinationSize = ComputeExplicitObjectSizeArgument(2);
  1022. IsChkVariant = true;
  1023. break;
  1024. }
  1025. case Builtin::BIscanf:
  1026. case Builtin::BIfscanf:
  1027. case Builtin::BIsscanf: {
  1028. unsigned FormatIndex = 1;
  1029. unsigned DataIndex = 2;
  1030. if (BuiltinID == Builtin::BIscanf) {
  1031. FormatIndex = 0;
  1032. DataIndex = 1;
  1033. }
  1034. const auto *FormatExpr =
  1035. TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
  1036. const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
  1037. if (!Format)
  1038. return;
  1039. if (!Format->isOrdinary() && !Format->isUTF8())
  1040. return;
  1041. auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
  1042. unsigned SourceSize) {
  1043. DiagID = diag::warn_fortify_scanf_overflow;
  1044. unsigned Index = ArgIndex + DataIndex;
  1045. StringRef FunctionName = GetFunctionName();
  1046. DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
  1047. PDiag(DiagID) << FunctionName << (Index + 1)
  1048. << DestSize << SourceSize);
  1049. };
  1050. StringRef FormatStrRef = Format->getString();
  1051. auto ShiftedComputeSizeArgument = [&](unsigned Index) {
  1052. return ComputeSizeArgument(Index + DataIndex);
  1053. };
  1054. ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
  1055. const char *FormatBytes = FormatStrRef.data();
  1056. const ConstantArrayType *T =
  1057. Context.getAsConstantArrayType(Format->getType());
  1058. assert(T && "String literal not of constant array type!");
  1059. size_t TypeSize = T->getSize().getZExtValue();
  1060. // In case there's a null byte somewhere.
  1061. size_t StrLen =
  1062. std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
  1063. analyze_format_string::ParseScanfString(H, FormatBytes,
  1064. FormatBytes + StrLen, getLangOpts(),
  1065. Context.getTargetInfo());
  1066. // Unlike the other cases, in this one we have already issued the diagnostic
  1067. // here, so no need to continue (because unlike the other cases, here the
  1068. // diagnostic refers to the argument number).
  1069. return;
  1070. }
  1071. case Builtin::BIsprintf:
  1072. case Builtin::BI__builtin___sprintf_chk: {
  1073. size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
  1074. auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
  1075. if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
  1076. if (!Format->isOrdinary() && !Format->isUTF8())
  1077. return;
  1078. StringRef FormatStrRef = Format->getString();
  1079. EstimateSizeFormatHandler H(FormatStrRef);
  1080. const char *FormatBytes = FormatStrRef.data();
  1081. const ConstantArrayType *T =
  1082. Context.getAsConstantArrayType(Format->getType());
  1083. assert(T && "String literal not of constant array type!");
  1084. size_t TypeSize = T->getSize().getZExtValue();
  1085. // In case there's a null byte somewhere.
  1086. size_t StrLen =
  1087. std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
  1088. if (!analyze_format_string::ParsePrintfString(
  1089. H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
  1090. Context.getTargetInfo(), false)) {
  1091. DiagID = diag::warn_fortify_source_format_overflow;
  1092. SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
  1093. .extOrTrunc(SizeTypeWidth);
  1094. if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
  1095. DestinationSize = ComputeExplicitObjectSizeArgument(2);
  1096. IsChkVariant = true;
  1097. } else {
  1098. DestinationSize = ComputeSizeArgument(0);
  1099. }
  1100. break;
  1101. }
  1102. }
  1103. return;
  1104. }
  1105. case Builtin::BI__builtin___memcpy_chk:
  1106. case Builtin::BI__builtin___memmove_chk:
  1107. case Builtin::BI__builtin___memset_chk:
  1108. case Builtin::BI__builtin___strlcat_chk:
  1109. case Builtin::BI__builtin___strlcpy_chk:
  1110. case Builtin::BI__builtin___strncat_chk:
  1111. case Builtin::BI__builtin___strncpy_chk:
  1112. case Builtin::BI__builtin___stpncpy_chk:
  1113. case Builtin::BI__builtin___memccpy_chk:
  1114. case Builtin::BI__builtin___mempcpy_chk: {
  1115. DiagID = diag::warn_builtin_chk_overflow;
  1116. SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
  1117. DestinationSize =
  1118. ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
  1119. IsChkVariant = true;
  1120. break;
  1121. }
  1122. case Builtin::BI__builtin___snprintf_chk:
  1123. case Builtin::BI__builtin___vsnprintf_chk: {
  1124. DiagID = diag::warn_builtin_chk_overflow;
  1125. SourceSize = ComputeExplicitObjectSizeArgument(1);
  1126. DestinationSize = ComputeExplicitObjectSizeArgument(3);
  1127. IsChkVariant = true;
  1128. break;
  1129. }
  1130. case Builtin::BIstrncat:
  1131. case Builtin::BI__builtin_strncat:
  1132. case Builtin::BIstrncpy:
  1133. case Builtin::BI__builtin_strncpy:
  1134. case Builtin::BIstpncpy:
  1135. case Builtin::BI__builtin_stpncpy: {
  1136. // Whether these functions overflow depends on the runtime strlen of the
  1137. // string, not just the buffer size, so emitting the "always overflow"
  1138. // diagnostic isn't quite right. We should still diagnose passing a buffer
  1139. // size larger than the destination buffer though; this is a runtime abort
  1140. // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
  1141. DiagID = diag::warn_fortify_source_size_mismatch;
  1142. SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
  1143. DestinationSize = ComputeSizeArgument(0);
  1144. break;
  1145. }
  1146. case Builtin::BImemcpy:
  1147. case Builtin::BI__builtin_memcpy:
  1148. case Builtin::BImemmove:
  1149. case Builtin::BI__builtin_memmove:
  1150. case Builtin::BImemset:
  1151. case Builtin::BI__builtin_memset:
  1152. case Builtin::BImempcpy:
  1153. case Builtin::BI__builtin_mempcpy: {
  1154. DiagID = diag::warn_fortify_source_overflow;
  1155. SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
  1156. DestinationSize = ComputeSizeArgument(0);
  1157. break;
  1158. }
  1159. case Builtin::BIsnprintf:
  1160. case Builtin::BI__builtin_snprintf:
  1161. case Builtin::BIvsnprintf:
  1162. case Builtin::BI__builtin_vsnprintf: {
  1163. DiagID = diag::warn_fortify_source_size_mismatch;
  1164. SourceSize = ComputeExplicitObjectSizeArgument(1);
  1165. DestinationSize = ComputeSizeArgument(0);
  1166. break;
  1167. }
  1168. }
  1169. if (!SourceSize || !DestinationSize ||
  1170. llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
  1171. return;
  1172. StringRef FunctionName = GetFunctionName();
  1173. SmallString<16> DestinationStr;
  1174. SmallString<16> SourceStr;
  1175. DestinationSize->toString(DestinationStr, /*Radix=*/10);
  1176. SourceSize->toString(SourceStr, /*Radix=*/10);
  1177. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  1178. PDiag(DiagID)
  1179. << FunctionName << DestinationStr << SourceStr);
  1180. }
  1181. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  1182. Scope::ScopeFlags NeededScopeFlags,
  1183. unsigned DiagID) {
  1184. // Scopes aren't available during instantiation. Fortunately, builtin
  1185. // functions cannot be template args so they cannot be formed through template
  1186. // instantiation. Therefore checking once during the parse is sufficient.
  1187. if (SemaRef.inTemplateInstantiation())
  1188. return false;
  1189. Scope *S = SemaRef.getCurScope();
  1190. while (S && !S->isSEHExceptScope())
  1191. S = S->getParent();
  1192. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  1193. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1194. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  1195. << DRE->getDecl()->getIdentifier();
  1196. return true;
  1197. }
  1198. return false;
  1199. }
  1200. static inline bool isBlockPointer(Expr *Arg) {
  1201. return Arg->getType()->isBlockPointerType();
  1202. }
  1203. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  1204. /// void*, which is a requirement of device side enqueue.
  1205. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  1206. const BlockPointerType *BPT =
  1207. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  1208. ArrayRef<QualType> Params =
  1209. BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
  1210. unsigned ArgCounter = 0;
  1211. bool IllegalParams = false;
  1212. // Iterate through the block parameters until either one is found that is not
  1213. // a local void*, or the block is valid.
  1214. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  1215. I != E; ++I, ++ArgCounter) {
  1216. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  1217. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  1218. LangAS::opencl_local) {
  1219. // Get the location of the error. If a block literal has been passed
  1220. // (BlockExpr) then we can point straight to the offending argument,
  1221. // else we just point to the variable reference.
  1222. SourceLocation ErrorLoc;
  1223. if (isa<BlockExpr>(BlockArg)) {
  1224. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  1225. ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
  1226. } else if (isa<DeclRefExpr>(BlockArg)) {
  1227. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
  1228. }
  1229. S.Diag(ErrorLoc,
  1230. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  1231. IllegalParams = true;
  1232. }
  1233. }
  1234. return IllegalParams;
  1235. }
  1236. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  1237. // OpenCL device can support extension but not the feature as extension
  1238. // requires subgroup independent forward progress, but subgroup independent
  1239. // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature.
  1240. if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) &&
  1241. !S.getOpenCLOptions().isSupported("__opencl_c_subgroups",
  1242. S.getLangOpts())) {
  1243. S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
  1244. << 1 << Call->getDirectCallee()
  1245. << "cl_khr_subgroups or __opencl_c_subgroups";
  1246. return true;
  1247. }
  1248. return false;
  1249. }
  1250. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  1251. if (checkArgCount(S, TheCall, 2))
  1252. return true;
  1253. if (checkOpenCLSubgroupExt(S, TheCall))
  1254. return true;
  1255. // First argument is an ndrange_t type.
  1256. Expr *NDRangeArg = TheCall->getArg(0);
  1257. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  1258. S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  1259. << TheCall->getDirectCallee() << "'ndrange_t'";
  1260. return true;
  1261. }
  1262. Expr *BlockArg = TheCall->getArg(1);
  1263. if (!isBlockPointer(BlockArg)) {
  1264. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  1265. << TheCall->getDirectCallee() << "block";
  1266. return true;
  1267. }
  1268. return checkOpenCLBlockArgs(S, BlockArg);
  1269. }
  1270. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  1271. /// get_kernel_work_group_size
  1272. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  1273. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  1274. if (checkArgCount(S, TheCall, 1))
  1275. return true;
  1276. Expr *BlockArg = TheCall->getArg(0);
  1277. if (!isBlockPointer(BlockArg)) {
  1278. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  1279. << TheCall->getDirectCallee() << "block";
  1280. return true;
  1281. }
  1282. return checkOpenCLBlockArgs(S, BlockArg);
  1283. }
  1284. /// Diagnose integer type and any valid implicit conversion to it.
  1285. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  1286. const QualType &IntType);
  1287. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  1288. unsigned Start, unsigned End) {
  1289. bool IllegalParams = false;
  1290. for (unsigned I = Start; I <= End; ++I)
  1291. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  1292. S.Context.getSizeType());
  1293. return IllegalParams;
  1294. }
  1295. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  1296. /// 'local void*' parameter of passed block.
  1297. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  1298. Expr *BlockArg,
  1299. unsigned NumNonVarArgs) {
  1300. const BlockPointerType *BPT =
  1301. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  1302. unsigned NumBlockParams =
  1303. BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
  1304. unsigned TotalNumArgs = TheCall->getNumArgs();
  1305. // For each argument passed to the block, a corresponding uint needs to
  1306. // be passed to describe the size of the local memory.
  1307. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  1308. S.Diag(TheCall->getBeginLoc(),
  1309. diag::err_opencl_enqueue_kernel_local_size_args);
  1310. return true;
  1311. }
  1312. // Check that the sizes of the local memory are specified by integers.
  1313. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  1314. TotalNumArgs - 1);
  1315. }
  1316. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  1317. /// overload formats specified in Table 6.13.17.1.
  1318. /// int enqueue_kernel(queue_t queue,
  1319. /// kernel_enqueue_flags_t flags,
  1320. /// const ndrange_t ndrange,
  1321. /// void (^block)(void))
  1322. /// int enqueue_kernel(queue_t queue,
  1323. /// kernel_enqueue_flags_t flags,
  1324. /// const ndrange_t ndrange,
  1325. /// uint num_events_in_wait_list,
  1326. /// clk_event_t *event_wait_list,
  1327. /// clk_event_t *event_ret,
  1328. /// void (^block)(void))
  1329. /// int enqueue_kernel(queue_t queue,
  1330. /// kernel_enqueue_flags_t flags,
  1331. /// const ndrange_t ndrange,
  1332. /// void (^block)(local void*, ...),
  1333. /// uint size0, ...)
  1334. /// int enqueue_kernel(queue_t queue,
  1335. /// kernel_enqueue_flags_t flags,
  1336. /// const ndrange_t ndrange,
  1337. /// uint num_events_in_wait_list,
  1338. /// clk_event_t *event_wait_list,
  1339. /// clk_event_t *event_ret,
  1340. /// void (^block)(local void*, ...),
  1341. /// uint size0, ...)
  1342. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  1343. unsigned NumArgs = TheCall->getNumArgs();
  1344. if (NumArgs < 4) {
  1345. S.Diag(TheCall->getBeginLoc(),
  1346. diag::err_typecheck_call_too_few_args_at_least)
  1347. << 0 << 4 << NumArgs;
  1348. return true;
  1349. }
  1350. Expr *Arg0 = TheCall->getArg(0);
  1351. Expr *Arg1 = TheCall->getArg(1);
  1352. Expr *Arg2 = TheCall->getArg(2);
  1353. Expr *Arg3 = TheCall->getArg(3);
  1354. // First argument always needs to be a queue_t type.
  1355. if (!Arg0->getType()->isQueueT()) {
  1356. S.Diag(TheCall->getArg(0)->getBeginLoc(),
  1357. diag::err_opencl_builtin_expected_type)
  1358. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  1359. return true;
  1360. }
  1361. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  1362. if (!Arg1->getType()->isIntegerType()) {
  1363. S.Diag(TheCall->getArg(1)->getBeginLoc(),
  1364. diag::err_opencl_builtin_expected_type)
  1365. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  1366. return true;
  1367. }
  1368. // Third argument is always an ndrange_t type.
  1369. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  1370. S.Diag(TheCall->getArg(2)->getBeginLoc(),
  1371. diag::err_opencl_builtin_expected_type)
  1372. << TheCall->getDirectCallee() << "'ndrange_t'";
  1373. return true;
  1374. }
  1375. // With four arguments, there is only one form that the function could be
  1376. // called in: no events and no variable arguments.
  1377. if (NumArgs == 4) {
  1378. // check that the last argument is the right block type.
  1379. if (!isBlockPointer(Arg3)) {
  1380. S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  1381. << TheCall->getDirectCallee() << "block";
  1382. return true;
  1383. }
  1384. // we have a block type, check the prototype
  1385. const BlockPointerType *BPT =
  1386. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  1387. if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
  1388. S.Diag(Arg3->getBeginLoc(),
  1389. diag::err_opencl_enqueue_kernel_blocks_no_args);
  1390. return true;
  1391. }
  1392. return false;
  1393. }
  1394. // we can have block + varargs.
  1395. if (isBlockPointer(Arg3))
  1396. return (checkOpenCLBlockArgs(S, Arg3) ||
  1397. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  1398. // last two cases with either exactly 7 args or 7 args and varargs.
  1399. if (NumArgs >= 7) {
  1400. // check common block argument.
  1401. Expr *Arg6 = TheCall->getArg(6);
  1402. if (!isBlockPointer(Arg6)) {
  1403. S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  1404. << TheCall->getDirectCallee() << "block";
  1405. return true;
  1406. }
  1407. if (checkOpenCLBlockArgs(S, Arg6))
  1408. return true;
  1409. // Forth argument has to be any integer type.
  1410. if (!Arg3->getType()->isIntegerType()) {
  1411. S.Diag(TheCall->getArg(3)->getBeginLoc(),
  1412. diag::err_opencl_builtin_expected_type)
  1413. << TheCall->getDirectCallee() << "integer";
  1414. return true;
  1415. }
  1416. // check remaining common arguments.
  1417. Expr *Arg4 = TheCall->getArg(4);
  1418. Expr *Arg5 = TheCall->getArg(5);
  1419. // Fifth argument is always passed as a pointer to clk_event_t.
  1420. if (!Arg4->isNullPointerConstant(S.Context,
  1421. Expr::NPC_ValueDependentIsNotNull) &&
  1422. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  1423. S.Diag(TheCall->getArg(4)->getBeginLoc(),
  1424. diag::err_opencl_builtin_expected_type)
  1425. << TheCall->getDirectCallee()
  1426. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  1427. return true;
  1428. }
  1429. // Sixth argument is always passed as a pointer to clk_event_t.
  1430. if (!Arg5->isNullPointerConstant(S.Context,
  1431. Expr::NPC_ValueDependentIsNotNull) &&
  1432. !(Arg5->getType()->isPointerType() &&
  1433. Arg5->getType()->getPointeeType()->isClkEventT())) {
  1434. S.Diag(TheCall->getArg(5)->getBeginLoc(),
  1435. diag::err_opencl_builtin_expected_type)
  1436. << TheCall->getDirectCallee()
  1437. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  1438. return true;
  1439. }
  1440. if (NumArgs == 7)
  1441. return false;
  1442. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  1443. }
  1444. // None of the specific case has been detected, give generic error
  1445. S.Diag(TheCall->getBeginLoc(),
  1446. diag::err_opencl_enqueue_kernel_incorrect_args);
  1447. return true;
  1448. }
  1449. /// Returns OpenCL access qual.
  1450. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  1451. return D->getAttr<OpenCLAccessAttr>();
  1452. }
  1453. /// Returns true if pipe element type is different from the pointer.
  1454. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  1455. const Expr *Arg0 = Call->getArg(0);
  1456. // First argument type should always be pipe.
  1457. if (!Arg0->getType()->isPipeType()) {
  1458. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  1459. << Call->getDirectCallee() << Arg0->getSourceRange();
  1460. return true;
  1461. }
  1462. OpenCLAccessAttr *AccessQual =
  1463. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  1464. // Validates the access qualifier is compatible with the call.
  1465. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  1466. // read_only and write_only, and assumed to be read_only if no qualifier is
  1467. // specified.
  1468. switch (Call->getDirectCallee()->getBuiltinID()) {
  1469. case Builtin::BIread_pipe:
  1470. case Builtin::BIreserve_read_pipe:
  1471. case Builtin::BIcommit_read_pipe:
  1472. case Builtin::BIwork_group_reserve_read_pipe:
  1473. case Builtin::BIsub_group_reserve_read_pipe:
  1474. case Builtin::BIwork_group_commit_read_pipe:
  1475. case Builtin::BIsub_group_commit_read_pipe:
  1476. if (!(!AccessQual || AccessQual->isReadOnly())) {
  1477. S.Diag(Arg0->getBeginLoc(),
  1478. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  1479. << "read_only" << Arg0->getSourceRange();
  1480. return true;
  1481. }
  1482. break;
  1483. case Builtin::BIwrite_pipe:
  1484. case Builtin::BIreserve_write_pipe:
  1485. case Builtin::BIcommit_write_pipe:
  1486. case Builtin::BIwork_group_reserve_write_pipe:
  1487. case Builtin::BIsub_group_reserve_write_pipe:
  1488. case Builtin::BIwork_group_commit_write_pipe:
  1489. case Builtin::BIsub_group_commit_write_pipe:
  1490. if (!(AccessQual && AccessQual->isWriteOnly())) {
  1491. S.Diag(Arg0->getBeginLoc(),
  1492. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  1493. << "write_only" << Arg0->getSourceRange();
  1494. return true;
  1495. }
  1496. break;
  1497. default:
  1498. break;
  1499. }
  1500. return false;
  1501. }
  1502. /// Returns true if pipe element type is different from the pointer.
  1503. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  1504. const Expr *Arg0 = Call->getArg(0);
  1505. const Expr *ArgIdx = Call->getArg(Idx);
  1506. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  1507. const QualType EltTy = PipeTy->getElementType();
  1508. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  1509. // The Idx argument should be a pointer and the type of the pointer and
  1510. // the type of pipe element should also be the same.
  1511. if (!ArgTy ||
  1512. !S.Context.hasSameType(
  1513. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  1514. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  1515. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  1516. << ArgIdx->getType() << ArgIdx->getSourceRange();
  1517. return true;
  1518. }
  1519. return false;
  1520. }
  1521. // Performs semantic analysis for the read/write_pipe call.
  1522. // \param S Reference to the semantic analyzer.
  1523. // \param Call A pointer to the builtin call.
  1524. // \return True if a semantic error has been found, false otherwise.
  1525. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  1526. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  1527. // functions have two forms.
  1528. switch (Call->getNumArgs()) {
  1529. case 2:
  1530. if (checkOpenCLPipeArg(S, Call))
  1531. return true;
  1532. // The call with 2 arguments should be
  1533. // read/write_pipe(pipe T, T*).
  1534. // Check packet type T.
  1535. if (checkOpenCLPipePacketType(S, Call, 1))
  1536. return true;
  1537. break;
  1538. case 4: {
  1539. if (checkOpenCLPipeArg(S, Call))
  1540. return true;
  1541. // The call with 4 arguments should be
  1542. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  1543. // Check reserve_id_t.
  1544. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  1545. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  1546. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  1547. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  1548. return true;
  1549. }
  1550. // Check the index.
  1551. const Expr *Arg2 = Call->getArg(2);
  1552. if (!Arg2->getType()->isIntegerType() &&
  1553. !Arg2->getType()->isUnsignedIntegerType()) {
  1554. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  1555. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  1556. << Arg2->getType() << Arg2->getSourceRange();
  1557. return true;
  1558. }
  1559. // Check packet type T.
  1560. if (checkOpenCLPipePacketType(S, Call, 3))
  1561. return true;
  1562. } break;
  1563. default:
  1564. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
  1565. << Call->getDirectCallee() << Call->getSourceRange();
  1566. return true;
  1567. }
  1568. return false;
  1569. }
  1570. // Performs a semantic analysis on the {work_group_/sub_group_
  1571. // /_}reserve_{read/write}_pipe
  1572. // \param S Reference to the semantic analyzer.
  1573. // \param Call The call to the builtin function to be analyzed.
  1574. // \return True if a semantic error was found, false otherwise.
  1575. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  1576. if (checkArgCount(S, Call, 2))
  1577. return true;
  1578. if (checkOpenCLPipeArg(S, Call))
  1579. return true;
  1580. // Check the reserve size.
  1581. if (!Call->getArg(1)->getType()->isIntegerType() &&
  1582. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  1583. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  1584. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  1585. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  1586. return true;
  1587. }
  1588. // Since return type of reserve_read/write_pipe built-in function is
  1589. // reserve_id_t, which is not defined in the builtin def file , we used int
  1590. // as return type and need to override the return type of these functions.
  1591. Call->setType(S.Context.OCLReserveIDTy);
  1592. return false;
  1593. }
  1594. // Performs a semantic analysis on {work_group_/sub_group_
  1595. // /_}commit_{read/write}_pipe
  1596. // \param S Reference to the semantic analyzer.
  1597. // \param Call The call to the builtin function to be analyzed.
  1598. // \return True if a semantic error was found, false otherwise.
  1599. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  1600. if (checkArgCount(S, Call, 2))
  1601. return true;
  1602. if (checkOpenCLPipeArg(S, Call))
  1603. return true;
  1604. // Check reserve_id_t.
  1605. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  1606. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  1607. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  1608. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  1609. return true;
  1610. }
  1611. return false;
  1612. }
  1613. // Performs a semantic analysis on the call to built-in Pipe
  1614. // Query Functions.
  1615. // \param S Reference to the semantic analyzer.
  1616. // \param Call The call to the builtin function to be analyzed.
  1617. // \return True if a semantic error was found, false otherwise.
  1618. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  1619. if (checkArgCount(S, Call, 1))
  1620. return true;
  1621. if (!Call->getArg(0)->getType()->isPipeType()) {
  1622. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  1623. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  1624. return true;
  1625. }
  1626. return false;
  1627. }
  1628. // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  1629. // Performs semantic analysis for the to_global/local/private call.
  1630. // \param S Reference to the semantic analyzer.
  1631. // \param BuiltinID ID of the builtin function.
  1632. // \param Call A pointer to the builtin call.
  1633. // \return True if a semantic error has been found, false otherwise.
  1634. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  1635. CallExpr *Call) {
  1636. if (checkArgCount(S, Call, 1))
  1637. return true;
  1638. auto RT = Call->getArg(0)->getType();
  1639. if (!RT->isPointerType() || RT->getPointeeType()
  1640. .getAddressSpace() == LangAS::opencl_constant) {
  1641. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
  1642. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  1643. return true;
  1644. }
  1645. if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
  1646. S.Diag(Call->getArg(0)->getBeginLoc(),
  1647. diag::warn_opencl_generic_address_space_arg)
  1648. << Call->getDirectCallee()->getNameInfo().getAsString()
  1649. << Call->getArg(0)->getSourceRange();
  1650. }
  1651. RT = RT->getPointeeType();
  1652. auto Qual = RT.getQualifiers();
  1653. switch (BuiltinID) {
  1654. case Builtin::BIto_global:
  1655. Qual.setAddressSpace(LangAS::opencl_global);
  1656. break;
  1657. case Builtin::BIto_local:
  1658. Qual.setAddressSpace(LangAS::opencl_local);
  1659. break;
  1660. case Builtin::BIto_private:
  1661. Qual.setAddressSpace(LangAS::opencl_private);
  1662. break;
  1663. default:
  1664. llvm_unreachable("Invalid builtin function");
  1665. }
  1666. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  1667. RT.getUnqualifiedType(), Qual)));
  1668. return false;
  1669. }
  1670. static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
  1671. if (checkArgCount(S, TheCall, 1))
  1672. return ExprError();
  1673. // Compute __builtin_launder's parameter type from the argument.
  1674. // The parameter type is:
  1675. // * The type of the argument if it's not an array or function type,
  1676. // Otherwise,
  1677. // * The decayed argument type.
  1678. QualType ParamTy = [&]() {
  1679. QualType ArgTy = TheCall->getArg(0)->getType();
  1680. if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
  1681. return S.Context.getPointerType(Ty->getElementType());
  1682. if (ArgTy->isFunctionType()) {
  1683. return S.Context.getPointerType(ArgTy);
  1684. }
  1685. return ArgTy;
  1686. }();
  1687. TheCall->setType(ParamTy);
  1688. auto DiagSelect = [&]() -> std::optional<unsigned> {
  1689. if (!ParamTy->isPointerType())
  1690. return 0;
  1691. if (ParamTy->isFunctionPointerType())
  1692. return 1;
  1693. if (ParamTy->isVoidPointerType())
  1694. return 2;
  1695. return std::optional<unsigned>{};
  1696. }();
  1697. if (DiagSelect) {
  1698. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
  1699. << *DiagSelect << TheCall->getSourceRange();
  1700. return ExprError();
  1701. }
  1702. // We either have an incomplete class type, or we have a class template
  1703. // whose instantiation has not been forced. Example:
  1704. //
  1705. // template <class T> struct Foo { T value; };
  1706. // Foo<int> *p = nullptr;
  1707. // auto *d = __builtin_launder(p);
  1708. if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
  1709. diag::err_incomplete_type))
  1710. return ExprError();
  1711. assert(ParamTy->getPointeeType()->isObjectType() &&
  1712. "Unhandled non-object pointer case");
  1713. InitializedEntity Entity =
  1714. InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
  1715. ExprResult Arg =
  1716. S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
  1717. if (Arg.isInvalid())
  1718. return ExprError();
  1719. TheCall->setArg(0, Arg.get());
  1720. return TheCall;
  1721. }
  1722. // Emit an error and return true if the current object format type is in the
  1723. // list of unsupported types.
  1724. static bool CheckBuiltinTargetNotInUnsupported(
  1725. Sema &S, unsigned BuiltinID, CallExpr *TheCall,
  1726. ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
  1727. llvm::Triple::ObjectFormatType CurObjFormat =
  1728. S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
  1729. if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
  1730. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  1731. << TheCall->getSourceRange();
  1732. return true;
  1733. }
  1734. return false;
  1735. }
  1736. // Emit an error and return true if the current architecture is not in the list
  1737. // of supported architectures.
  1738. static bool
  1739. CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
  1740. ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
  1741. llvm::Triple::ArchType CurArch =
  1742. S.getASTContext().getTargetInfo().getTriple().getArch();
  1743. if (llvm::is_contained(SupportedArchs, CurArch))
  1744. return false;
  1745. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  1746. << TheCall->getSourceRange();
  1747. return true;
  1748. }
  1749. static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
  1750. SourceLocation CallSiteLoc);
  1751. bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
  1752. CallExpr *TheCall) {
  1753. switch (TI.getTriple().getArch()) {
  1754. default:
  1755. // Some builtins don't require additional checking, so just consider these
  1756. // acceptable.
  1757. return false;
  1758. case llvm::Triple::arm:
  1759. case llvm::Triple::armeb:
  1760. case llvm::Triple::thumb:
  1761. case llvm::Triple::thumbeb:
  1762. return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
  1763. case llvm::Triple::aarch64:
  1764. case llvm::Triple::aarch64_32:
  1765. case llvm::Triple::aarch64_be:
  1766. return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
  1767. case llvm::Triple::bpfeb:
  1768. case llvm::Triple::bpfel:
  1769. return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
  1770. case llvm::Triple::hexagon:
  1771. return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
  1772. case llvm::Triple::mips:
  1773. case llvm::Triple::mipsel:
  1774. case llvm::Triple::mips64:
  1775. case llvm::Triple::mips64el:
  1776. return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
  1777. case llvm::Triple::systemz:
  1778. return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
  1779. case llvm::Triple::x86:
  1780. case llvm::Triple::x86_64:
  1781. return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
  1782. case llvm::Triple::ppc:
  1783. case llvm::Triple::ppcle:
  1784. case llvm::Triple::ppc64:
  1785. case llvm::Triple::ppc64le:
  1786. return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
  1787. case llvm::Triple::amdgcn:
  1788. return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
  1789. case llvm::Triple::riscv32:
  1790. case llvm::Triple::riscv64:
  1791. return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
  1792. case llvm::Triple::loongarch32:
  1793. case llvm::Triple::loongarch64:
  1794. return CheckLoongArchBuiltinFunctionCall(TI, BuiltinID, TheCall);
  1795. }
  1796. }
  1797. // Check if \p Ty is a valid type for the elementwise math builtins. If it is
  1798. // not a valid type, emit an error message and return true. Otherwise return
  1799. // false.
  1800. static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
  1801. QualType Ty) {
  1802. if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
  1803. return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
  1804. << 1 << /* vector, integer or float ty*/ 0 << Ty;
  1805. }
  1806. return false;
  1807. }
  1808. static bool checkFPMathBuiltinElementType(Sema &S, SourceLocation Loc,
  1809. QualType ArgTy, int ArgIndex) {
  1810. QualType EltTy = ArgTy;
  1811. if (auto *VecTy = EltTy->getAs<VectorType>())
  1812. EltTy = VecTy->getElementType();
  1813. if (!EltTy->isRealFloatingType()) {
  1814. return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
  1815. << ArgIndex << /* vector or float ty*/ 5 << ArgTy;
  1816. }
  1817. return false;
  1818. }
  1819. ExprResult
  1820. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  1821. CallExpr *TheCall) {
  1822. ExprResult TheCallResult(TheCall);
  1823. // Find out if any arguments are required to be integer constant expressions.
  1824. unsigned ICEArguments = 0;
  1825. ASTContext::GetBuiltinTypeError Error;
  1826. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  1827. if (Error != ASTContext::GE_None)
  1828. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  1829. // If any arguments are required to be ICE's, check and diagnose.
  1830. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  1831. // Skip arguments not required to be ICE's.
  1832. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  1833. llvm::APSInt Result;
  1834. // If we don't have enough arguments, continue so we can issue better
  1835. // diagnostic in checkArgCount(...)
  1836. if (ArgNo < TheCall->getNumArgs() &&
  1837. SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  1838. return true;
  1839. ICEArguments &= ~(1 << ArgNo);
  1840. }
  1841. switch (BuiltinID) {
  1842. case Builtin::BI__builtin___CFStringMakeConstantString:
  1843. // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
  1844. // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
  1845. if (CheckBuiltinTargetNotInUnsupported(
  1846. *this, BuiltinID, TheCall,
  1847. {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
  1848. return ExprError();
  1849. assert(TheCall->getNumArgs() == 1 &&
  1850. "Wrong # arguments to builtin CFStringMakeConstantString");
  1851. if (CheckObjCString(TheCall->getArg(0)))
  1852. return ExprError();
  1853. break;
  1854. case Builtin::BI__builtin_ms_va_start:
  1855. case Builtin::BI__builtin_stdarg_start:
  1856. case Builtin::BI__builtin_va_start:
  1857. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  1858. return ExprError();
  1859. break;
  1860. case Builtin::BI__va_start: {
  1861. switch (Context.getTargetInfo().getTriple().getArch()) {
  1862. case llvm::Triple::aarch64:
  1863. case llvm::Triple::arm:
  1864. case llvm::Triple::thumb:
  1865. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  1866. return ExprError();
  1867. break;
  1868. default:
  1869. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  1870. return ExprError();
  1871. break;
  1872. }
  1873. break;
  1874. }
  1875. // The acquire, release, and no fence variants are ARM and AArch64 only.
  1876. case Builtin::BI_interlockedbittestandset_acq:
  1877. case Builtin::BI_interlockedbittestandset_rel:
  1878. case Builtin::BI_interlockedbittestandset_nf:
  1879. case Builtin::BI_interlockedbittestandreset_acq:
  1880. case Builtin::BI_interlockedbittestandreset_rel:
  1881. case Builtin::BI_interlockedbittestandreset_nf:
  1882. if (CheckBuiltinTargetInSupported(
  1883. *this, BuiltinID, TheCall,
  1884. {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
  1885. return ExprError();
  1886. break;
  1887. // The 64-bit bittest variants are x64, ARM, and AArch64 only.
  1888. case Builtin::BI_bittest64:
  1889. case Builtin::BI_bittestandcomplement64:
  1890. case Builtin::BI_bittestandreset64:
  1891. case Builtin::BI_bittestandset64:
  1892. case Builtin::BI_interlockedbittestandreset64:
  1893. case Builtin::BI_interlockedbittestandset64:
  1894. if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
  1895. {llvm::Triple::x86_64, llvm::Triple::arm,
  1896. llvm::Triple::thumb,
  1897. llvm::Triple::aarch64}))
  1898. return ExprError();
  1899. break;
  1900. case Builtin::BI__builtin_isgreater:
  1901. case Builtin::BI__builtin_isgreaterequal:
  1902. case Builtin::BI__builtin_isless:
  1903. case Builtin::BI__builtin_islessequal:
  1904. case Builtin::BI__builtin_islessgreater:
  1905. case Builtin::BI__builtin_isunordered:
  1906. if (SemaBuiltinUnorderedCompare(TheCall))
  1907. return ExprError();
  1908. break;
  1909. case Builtin::BI__builtin_fpclassify:
  1910. if (SemaBuiltinFPClassification(TheCall, 6))
  1911. return ExprError();
  1912. break;
  1913. case Builtin::BI__builtin_isfinite:
  1914. case Builtin::BI__builtin_isinf:
  1915. case Builtin::BI__builtin_isinf_sign:
  1916. case Builtin::BI__builtin_isnan:
  1917. case Builtin::BI__builtin_isnormal:
  1918. case Builtin::BI__builtin_signbit:
  1919. case Builtin::BI__builtin_signbitf:
  1920. case Builtin::BI__builtin_signbitl:
  1921. if (SemaBuiltinFPClassification(TheCall, 1))
  1922. return ExprError();
  1923. break;
  1924. case Builtin::BI__builtin_shufflevector:
  1925. return SemaBuiltinShuffleVector(TheCall);
  1926. // TheCall will be freed by the smart pointer here, but that's fine, since
  1927. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  1928. case Builtin::BI__builtin_prefetch:
  1929. if (SemaBuiltinPrefetch(TheCall))
  1930. return ExprError();
  1931. break;
  1932. case Builtin::BI__builtin_alloca_with_align:
  1933. case Builtin::BI__builtin_alloca_with_align_uninitialized:
  1934. if (SemaBuiltinAllocaWithAlign(TheCall))
  1935. return ExprError();
  1936. [[fallthrough]];
  1937. case Builtin::BI__builtin_alloca:
  1938. case Builtin::BI__builtin_alloca_uninitialized:
  1939. Diag(TheCall->getBeginLoc(), diag::warn_alloca)
  1940. << TheCall->getDirectCallee();
  1941. break;
  1942. case Builtin::BI__arithmetic_fence:
  1943. if (SemaBuiltinArithmeticFence(TheCall))
  1944. return ExprError();
  1945. break;
  1946. case Builtin::BI__assume:
  1947. case Builtin::BI__builtin_assume:
  1948. if (SemaBuiltinAssume(TheCall))
  1949. return ExprError();
  1950. break;
  1951. case Builtin::BI__builtin_assume_aligned:
  1952. if (SemaBuiltinAssumeAligned(TheCall))
  1953. return ExprError();
  1954. break;
  1955. case Builtin::BI__builtin_dynamic_object_size:
  1956. case Builtin::BI__builtin_object_size:
  1957. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  1958. return ExprError();
  1959. break;
  1960. case Builtin::BI__builtin_longjmp:
  1961. if (SemaBuiltinLongjmp(TheCall))
  1962. return ExprError();
  1963. break;
  1964. case Builtin::BI__builtin_setjmp:
  1965. if (SemaBuiltinSetjmp(TheCall))
  1966. return ExprError();
  1967. break;
  1968. case Builtin::BI__builtin_classify_type:
  1969. if (checkArgCount(*this, TheCall, 1)) return true;
  1970. TheCall->setType(Context.IntTy);
  1971. break;
  1972. case Builtin::BI__builtin_complex:
  1973. if (SemaBuiltinComplex(TheCall))
  1974. return ExprError();
  1975. break;
  1976. case Builtin::BI__builtin_constant_p: {
  1977. if (checkArgCount(*this, TheCall, 1)) return true;
  1978. ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
  1979. if (Arg.isInvalid()) return true;
  1980. TheCall->setArg(0, Arg.get());
  1981. TheCall->setType(Context.IntTy);
  1982. break;
  1983. }
  1984. case Builtin::BI__builtin_launder:
  1985. return SemaBuiltinLaunder(*this, TheCall);
  1986. case Builtin::BI__sync_fetch_and_add:
  1987. case Builtin::BI__sync_fetch_and_add_1:
  1988. case Builtin::BI__sync_fetch_and_add_2:
  1989. case Builtin::BI__sync_fetch_and_add_4:
  1990. case Builtin::BI__sync_fetch_and_add_8:
  1991. case Builtin::BI__sync_fetch_and_add_16:
  1992. case Builtin::BI__sync_fetch_and_sub:
  1993. case Builtin::BI__sync_fetch_and_sub_1:
  1994. case Builtin::BI__sync_fetch_and_sub_2:
  1995. case Builtin::BI__sync_fetch_and_sub_4:
  1996. case Builtin::BI__sync_fetch_and_sub_8:
  1997. case Builtin::BI__sync_fetch_and_sub_16:
  1998. case Builtin::BI__sync_fetch_and_or:
  1999. case Builtin::BI__sync_fetch_and_or_1:
  2000. case Builtin::BI__sync_fetch_and_or_2:
  2001. case Builtin::BI__sync_fetch_and_or_4:
  2002. case Builtin::BI__sync_fetch_and_or_8:
  2003. case Builtin::BI__sync_fetch_and_or_16:
  2004. case Builtin::BI__sync_fetch_and_and:
  2005. case Builtin::BI__sync_fetch_and_and_1:
  2006. case Builtin::BI__sync_fetch_and_and_2:
  2007. case Builtin::BI__sync_fetch_and_and_4:
  2008. case Builtin::BI__sync_fetch_and_and_8:
  2009. case Builtin::BI__sync_fetch_and_and_16:
  2010. case Builtin::BI__sync_fetch_and_xor:
  2011. case Builtin::BI__sync_fetch_and_xor_1:
  2012. case Builtin::BI__sync_fetch_and_xor_2:
  2013. case Builtin::BI__sync_fetch_and_xor_4:
  2014. case Builtin::BI__sync_fetch_and_xor_8:
  2015. case Builtin::BI__sync_fetch_and_xor_16:
  2016. case Builtin::BI__sync_fetch_and_nand:
  2017. case Builtin::BI__sync_fetch_and_nand_1:
  2018. case Builtin::BI__sync_fetch_and_nand_2:
  2019. case Builtin::BI__sync_fetch_and_nand_4:
  2020. case Builtin::BI__sync_fetch_and_nand_8:
  2021. case Builtin::BI__sync_fetch_and_nand_16:
  2022. case Builtin::BI__sync_add_and_fetch:
  2023. case Builtin::BI__sync_add_and_fetch_1:
  2024. case Builtin::BI__sync_add_and_fetch_2:
  2025. case Builtin::BI__sync_add_and_fetch_4:
  2026. case Builtin::BI__sync_add_and_fetch_8:
  2027. case Builtin::BI__sync_add_and_fetch_16:
  2028. case Builtin::BI__sync_sub_and_fetch:
  2029. case Builtin::BI__sync_sub_and_fetch_1:
  2030. case Builtin::BI__sync_sub_and_fetch_2:
  2031. case Builtin::BI__sync_sub_and_fetch_4:
  2032. case Builtin::BI__sync_sub_and_fetch_8:
  2033. case Builtin::BI__sync_sub_and_fetch_16:
  2034. case Builtin::BI__sync_and_and_fetch:
  2035. case Builtin::BI__sync_and_and_fetch_1:
  2036. case Builtin::BI__sync_and_and_fetch_2:
  2037. case Builtin::BI__sync_and_and_fetch_4:
  2038. case Builtin::BI__sync_and_and_fetch_8:
  2039. case Builtin::BI__sync_and_and_fetch_16:
  2040. case Builtin::BI__sync_or_and_fetch:
  2041. case Builtin::BI__sync_or_and_fetch_1:
  2042. case Builtin::BI__sync_or_and_fetch_2:
  2043. case Builtin::BI__sync_or_and_fetch_4:
  2044. case Builtin::BI__sync_or_and_fetch_8:
  2045. case Builtin::BI__sync_or_and_fetch_16:
  2046. case Builtin::BI__sync_xor_and_fetch:
  2047. case Builtin::BI__sync_xor_and_fetch_1:
  2048. case Builtin::BI__sync_xor_and_fetch_2:
  2049. case Builtin::BI__sync_xor_and_fetch_4:
  2050. case Builtin::BI__sync_xor_and_fetch_8:
  2051. case Builtin::BI__sync_xor_and_fetch_16:
  2052. case Builtin::BI__sync_nand_and_fetch:
  2053. case Builtin::BI__sync_nand_and_fetch_1:
  2054. case Builtin::BI__sync_nand_and_fetch_2:
  2055. case Builtin::BI__sync_nand_and_fetch_4:
  2056. case Builtin::BI__sync_nand_and_fetch_8:
  2057. case Builtin::BI__sync_nand_and_fetch_16:
  2058. case Builtin::BI__sync_val_compare_and_swap:
  2059. case Builtin::BI__sync_val_compare_and_swap_1:
  2060. case Builtin::BI__sync_val_compare_and_swap_2:
  2061. case Builtin::BI__sync_val_compare_and_swap_4:
  2062. case Builtin::BI__sync_val_compare_and_swap_8:
  2063. case Builtin::BI__sync_val_compare_and_swap_16:
  2064. case Builtin::BI__sync_bool_compare_and_swap:
  2065. case Builtin::BI__sync_bool_compare_and_swap_1:
  2066. case Builtin::BI__sync_bool_compare_and_swap_2:
  2067. case Builtin::BI__sync_bool_compare_and_swap_4:
  2068. case Builtin::BI__sync_bool_compare_and_swap_8:
  2069. case Builtin::BI__sync_bool_compare_and_swap_16:
  2070. case Builtin::BI__sync_lock_test_and_set:
  2071. case Builtin::BI__sync_lock_test_and_set_1:
  2072. case Builtin::BI__sync_lock_test_and_set_2:
  2073. case Builtin::BI__sync_lock_test_and_set_4:
  2074. case Builtin::BI__sync_lock_test_and_set_8:
  2075. case Builtin::BI__sync_lock_test_and_set_16:
  2076. case Builtin::BI__sync_lock_release:
  2077. case Builtin::BI__sync_lock_release_1:
  2078. case Builtin::BI__sync_lock_release_2:
  2079. case Builtin::BI__sync_lock_release_4:
  2080. case Builtin::BI__sync_lock_release_8:
  2081. case Builtin::BI__sync_lock_release_16:
  2082. case Builtin::BI__sync_swap:
  2083. case Builtin::BI__sync_swap_1:
  2084. case Builtin::BI__sync_swap_2:
  2085. case Builtin::BI__sync_swap_4:
  2086. case Builtin::BI__sync_swap_8:
  2087. case Builtin::BI__sync_swap_16:
  2088. return SemaBuiltinAtomicOverloaded(TheCallResult);
  2089. case Builtin::BI__sync_synchronize:
  2090. Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
  2091. << TheCall->getCallee()->getSourceRange();
  2092. break;
  2093. case Builtin::BI__builtin_nontemporal_load:
  2094. case Builtin::BI__builtin_nontemporal_store:
  2095. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  2096. case Builtin::BI__builtin_memcpy_inline: {
  2097. clang::Expr *SizeOp = TheCall->getArg(2);
  2098. // We warn about copying to or from `nullptr` pointers when `size` is
  2099. // greater than 0. When `size` is value dependent we cannot evaluate its
  2100. // value so we bail out.
  2101. if (SizeOp->isValueDependent())
  2102. break;
  2103. if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
  2104. CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
  2105. CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
  2106. }
  2107. break;
  2108. }
  2109. case Builtin::BI__builtin_memset_inline: {
  2110. clang::Expr *SizeOp = TheCall->getArg(2);
  2111. // We warn about filling to `nullptr` pointers when `size` is greater than
  2112. // 0. When `size` is value dependent we cannot evaluate its value so we bail
  2113. // out.
  2114. if (SizeOp->isValueDependent())
  2115. break;
  2116. if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
  2117. CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
  2118. break;
  2119. }
  2120. #define BUILTIN(ID, TYPE, ATTRS)
  2121. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  2122. case Builtin::BI##ID: \
  2123. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  2124. #include "clang/Basic/Builtins.def"
  2125. case Builtin::BI__annotation:
  2126. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  2127. return ExprError();
  2128. break;
  2129. case Builtin::BI__builtin_annotation:
  2130. if (SemaBuiltinAnnotation(*this, TheCall))
  2131. return ExprError();
  2132. break;
  2133. case Builtin::BI__builtin_addressof:
  2134. if (SemaBuiltinAddressof(*this, TheCall))
  2135. return ExprError();
  2136. break;
  2137. case Builtin::BI__builtin_function_start:
  2138. if (SemaBuiltinFunctionStart(*this, TheCall))
  2139. return ExprError();
  2140. break;
  2141. case Builtin::BI__builtin_is_aligned:
  2142. case Builtin::BI__builtin_align_up:
  2143. case Builtin::BI__builtin_align_down:
  2144. if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
  2145. return ExprError();
  2146. break;
  2147. case Builtin::BI__builtin_add_overflow:
  2148. case Builtin::BI__builtin_sub_overflow:
  2149. case Builtin::BI__builtin_mul_overflow:
  2150. if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
  2151. return ExprError();
  2152. break;
  2153. case Builtin::BI__builtin_operator_new:
  2154. case Builtin::BI__builtin_operator_delete: {
  2155. bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
  2156. ExprResult Res =
  2157. SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
  2158. if (Res.isInvalid())
  2159. CorrectDelayedTyposInExpr(TheCallResult.get());
  2160. return Res;
  2161. }
  2162. case Builtin::BI__builtin_dump_struct:
  2163. return SemaBuiltinDumpStruct(*this, TheCall);
  2164. case Builtin::BI__builtin_expect_with_probability: {
  2165. // We first want to ensure we are called with 3 arguments
  2166. if (checkArgCount(*this, TheCall, 3))
  2167. return ExprError();
  2168. // then check probability is constant float in range [0.0, 1.0]
  2169. const Expr *ProbArg = TheCall->getArg(2);
  2170. SmallVector<PartialDiagnosticAt, 8> Notes;
  2171. Expr::EvalResult Eval;
  2172. Eval.Diag = &Notes;
  2173. if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
  2174. !Eval.Val.isFloat()) {
  2175. Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
  2176. << ProbArg->getSourceRange();
  2177. for (const PartialDiagnosticAt &PDiag : Notes)
  2178. Diag(PDiag.first, PDiag.second);
  2179. return ExprError();
  2180. }
  2181. llvm::APFloat Probability = Eval.Val.getFloat();
  2182. bool LoseInfo = false;
  2183. Probability.convert(llvm::APFloat::IEEEdouble(),
  2184. llvm::RoundingMode::Dynamic, &LoseInfo);
  2185. if (!(Probability >= llvm::APFloat(0.0) &&
  2186. Probability <= llvm::APFloat(1.0))) {
  2187. Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
  2188. << ProbArg->getSourceRange();
  2189. return ExprError();
  2190. }
  2191. break;
  2192. }
  2193. case Builtin::BI__builtin_preserve_access_index:
  2194. if (SemaBuiltinPreserveAI(*this, TheCall))
  2195. return ExprError();
  2196. break;
  2197. case Builtin::BI__builtin_call_with_static_chain:
  2198. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  2199. return ExprError();
  2200. break;
  2201. case Builtin::BI__exception_code:
  2202. case Builtin::BI_exception_code:
  2203. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  2204. diag::err_seh___except_block))
  2205. return ExprError();
  2206. break;
  2207. case Builtin::BI__exception_info:
  2208. case Builtin::BI_exception_info:
  2209. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  2210. diag::err_seh___except_filter))
  2211. return ExprError();
  2212. break;
  2213. case Builtin::BI__GetExceptionInfo:
  2214. if (checkArgCount(*this, TheCall, 1))
  2215. return ExprError();
  2216. if (CheckCXXThrowOperand(
  2217. TheCall->getBeginLoc(),
  2218. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  2219. TheCall))
  2220. return ExprError();
  2221. TheCall->setType(Context.VoidPtrTy);
  2222. break;
  2223. case Builtin::BIaddressof:
  2224. case Builtin::BI__addressof:
  2225. case Builtin::BIforward:
  2226. case Builtin::BImove:
  2227. case Builtin::BImove_if_noexcept:
  2228. case Builtin::BIas_const: {
  2229. // These are all expected to be of the form
  2230. // T &/&&/* f(U &/&&)
  2231. // where T and U only differ in qualification.
  2232. if (checkArgCount(*this, TheCall, 1))
  2233. return ExprError();
  2234. QualType Param = FDecl->getParamDecl(0)->getType();
  2235. QualType Result = FDecl->getReturnType();
  2236. bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
  2237. BuiltinID == Builtin::BI__addressof;
  2238. if (!(Param->isReferenceType() &&
  2239. (ReturnsPointer ? Result->isAnyPointerType()
  2240. : Result->isReferenceType()) &&
  2241. Context.hasSameUnqualifiedType(Param->getPointeeType(),
  2242. Result->getPointeeType()))) {
  2243. Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
  2244. << FDecl;
  2245. return ExprError();
  2246. }
  2247. break;
  2248. }
  2249. // OpenCL v2.0, s6.13.16 - Pipe functions
  2250. case Builtin::BIread_pipe:
  2251. case Builtin::BIwrite_pipe:
  2252. // Since those two functions are declared with var args, we need a semantic
  2253. // check for the argument.
  2254. if (SemaBuiltinRWPipe(*this, TheCall))
  2255. return ExprError();
  2256. break;
  2257. case Builtin::BIreserve_read_pipe:
  2258. case Builtin::BIreserve_write_pipe:
  2259. case Builtin::BIwork_group_reserve_read_pipe:
  2260. case Builtin::BIwork_group_reserve_write_pipe:
  2261. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  2262. return ExprError();
  2263. break;
  2264. case Builtin::BIsub_group_reserve_read_pipe:
  2265. case Builtin::BIsub_group_reserve_write_pipe:
  2266. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  2267. SemaBuiltinReserveRWPipe(*this, TheCall))
  2268. return ExprError();
  2269. break;
  2270. case Builtin::BIcommit_read_pipe:
  2271. case Builtin::BIcommit_write_pipe:
  2272. case Builtin::BIwork_group_commit_read_pipe:
  2273. case Builtin::BIwork_group_commit_write_pipe:
  2274. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  2275. return ExprError();
  2276. break;
  2277. case Builtin::BIsub_group_commit_read_pipe:
  2278. case Builtin::BIsub_group_commit_write_pipe:
  2279. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  2280. SemaBuiltinCommitRWPipe(*this, TheCall))
  2281. return ExprError();
  2282. break;
  2283. case Builtin::BIget_pipe_num_packets:
  2284. case Builtin::BIget_pipe_max_packets:
  2285. if (SemaBuiltinPipePackets(*this, TheCall))
  2286. return ExprError();
  2287. break;
  2288. case Builtin::BIto_global:
  2289. case Builtin::BIto_local:
  2290. case Builtin::BIto_private:
  2291. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  2292. return ExprError();
  2293. break;
  2294. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  2295. case Builtin::BIenqueue_kernel:
  2296. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  2297. return ExprError();
  2298. break;
  2299. case Builtin::BIget_kernel_work_group_size:
  2300. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  2301. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  2302. return ExprError();
  2303. break;
  2304. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  2305. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  2306. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  2307. return ExprError();
  2308. break;
  2309. case Builtin::BI__builtin_os_log_format:
  2310. Cleanup.setExprNeedsCleanups(true);
  2311. [[fallthrough]];
  2312. case Builtin::BI__builtin_os_log_format_buffer_size:
  2313. if (SemaBuiltinOSLogFormat(TheCall))
  2314. return ExprError();
  2315. break;
  2316. case Builtin::BI__builtin_frame_address:
  2317. case Builtin::BI__builtin_return_address: {
  2318. if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
  2319. return ExprError();
  2320. // -Wframe-address warning if non-zero passed to builtin
  2321. // return/frame address.
  2322. Expr::EvalResult Result;
  2323. if (!TheCall->getArg(0)->isValueDependent() &&
  2324. TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
  2325. Result.Val.getInt() != 0)
  2326. Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
  2327. << ((BuiltinID == Builtin::BI__builtin_return_address)
  2328. ? "__builtin_return_address"
  2329. : "__builtin_frame_address")
  2330. << TheCall->getSourceRange();
  2331. break;
  2332. }
  2333. // __builtin_elementwise_abs restricts the element type to signed integers or
  2334. // floating point types only.
  2335. case Builtin::BI__builtin_elementwise_abs: {
  2336. if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
  2337. return ExprError();
  2338. QualType ArgTy = TheCall->getArg(0)->getType();
  2339. QualType EltTy = ArgTy;
  2340. if (auto *VecTy = EltTy->getAs<VectorType>())
  2341. EltTy = VecTy->getElementType();
  2342. if (EltTy->isUnsignedIntegerType()) {
  2343. Diag(TheCall->getArg(0)->getBeginLoc(),
  2344. diag::err_builtin_invalid_arg_type)
  2345. << 1 << /* signed integer or float ty*/ 3 << ArgTy;
  2346. return ExprError();
  2347. }
  2348. break;
  2349. }
  2350. // These builtins restrict the element type to floating point
  2351. // types only.
  2352. case Builtin::BI__builtin_elementwise_ceil:
  2353. case Builtin::BI__builtin_elementwise_cos:
  2354. case Builtin::BI__builtin_elementwise_floor:
  2355. case Builtin::BI__builtin_elementwise_roundeven:
  2356. case Builtin::BI__builtin_elementwise_sin:
  2357. case Builtin::BI__builtin_elementwise_trunc:
  2358. case Builtin::BI__builtin_elementwise_canonicalize: {
  2359. if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
  2360. return ExprError();
  2361. QualType ArgTy = TheCall->getArg(0)->getType();
  2362. QualType EltTy = ArgTy;
  2363. if (auto *VecTy = EltTy->getAs<VectorType>())
  2364. EltTy = VecTy->getElementType();
  2365. if (!EltTy->isFloatingType()) {
  2366. Diag(TheCall->getArg(0)->getBeginLoc(),
  2367. diag::err_builtin_invalid_arg_type)
  2368. << 1 << /* float ty*/ 5 << ArgTy;
  2369. return ExprError();
  2370. }
  2371. break;
  2372. }
  2373. // These builtins restrict the element type to integer
  2374. // types only.
  2375. case Builtin::BI__builtin_elementwise_add_sat:
  2376. case Builtin::BI__builtin_elementwise_sub_sat: {
  2377. if (SemaBuiltinElementwiseMath(TheCall))
  2378. return ExprError();
  2379. const Expr *Arg = TheCall->getArg(0);
  2380. QualType ArgTy = Arg->getType();
  2381. QualType EltTy = ArgTy;
  2382. if (auto *VecTy = EltTy->getAs<VectorType>())
  2383. EltTy = VecTy->getElementType();
  2384. if (!EltTy->isIntegerType()) {
  2385. Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  2386. << 1 << /* integer ty */ 6 << ArgTy;
  2387. return ExprError();
  2388. }
  2389. break;
  2390. }
  2391. case Builtin::BI__builtin_elementwise_min:
  2392. case Builtin::BI__builtin_elementwise_max:
  2393. if (SemaBuiltinElementwiseMath(TheCall))
  2394. return ExprError();
  2395. break;
  2396. case Builtin::BI__builtin_elementwise_copysign: {
  2397. if (checkArgCount(*this, TheCall, 2))
  2398. return ExprError();
  2399. ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
  2400. ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
  2401. if (Magnitude.isInvalid() || Sign.isInvalid())
  2402. return ExprError();
  2403. QualType MagnitudeTy = Magnitude.get()->getType();
  2404. QualType SignTy = Sign.get()->getType();
  2405. if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
  2406. MagnitudeTy, 1) ||
  2407. checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
  2408. SignTy, 2)) {
  2409. return ExprError();
  2410. }
  2411. if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
  2412. return Diag(Sign.get()->getBeginLoc(),
  2413. diag::err_typecheck_call_different_arg_types)
  2414. << MagnitudeTy << SignTy;
  2415. }
  2416. TheCall->setArg(0, Magnitude.get());
  2417. TheCall->setArg(1, Sign.get());
  2418. TheCall->setType(Magnitude.get()->getType());
  2419. break;
  2420. }
  2421. case Builtin::BI__builtin_reduce_max:
  2422. case Builtin::BI__builtin_reduce_min: {
  2423. if (PrepareBuiltinReduceMathOneArgCall(TheCall))
  2424. return ExprError();
  2425. const Expr *Arg = TheCall->getArg(0);
  2426. const auto *TyA = Arg->getType()->getAs<VectorType>();
  2427. if (!TyA) {
  2428. Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  2429. << 1 << /* vector ty*/ 4 << Arg->getType();
  2430. return ExprError();
  2431. }
  2432. TheCall->setType(TyA->getElementType());
  2433. break;
  2434. }
  2435. // These builtins support vectors of integers only.
  2436. // TODO: ADD/MUL should support floating-point types.
  2437. case Builtin::BI__builtin_reduce_add:
  2438. case Builtin::BI__builtin_reduce_mul:
  2439. case Builtin::BI__builtin_reduce_xor:
  2440. case Builtin::BI__builtin_reduce_or:
  2441. case Builtin::BI__builtin_reduce_and: {
  2442. if (PrepareBuiltinReduceMathOneArgCall(TheCall))
  2443. return ExprError();
  2444. const Expr *Arg = TheCall->getArg(0);
  2445. const auto *TyA = Arg->getType()->getAs<VectorType>();
  2446. if (!TyA || !TyA->getElementType()->isIntegerType()) {
  2447. Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  2448. << 1 << /* vector of integers */ 6 << Arg->getType();
  2449. return ExprError();
  2450. }
  2451. TheCall->setType(TyA->getElementType());
  2452. break;
  2453. }
  2454. case Builtin::BI__builtin_matrix_transpose:
  2455. return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
  2456. case Builtin::BI__builtin_matrix_column_major_load:
  2457. return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
  2458. case Builtin::BI__builtin_matrix_column_major_store:
  2459. return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
  2460. case Builtin::BI__builtin_get_device_side_mangled_name: {
  2461. auto Check = [](CallExpr *TheCall) {
  2462. if (TheCall->getNumArgs() != 1)
  2463. return false;
  2464. auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
  2465. if (!DRE)
  2466. return false;
  2467. auto *D = DRE->getDecl();
  2468. if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
  2469. return false;
  2470. return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
  2471. D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
  2472. };
  2473. if (!Check(TheCall)) {
  2474. Diag(TheCall->getBeginLoc(),
  2475. diag::err_hip_invalid_args_builtin_mangled_name);
  2476. return ExprError();
  2477. }
  2478. }
  2479. }
  2480. // Since the target specific builtins for each arch overlap, only check those
  2481. // of the arch we are compiling for.
  2482. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  2483. if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
  2484. assert(Context.getAuxTargetInfo() &&
  2485. "Aux Target Builtin, but not an aux target?");
  2486. if (CheckTSBuiltinFunctionCall(
  2487. *Context.getAuxTargetInfo(),
  2488. Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
  2489. return ExprError();
  2490. } else {
  2491. if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
  2492. TheCall))
  2493. return ExprError();
  2494. }
  2495. }
  2496. return TheCallResult;
  2497. }
  2498. // Get the valid immediate range for the specified NEON type code.
  2499. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  2500. NeonTypeFlags Type(t);
  2501. int IsQuad = ForceQuad ? true : Type.isQuad();
  2502. switch (Type.getEltType()) {
  2503. case NeonTypeFlags::Int8:
  2504. case NeonTypeFlags::Poly8:
  2505. return shift ? 7 : (8 << IsQuad) - 1;
  2506. case NeonTypeFlags::Int16:
  2507. case NeonTypeFlags::Poly16:
  2508. return shift ? 15 : (4 << IsQuad) - 1;
  2509. case NeonTypeFlags::Int32:
  2510. return shift ? 31 : (2 << IsQuad) - 1;
  2511. case NeonTypeFlags::Int64:
  2512. case NeonTypeFlags::Poly64:
  2513. return shift ? 63 : (1 << IsQuad) - 1;
  2514. case NeonTypeFlags::Poly128:
  2515. return shift ? 127 : (1 << IsQuad) - 1;
  2516. case NeonTypeFlags::Float16:
  2517. assert(!shift && "cannot shift float types!");
  2518. return (4 << IsQuad) - 1;
  2519. case NeonTypeFlags::Float32:
  2520. assert(!shift && "cannot shift float types!");
  2521. return (2 << IsQuad) - 1;
  2522. case NeonTypeFlags::Float64:
  2523. assert(!shift && "cannot shift float types!");
  2524. return (1 << IsQuad) - 1;
  2525. case NeonTypeFlags::BFloat16:
  2526. assert(!shift && "cannot shift float types!");
  2527. return (4 << IsQuad) - 1;
  2528. }
  2529. llvm_unreachable("Invalid NeonTypeFlag!");
  2530. }
  2531. /// getNeonEltType - Return the QualType corresponding to the elements of
  2532. /// the vector type specified by the NeonTypeFlags. This is used to check
  2533. /// the pointer arguments for Neon load/store intrinsics.
  2534. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  2535. bool IsPolyUnsigned, bool IsInt64Long) {
  2536. switch (Flags.getEltType()) {
  2537. case NeonTypeFlags::Int8:
  2538. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  2539. case NeonTypeFlags::Int16:
  2540. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  2541. case NeonTypeFlags::Int32:
  2542. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  2543. case NeonTypeFlags::Int64:
  2544. if (IsInt64Long)
  2545. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  2546. else
  2547. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  2548. : Context.LongLongTy;
  2549. case NeonTypeFlags::Poly8:
  2550. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  2551. case NeonTypeFlags::Poly16:
  2552. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  2553. case NeonTypeFlags::Poly64:
  2554. if (IsInt64Long)
  2555. return Context.UnsignedLongTy;
  2556. else
  2557. return Context.UnsignedLongLongTy;
  2558. case NeonTypeFlags::Poly128:
  2559. break;
  2560. case NeonTypeFlags::Float16:
  2561. return Context.HalfTy;
  2562. case NeonTypeFlags::Float32:
  2563. return Context.FloatTy;
  2564. case NeonTypeFlags::Float64:
  2565. return Context.DoubleTy;
  2566. case NeonTypeFlags::BFloat16:
  2567. return Context.BFloat16Ty;
  2568. }
  2569. llvm_unreachable("Invalid NeonTypeFlag!");
  2570. }
  2571. bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2572. // Range check SVE intrinsics that take immediate values.
  2573. SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
  2574. switch (BuiltinID) {
  2575. default:
  2576. return false;
  2577. #define GET_SVE_IMMEDIATE_CHECK
  2578. #include "clang/Basic/arm_sve_sema_rangechecks.inc"
  2579. #undef GET_SVE_IMMEDIATE_CHECK
  2580. }
  2581. // Perform all the immediate checks for this builtin call.
  2582. bool HasError = false;
  2583. for (auto &I : ImmChecks) {
  2584. int ArgNum, CheckTy, ElementSizeInBits;
  2585. std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
  2586. typedef bool(*OptionSetCheckFnTy)(int64_t Value);
  2587. // Function that checks whether the operand (ArgNum) is an immediate
  2588. // that is one of the predefined values.
  2589. auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
  2590. int ErrDiag) -> bool {
  2591. // We can't check the value of a dependent argument.
  2592. Expr *Arg = TheCall->getArg(ArgNum);
  2593. if (Arg->isTypeDependent() || Arg->isValueDependent())
  2594. return false;
  2595. // Check constant-ness first.
  2596. llvm::APSInt Imm;
  2597. if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
  2598. return true;
  2599. if (!CheckImm(Imm.getSExtValue()))
  2600. return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
  2601. return false;
  2602. };
  2603. switch ((SVETypeFlags::ImmCheckType)CheckTy) {
  2604. case SVETypeFlags::ImmCheck0_31:
  2605. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
  2606. HasError = true;
  2607. break;
  2608. case SVETypeFlags::ImmCheck0_13:
  2609. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
  2610. HasError = true;
  2611. break;
  2612. case SVETypeFlags::ImmCheck1_16:
  2613. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
  2614. HasError = true;
  2615. break;
  2616. case SVETypeFlags::ImmCheck0_7:
  2617. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
  2618. HasError = true;
  2619. break;
  2620. case SVETypeFlags::ImmCheckExtract:
  2621. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
  2622. (2048 / ElementSizeInBits) - 1))
  2623. HasError = true;
  2624. break;
  2625. case SVETypeFlags::ImmCheckShiftRight:
  2626. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
  2627. HasError = true;
  2628. break;
  2629. case SVETypeFlags::ImmCheckShiftRightNarrow:
  2630. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
  2631. ElementSizeInBits / 2))
  2632. HasError = true;
  2633. break;
  2634. case SVETypeFlags::ImmCheckShiftLeft:
  2635. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
  2636. ElementSizeInBits - 1))
  2637. HasError = true;
  2638. break;
  2639. case SVETypeFlags::ImmCheckLaneIndex:
  2640. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
  2641. (128 / (1 * ElementSizeInBits)) - 1))
  2642. HasError = true;
  2643. break;
  2644. case SVETypeFlags::ImmCheckLaneIndexCompRotate:
  2645. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
  2646. (128 / (2 * ElementSizeInBits)) - 1))
  2647. HasError = true;
  2648. break;
  2649. case SVETypeFlags::ImmCheckLaneIndexDot:
  2650. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
  2651. (128 / (4 * ElementSizeInBits)) - 1))
  2652. HasError = true;
  2653. break;
  2654. case SVETypeFlags::ImmCheckComplexRot90_270:
  2655. if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
  2656. diag::err_rotation_argument_to_cadd))
  2657. HasError = true;
  2658. break;
  2659. case SVETypeFlags::ImmCheckComplexRotAll90:
  2660. if (CheckImmediateInSet(
  2661. [](int64_t V) {
  2662. return V == 0 || V == 90 || V == 180 || V == 270;
  2663. },
  2664. diag::err_rotation_argument_to_cmla))
  2665. HasError = true;
  2666. break;
  2667. case SVETypeFlags::ImmCheck0_1:
  2668. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
  2669. HasError = true;
  2670. break;
  2671. case SVETypeFlags::ImmCheck0_2:
  2672. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
  2673. HasError = true;
  2674. break;
  2675. case SVETypeFlags::ImmCheck0_3:
  2676. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
  2677. HasError = true;
  2678. break;
  2679. }
  2680. }
  2681. return HasError;
  2682. }
  2683. bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
  2684. unsigned BuiltinID, CallExpr *TheCall) {
  2685. llvm::APSInt Result;
  2686. uint64_t mask = 0;
  2687. unsigned TV = 0;
  2688. int PtrArgNum = -1;
  2689. bool HasConstPtr = false;
  2690. switch (BuiltinID) {
  2691. #define GET_NEON_OVERLOAD_CHECK
  2692. #include "clang/Basic/arm_neon.inc"
  2693. #include "clang/Basic/arm_fp16.inc"
  2694. #undef GET_NEON_OVERLOAD_CHECK
  2695. }
  2696. // For NEON intrinsics which are overloaded on vector element type, validate
  2697. // the immediate which specifies which variant to emit.
  2698. unsigned ImmArg = TheCall->getNumArgs()-1;
  2699. if (mask) {
  2700. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  2701. return true;
  2702. TV = Result.getLimitedValue(64);
  2703. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  2704. return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
  2705. << TheCall->getArg(ImmArg)->getSourceRange();
  2706. }
  2707. if (PtrArgNum >= 0) {
  2708. // Check that pointer arguments have the specified type.
  2709. Expr *Arg = TheCall->getArg(PtrArgNum);
  2710. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  2711. Arg = ICE->getSubExpr();
  2712. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  2713. QualType RHSTy = RHS.get()->getType();
  2714. llvm::Triple::ArchType Arch = TI.getTriple().getArch();
  2715. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  2716. Arch == llvm::Triple::aarch64_32 ||
  2717. Arch == llvm::Triple::aarch64_be;
  2718. bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
  2719. QualType EltTy =
  2720. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  2721. if (HasConstPtr)
  2722. EltTy = EltTy.withConst();
  2723. QualType LHSTy = Context.getPointerType(EltTy);
  2724. AssignConvertType ConvTy;
  2725. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  2726. if (RHS.isInvalid())
  2727. return true;
  2728. if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
  2729. RHS.get(), AA_Assigning))
  2730. return true;
  2731. }
  2732. // For NEON intrinsics which take an immediate value as part of the
  2733. // instruction, range check them here.
  2734. unsigned i = 0, l = 0, u = 0;
  2735. switch (BuiltinID) {
  2736. default:
  2737. return false;
  2738. #define GET_NEON_IMMEDIATE_CHECK
  2739. #include "clang/Basic/arm_neon.inc"
  2740. #include "clang/Basic/arm_fp16.inc"
  2741. #undef GET_NEON_IMMEDIATE_CHECK
  2742. }
  2743. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  2744. }
  2745. bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2746. switch (BuiltinID) {
  2747. default:
  2748. return false;
  2749. #include "clang/Basic/arm_mve_builtin_sema.inc"
  2750. }
  2751. }
  2752. bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
  2753. CallExpr *TheCall) {
  2754. bool Err = false;
  2755. switch (BuiltinID) {
  2756. default:
  2757. return false;
  2758. #include "clang/Basic/arm_cde_builtin_sema.inc"
  2759. }
  2760. if (Err)
  2761. return true;
  2762. return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
  2763. }
  2764. bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
  2765. const Expr *CoprocArg, bool WantCDE) {
  2766. if (isConstantEvaluated())
  2767. return false;
  2768. // We can't check the value of a dependent argument.
  2769. if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
  2770. return false;
  2771. llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
  2772. int64_t CoprocNo = CoprocNoAP.getExtValue();
  2773. assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
  2774. uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
  2775. bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
  2776. if (IsCDECoproc != WantCDE)
  2777. return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
  2778. << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
  2779. return false;
  2780. }
  2781. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  2782. unsigned MaxWidth) {
  2783. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  2784. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  2785. BuiltinID == ARM::BI__builtin_arm_strex ||
  2786. BuiltinID == ARM::BI__builtin_arm_stlex ||
  2787. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  2788. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  2789. BuiltinID == AArch64::BI__builtin_arm_strex ||
  2790. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  2791. "unexpected ARM builtin");
  2792. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  2793. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  2794. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  2795. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  2796. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  2797. // Ensure that we have the proper number of arguments.
  2798. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  2799. return true;
  2800. // Inspect the pointer argument of the atomic builtin. This should always be
  2801. // a pointer type, whose element is an integral scalar or pointer type.
  2802. // Because it is a pointer type, we don't have to worry about any implicit
  2803. // casts here.
  2804. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  2805. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  2806. if (PointerArgRes.isInvalid())
  2807. return true;
  2808. PointerArg = PointerArgRes.get();
  2809. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  2810. if (!pointerType) {
  2811. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  2812. << PointerArg->getType() << PointerArg->getSourceRange();
  2813. return true;
  2814. }
  2815. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  2816. // task is to insert the appropriate casts into the AST. First work out just
  2817. // what the appropriate type is.
  2818. QualType ValType = pointerType->getPointeeType();
  2819. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  2820. if (IsLdrex)
  2821. AddrType.addConst();
  2822. // Issue a warning if the cast is dodgy.
  2823. CastKind CastNeeded = CK_NoOp;
  2824. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  2825. CastNeeded = CK_BitCast;
  2826. Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
  2827. << PointerArg->getType() << Context.getPointerType(AddrType)
  2828. << AA_Passing << PointerArg->getSourceRange();
  2829. }
  2830. // Finally, do the cast and replace the argument with the corrected version.
  2831. AddrType = Context.getPointerType(AddrType);
  2832. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  2833. if (PointerArgRes.isInvalid())
  2834. return true;
  2835. PointerArg = PointerArgRes.get();
  2836. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  2837. // In general, we allow ints, floats and pointers to be loaded and stored.
  2838. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  2839. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  2840. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  2841. << PointerArg->getType() << PointerArg->getSourceRange();
  2842. return true;
  2843. }
  2844. // But ARM doesn't have instructions to deal with 128-bit versions.
  2845. if (Context.getTypeSize(ValType) > MaxWidth) {
  2846. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  2847. Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
  2848. << PointerArg->getType() << PointerArg->getSourceRange();
  2849. return true;
  2850. }
  2851. switch (ValType.getObjCLifetime()) {
  2852. case Qualifiers::OCL_None:
  2853. case Qualifiers::OCL_ExplicitNone:
  2854. // okay
  2855. break;
  2856. case Qualifiers::OCL_Weak:
  2857. case Qualifiers::OCL_Strong:
  2858. case Qualifiers::OCL_Autoreleasing:
  2859. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  2860. << ValType << PointerArg->getSourceRange();
  2861. return true;
  2862. }
  2863. if (IsLdrex) {
  2864. TheCall->setType(ValType);
  2865. return false;
  2866. }
  2867. // Initialize the argument to be stored.
  2868. ExprResult ValArg = TheCall->getArg(0);
  2869. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  2870. Context, ValType, /*consume*/ false);
  2871. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  2872. if (ValArg.isInvalid())
  2873. return true;
  2874. TheCall->setArg(0, ValArg.get());
  2875. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  2876. // but the custom checker bypasses all default analysis.
  2877. TheCall->setType(Context.IntTy);
  2878. return false;
  2879. }
  2880. bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
  2881. CallExpr *TheCall) {
  2882. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  2883. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  2884. BuiltinID == ARM::BI__builtin_arm_strex ||
  2885. BuiltinID == ARM::BI__builtin_arm_stlex) {
  2886. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  2887. }
  2888. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  2889. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  2890. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  2891. }
  2892. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  2893. BuiltinID == ARM::BI__builtin_arm_wsr64)
  2894. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  2895. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  2896. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  2897. BuiltinID == ARM::BI__builtin_arm_wsr ||
  2898. BuiltinID == ARM::BI__builtin_arm_wsrp)
  2899. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  2900. if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
  2901. return true;
  2902. if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
  2903. return true;
  2904. if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
  2905. return true;
  2906. // For intrinsics which take an immediate value as part of the instruction,
  2907. // range check them here.
  2908. // FIXME: VFP Intrinsics should error if VFP not present.
  2909. switch (BuiltinID) {
  2910. default: return false;
  2911. case ARM::BI__builtin_arm_ssat:
  2912. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  2913. case ARM::BI__builtin_arm_usat:
  2914. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  2915. case ARM::BI__builtin_arm_ssat16:
  2916. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  2917. case ARM::BI__builtin_arm_usat16:
  2918. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  2919. case ARM::BI__builtin_arm_vcvtr_f:
  2920. case ARM::BI__builtin_arm_vcvtr_d:
  2921. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  2922. case ARM::BI__builtin_arm_dmb:
  2923. case ARM::BI__builtin_arm_dsb:
  2924. case ARM::BI__builtin_arm_isb:
  2925. case ARM::BI__builtin_arm_dbg:
  2926. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  2927. case ARM::BI__builtin_arm_cdp:
  2928. case ARM::BI__builtin_arm_cdp2:
  2929. case ARM::BI__builtin_arm_mcr:
  2930. case ARM::BI__builtin_arm_mcr2:
  2931. case ARM::BI__builtin_arm_mrc:
  2932. case ARM::BI__builtin_arm_mrc2:
  2933. case ARM::BI__builtin_arm_mcrr:
  2934. case ARM::BI__builtin_arm_mcrr2:
  2935. case ARM::BI__builtin_arm_mrrc:
  2936. case ARM::BI__builtin_arm_mrrc2:
  2937. case ARM::BI__builtin_arm_ldc:
  2938. case ARM::BI__builtin_arm_ldcl:
  2939. case ARM::BI__builtin_arm_ldc2:
  2940. case ARM::BI__builtin_arm_ldc2l:
  2941. case ARM::BI__builtin_arm_stc:
  2942. case ARM::BI__builtin_arm_stcl:
  2943. case ARM::BI__builtin_arm_stc2:
  2944. case ARM::BI__builtin_arm_stc2l:
  2945. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
  2946. CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
  2947. /*WantCDE*/ false);
  2948. }
  2949. }
  2950. bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
  2951. unsigned BuiltinID,
  2952. CallExpr *TheCall) {
  2953. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  2954. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  2955. BuiltinID == AArch64::BI__builtin_arm_strex ||
  2956. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  2957. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  2958. }
  2959. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  2960. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  2961. SemaBuiltinConstantArgRange(TheCall, 2, 0, 3) ||
  2962. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  2963. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  2964. }
  2965. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  2966. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  2967. BuiltinID == AArch64::BI__builtin_arm_rsr128 ||
  2968. BuiltinID == AArch64::BI__builtin_arm_wsr128)
  2969. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  2970. // Memory Tagging Extensions (MTE) Intrinsics
  2971. if (BuiltinID == AArch64::BI__builtin_arm_irg ||
  2972. BuiltinID == AArch64::BI__builtin_arm_addg ||
  2973. BuiltinID == AArch64::BI__builtin_arm_gmi ||
  2974. BuiltinID == AArch64::BI__builtin_arm_ldg ||
  2975. BuiltinID == AArch64::BI__builtin_arm_stg ||
  2976. BuiltinID == AArch64::BI__builtin_arm_subp) {
  2977. return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
  2978. }
  2979. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  2980. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  2981. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  2982. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  2983. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  2984. // Only check the valid encoding range. Any constant in this range would be
  2985. // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
  2986. // an exception for incorrect registers. This matches MSVC behavior.
  2987. if (BuiltinID == AArch64::BI_ReadStatusReg ||
  2988. BuiltinID == AArch64::BI_WriteStatusReg)
  2989. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
  2990. if (BuiltinID == AArch64::BI__getReg)
  2991. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
  2992. if (BuiltinID == AArch64::BI__break)
  2993. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xffff);
  2994. if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
  2995. return true;
  2996. if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
  2997. return true;
  2998. // For intrinsics which take an immediate value as part of the instruction,
  2999. // range check them here.
  3000. unsigned i = 0, l = 0, u = 0;
  3001. switch (BuiltinID) {
  3002. default: return false;
  3003. case AArch64::BI__builtin_arm_dmb:
  3004. case AArch64::BI__builtin_arm_dsb:
  3005. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  3006. case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
  3007. }
  3008. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  3009. }
  3010. static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
  3011. if (Arg->getType()->getAsPlaceholderType())
  3012. return false;
  3013. // The first argument needs to be a record field access.
  3014. // If it is an array element access, we delay decision
  3015. // to BPF backend to check whether the access is a
  3016. // field access or not.
  3017. return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
  3018. isa<MemberExpr>(Arg->IgnoreParens()) ||
  3019. isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
  3020. }
  3021. static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
  3022. QualType ArgType = Arg->getType();
  3023. if (ArgType->getAsPlaceholderType())
  3024. return false;
  3025. // for TYPE_EXISTENCE/TYPE_MATCH/TYPE_SIZEOF reloc type
  3026. // format:
  3027. // 1. __builtin_preserve_type_info(*(<type> *)0, flag);
  3028. // 2. <type> var;
  3029. // __builtin_preserve_type_info(var, flag);
  3030. if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
  3031. !isa<UnaryOperator>(Arg->IgnoreParens()))
  3032. return false;
  3033. // Typedef type.
  3034. if (ArgType->getAs<TypedefType>())
  3035. return true;
  3036. // Record type or Enum type.
  3037. const Type *Ty = ArgType->getUnqualifiedDesugaredType();
  3038. if (const auto *RT = Ty->getAs<RecordType>()) {
  3039. if (!RT->getDecl()->getDeclName().isEmpty())
  3040. return true;
  3041. } else if (const auto *ET = Ty->getAs<EnumType>()) {
  3042. if (!ET->getDecl()->getDeclName().isEmpty())
  3043. return true;
  3044. }
  3045. return false;
  3046. }
  3047. static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
  3048. QualType ArgType = Arg->getType();
  3049. if (ArgType->getAsPlaceholderType())
  3050. return false;
  3051. // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
  3052. // format:
  3053. // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
  3054. // flag);
  3055. const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
  3056. if (!UO)
  3057. return false;
  3058. const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
  3059. if (!CE)
  3060. return false;
  3061. if (CE->getCastKind() != CK_IntegralToPointer &&
  3062. CE->getCastKind() != CK_NullToPointer)
  3063. return false;
  3064. // The integer must be from an EnumConstantDecl.
  3065. const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
  3066. if (!DR)
  3067. return false;
  3068. const EnumConstantDecl *Enumerator =
  3069. dyn_cast<EnumConstantDecl>(DR->getDecl());
  3070. if (!Enumerator)
  3071. return false;
  3072. // The type must be EnumType.
  3073. const Type *Ty = ArgType->getUnqualifiedDesugaredType();
  3074. const auto *ET = Ty->getAs<EnumType>();
  3075. if (!ET)
  3076. return false;
  3077. // The enum value must be supported.
  3078. return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
  3079. }
  3080. bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
  3081. CallExpr *TheCall) {
  3082. assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
  3083. BuiltinID == BPF::BI__builtin_btf_type_id ||
  3084. BuiltinID == BPF::BI__builtin_preserve_type_info ||
  3085. BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
  3086. "unexpected BPF builtin");
  3087. if (checkArgCount(*this, TheCall, 2))
  3088. return true;
  3089. // The second argument needs to be a constant int
  3090. Expr *Arg = TheCall->getArg(1);
  3091. std::optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
  3092. diag::kind kind;
  3093. if (!Value) {
  3094. if (BuiltinID == BPF::BI__builtin_preserve_field_info)
  3095. kind = diag::err_preserve_field_info_not_const;
  3096. else if (BuiltinID == BPF::BI__builtin_btf_type_id)
  3097. kind = diag::err_btf_type_id_not_const;
  3098. else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
  3099. kind = diag::err_preserve_type_info_not_const;
  3100. else
  3101. kind = diag::err_preserve_enum_value_not_const;
  3102. Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
  3103. return true;
  3104. }
  3105. // The first argument
  3106. Arg = TheCall->getArg(0);
  3107. bool InvalidArg = false;
  3108. bool ReturnUnsignedInt = true;
  3109. if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
  3110. if (!isValidBPFPreserveFieldInfoArg(Arg)) {
  3111. InvalidArg = true;
  3112. kind = diag::err_preserve_field_info_not_field;
  3113. }
  3114. } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
  3115. if (!isValidBPFPreserveTypeInfoArg(Arg)) {
  3116. InvalidArg = true;
  3117. kind = diag::err_preserve_type_info_invalid;
  3118. }
  3119. } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
  3120. if (!isValidBPFPreserveEnumValueArg(Arg)) {
  3121. InvalidArg = true;
  3122. kind = diag::err_preserve_enum_value_invalid;
  3123. }
  3124. ReturnUnsignedInt = false;
  3125. } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
  3126. ReturnUnsignedInt = false;
  3127. }
  3128. if (InvalidArg) {
  3129. Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
  3130. return true;
  3131. }
  3132. if (ReturnUnsignedInt)
  3133. TheCall->setType(Context.UnsignedIntTy);
  3134. else
  3135. TheCall->setType(Context.UnsignedLongTy);
  3136. return false;
  3137. }
  3138. bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
  3139. struct ArgInfo {
  3140. uint8_t OpNum;
  3141. bool IsSigned;
  3142. uint8_t BitWidth;
  3143. uint8_t Align;
  3144. };
  3145. struct BuiltinInfo {
  3146. unsigned BuiltinID;
  3147. ArgInfo Infos[2];
  3148. };
  3149. static BuiltinInfo Infos[] = {
  3150. { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
  3151. { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
  3152. { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
  3153. { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} },
  3154. { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
  3155. { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
  3156. { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
  3157. { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
  3158. { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
  3159. { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
  3160. { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
  3161. { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
  3162. { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
  3163. { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
  3164. { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
  3165. { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
  3166. { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
  3167. { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
  3168. { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
  3169. { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
  3170. { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
  3171. { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
  3172. { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
  3173. { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
  3174. { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
  3175. { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
  3176. { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
  3177. { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
  3178. { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
  3179. { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
  3180. { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
  3181. { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
  3182. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
  3183. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
  3184. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
  3185. { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
  3186. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
  3187. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
  3188. { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
  3189. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
  3190. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
  3191. { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
  3192. { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
  3193. { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
  3194. { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
  3195. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
  3196. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
  3197. { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
  3198. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
  3199. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
  3200. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
  3201. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
  3202. { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
  3203. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
  3204. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
  3205. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
  3206. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
  3207. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
  3208. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
  3209. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
  3210. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
  3211. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
  3212. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
  3213. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
  3214. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
  3215. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
  3216. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
  3217. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
  3218. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
  3219. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
  3220. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
  3221. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
  3222. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
  3223. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
  3224. {{ 1, false, 6, 0 }} },
  3225. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
  3226. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
  3227. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
  3228. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
  3229. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
  3230. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
  3231. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
  3232. {{ 1, false, 5, 0 }} },
  3233. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
  3234. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
  3235. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
  3236. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
  3237. { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
  3238. { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
  3239. { 2, false, 5, 0 }} },
  3240. { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
  3241. { 2, false, 6, 0 }} },
  3242. { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
  3243. { 3, false, 5, 0 }} },
  3244. { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
  3245. { 3, false, 6, 0 }} },
  3246. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
  3247. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
  3248. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
  3249. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
  3250. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
  3251. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
  3252. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
  3253. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
  3254. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
  3255. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
  3256. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
  3257. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
  3258. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
  3259. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
  3260. { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
  3261. { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
  3262. {{ 2, false, 4, 0 },
  3263. { 3, false, 5, 0 }} },
  3264. { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
  3265. {{ 2, false, 4, 0 },
  3266. { 3, false, 5, 0 }} },
  3267. { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
  3268. {{ 2, false, 4, 0 },
  3269. { 3, false, 5, 0 }} },
  3270. { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
  3271. {{ 2, false, 4, 0 },
  3272. { 3, false, 5, 0 }} },
  3273. { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
  3274. { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
  3275. { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
  3276. { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
  3277. { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
  3278. { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
  3279. { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
  3280. { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
  3281. { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
  3282. { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
  3283. { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
  3284. { 2, false, 5, 0 }} },
  3285. { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
  3286. { 2, false, 6, 0 }} },
  3287. { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
  3288. { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
  3289. { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
  3290. { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
  3291. { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
  3292. { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
  3293. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
  3294. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
  3295. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
  3296. {{ 1, false, 4, 0 }} },
  3297. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
  3298. { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
  3299. {{ 1, false, 4, 0 }} },
  3300. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
  3301. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
  3302. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
  3303. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
  3304. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
  3305. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
  3306. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
  3307. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
  3308. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
  3309. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
  3310. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
  3311. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
  3312. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
  3313. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
  3314. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
  3315. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
  3316. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
  3317. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
  3318. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
  3319. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
  3320. {{ 3, false, 1, 0 }} },
  3321. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
  3322. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
  3323. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
  3324. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
  3325. {{ 3, false, 1, 0 }} },
  3326. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
  3327. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
  3328. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
  3329. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
  3330. {{ 3, false, 1, 0 }} },
  3331. { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10, {{ 2, false, 2, 0 }} },
  3332. { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_128B,
  3333. {{ 2, false, 2, 0 }} },
  3334. { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_vxx,
  3335. {{ 3, false, 2, 0 }} },
  3336. { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_vxx_128B,
  3337. {{ 3, false, 2, 0 }} },
  3338. { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10, {{ 2, false, 2, 0 }} },
  3339. { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_128B,
  3340. {{ 2, false, 2, 0 }} },
  3341. { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_vxx,
  3342. {{ 3, false, 2, 0 }} },
  3343. { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_vxx_128B,
  3344. {{ 3, false, 2, 0 }} },
  3345. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, {{ 2, false, 3, 0 }} },
  3346. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, {{ 2, false, 3, 0 }} },
  3347. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, {{ 3, false, 3, 0 }} },
  3348. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B,
  3349. {{ 3, false, 3, 0 }} },
  3350. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, {{ 2, false, 3, 0 }} },
  3351. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, {{ 2, false, 3, 0 }} },
  3352. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, {{ 3, false, 3, 0 }} },
  3353. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B,
  3354. {{ 3, false, 3, 0 }} },
  3355. };
  3356. // Use a dynamically initialized static to sort the table exactly once on
  3357. // first run.
  3358. static const bool SortOnce =
  3359. (llvm::sort(Infos,
  3360. [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
  3361. return LHS.BuiltinID < RHS.BuiltinID;
  3362. }),
  3363. true);
  3364. (void)SortOnce;
  3365. const BuiltinInfo *F = llvm::partition_point(
  3366. Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
  3367. if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
  3368. return false;
  3369. bool Error = false;
  3370. for (const ArgInfo &A : F->Infos) {
  3371. // Ignore empty ArgInfo elements.
  3372. if (A.BitWidth == 0)
  3373. continue;
  3374. int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
  3375. int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
  3376. if (!A.Align) {
  3377. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
  3378. } else {
  3379. unsigned M = 1 << A.Align;
  3380. Min *= M;
  3381. Max *= M;
  3382. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
  3383. Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
  3384. }
  3385. }
  3386. return Error;
  3387. }
  3388. bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
  3389. CallExpr *TheCall) {
  3390. return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
  3391. }
  3392. bool Sema::CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI,
  3393. unsigned BuiltinID,
  3394. CallExpr *TheCall) {
  3395. switch (BuiltinID) {
  3396. default:
  3397. break;
  3398. case LoongArch::BI__builtin_loongarch_cacop_d:
  3399. if (!TI.hasFeature("64bit"))
  3400. return Diag(TheCall->getBeginLoc(),
  3401. diag::err_loongarch_builtin_requires_la64)
  3402. << TheCall->getSourceRange();
  3403. LLVM_FALLTHROUGH;
  3404. case LoongArch::BI__builtin_loongarch_cacop_w: {
  3405. if (BuiltinID == LoongArch::BI__builtin_loongarch_cacop_w &&
  3406. !TI.hasFeature("32bit"))
  3407. return Diag(TheCall->getBeginLoc(),
  3408. diag::err_loongarch_builtin_requires_la32)
  3409. << TheCall->getSourceRange();
  3410. SemaBuiltinConstantArgRange(TheCall, 0, 0, llvm::maxUIntN(5));
  3411. SemaBuiltinConstantArgRange(TheCall, 2, llvm::minIntN(12),
  3412. llvm::maxIntN(12));
  3413. break;
  3414. }
  3415. case LoongArch::BI__builtin_loongarch_crc_w_b_w:
  3416. case LoongArch::BI__builtin_loongarch_crc_w_h_w:
  3417. case LoongArch::BI__builtin_loongarch_crc_w_w_w:
  3418. case LoongArch::BI__builtin_loongarch_crc_w_d_w:
  3419. case LoongArch::BI__builtin_loongarch_crcc_w_b_w:
  3420. case LoongArch::BI__builtin_loongarch_crcc_w_h_w:
  3421. case LoongArch::BI__builtin_loongarch_crcc_w_w_w:
  3422. case LoongArch::BI__builtin_loongarch_crcc_w_d_w:
  3423. case LoongArch::BI__builtin_loongarch_iocsrrd_d:
  3424. case LoongArch::BI__builtin_loongarch_iocsrwr_d:
  3425. case LoongArch::BI__builtin_loongarch_asrtle_d:
  3426. case LoongArch::BI__builtin_loongarch_asrtgt_d:
  3427. if (!TI.hasFeature("64bit"))
  3428. return Diag(TheCall->getBeginLoc(),
  3429. diag::err_loongarch_builtin_requires_la64)
  3430. << TheCall->getSourceRange();
  3431. break;
  3432. case LoongArch::BI__builtin_loongarch_break:
  3433. case LoongArch::BI__builtin_loongarch_dbar:
  3434. case LoongArch::BI__builtin_loongarch_ibar:
  3435. case LoongArch::BI__builtin_loongarch_syscall:
  3436. // Check if immediate is in [0, 32767].
  3437. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 32767);
  3438. case LoongArch::BI__builtin_loongarch_csrrd_w:
  3439. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 16383);
  3440. case LoongArch::BI__builtin_loongarch_csrwr_w:
  3441. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 16383);
  3442. case LoongArch::BI__builtin_loongarch_csrxchg_w:
  3443. return SemaBuiltinConstantArgRange(TheCall, 2, 0, 16383);
  3444. case LoongArch::BI__builtin_loongarch_csrrd_d:
  3445. if (!TI.hasFeature("64bit"))
  3446. return Diag(TheCall->getBeginLoc(),
  3447. diag::err_loongarch_builtin_requires_la64)
  3448. << TheCall->getSourceRange();
  3449. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 16383);
  3450. case LoongArch::BI__builtin_loongarch_csrwr_d:
  3451. if (!TI.hasFeature("64bit"))
  3452. return Diag(TheCall->getBeginLoc(),
  3453. diag::err_loongarch_builtin_requires_la64)
  3454. << TheCall->getSourceRange();
  3455. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 16383);
  3456. case LoongArch::BI__builtin_loongarch_csrxchg_d:
  3457. if (!TI.hasFeature("64bit"))
  3458. return Diag(TheCall->getBeginLoc(),
  3459. diag::err_loongarch_builtin_requires_la64)
  3460. << TheCall->getSourceRange();
  3461. return SemaBuiltinConstantArgRange(TheCall, 2, 0, 16383);
  3462. case LoongArch::BI__builtin_loongarch_lddir_d:
  3463. case LoongArch::BI__builtin_loongarch_ldpte_d:
  3464. if (!TI.hasFeature("64bit"))
  3465. return Diag(TheCall->getBeginLoc(),
  3466. diag::err_loongarch_builtin_requires_la64)
  3467. << TheCall->getSourceRange();
  3468. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  3469. case LoongArch::BI__builtin_loongarch_movfcsr2gr:
  3470. case LoongArch::BI__builtin_loongarch_movgr2fcsr:
  3471. return SemaBuiltinConstantArgRange(TheCall, 0, 0, llvm::maxUIntN(2));
  3472. }
  3473. return false;
  3474. }
  3475. bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
  3476. unsigned BuiltinID, CallExpr *TheCall) {
  3477. return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
  3478. CheckMipsBuiltinArgument(BuiltinID, TheCall);
  3479. }
  3480. bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
  3481. CallExpr *TheCall) {
  3482. if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
  3483. BuiltinID <= Mips::BI__builtin_mips_lwx) {
  3484. if (!TI.hasFeature("dsp"))
  3485. return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
  3486. }
  3487. if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
  3488. BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
  3489. if (!TI.hasFeature("dspr2"))
  3490. return Diag(TheCall->getBeginLoc(),
  3491. diag::err_mips_builtin_requires_dspr2);
  3492. }
  3493. if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
  3494. BuiltinID <= Mips::BI__builtin_msa_xori_b) {
  3495. if (!TI.hasFeature("msa"))
  3496. return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
  3497. }
  3498. return false;
  3499. }
  3500. // CheckMipsBuiltinArgument - Checks the constant value passed to the
  3501. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  3502. // ordering for DSP is unspecified. MSA is ordered by the data format used
  3503. // by the underlying instruction i.e., df/m, df/n and then by size.
  3504. //
  3505. // FIXME: The size tests here should instead be tablegen'd along with the
  3506. // definitions from include/clang/Basic/BuiltinsMips.def.
  3507. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  3508. // be too.
  3509. bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
  3510. unsigned i = 0, l = 0, u = 0, m = 0;
  3511. switch (BuiltinID) {
  3512. default: return false;
  3513. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  3514. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  3515. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  3516. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  3517. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  3518. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  3519. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  3520. // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
  3521. // df/m field.
  3522. // These intrinsics take an unsigned 3 bit immediate.
  3523. case Mips::BI__builtin_msa_bclri_b:
  3524. case Mips::BI__builtin_msa_bnegi_b:
  3525. case Mips::BI__builtin_msa_bseti_b:
  3526. case Mips::BI__builtin_msa_sat_s_b:
  3527. case Mips::BI__builtin_msa_sat_u_b:
  3528. case Mips::BI__builtin_msa_slli_b:
  3529. case Mips::BI__builtin_msa_srai_b:
  3530. case Mips::BI__builtin_msa_srari_b:
  3531. case Mips::BI__builtin_msa_srli_b:
  3532. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  3533. case Mips::BI__builtin_msa_binsli_b:
  3534. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  3535. // These intrinsics take an unsigned 4 bit immediate.
  3536. case Mips::BI__builtin_msa_bclri_h:
  3537. case Mips::BI__builtin_msa_bnegi_h:
  3538. case Mips::BI__builtin_msa_bseti_h:
  3539. case Mips::BI__builtin_msa_sat_s_h:
  3540. case Mips::BI__builtin_msa_sat_u_h:
  3541. case Mips::BI__builtin_msa_slli_h:
  3542. case Mips::BI__builtin_msa_srai_h:
  3543. case Mips::BI__builtin_msa_srari_h:
  3544. case Mips::BI__builtin_msa_srli_h:
  3545. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  3546. case Mips::BI__builtin_msa_binsli_h:
  3547. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  3548. // These intrinsics take an unsigned 5 bit immediate.
  3549. // The first block of intrinsics actually have an unsigned 5 bit field,
  3550. // not a df/n field.
  3551. case Mips::BI__builtin_msa_cfcmsa:
  3552. case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
  3553. case Mips::BI__builtin_msa_clei_u_b:
  3554. case Mips::BI__builtin_msa_clei_u_h:
  3555. case Mips::BI__builtin_msa_clei_u_w:
  3556. case Mips::BI__builtin_msa_clei_u_d:
  3557. case Mips::BI__builtin_msa_clti_u_b:
  3558. case Mips::BI__builtin_msa_clti_u_h:
  3559. case Mips::BI__builtin_msa_clti_u_w:
  3560. case Mips::BI__builtin_msa_clti_u_d:
  3561. case Mips::BI__builtin_msa_maxi_u_b:
  3562. case Mips::BI__builtin_msa_maxi_u_h:
  3563. case Mips::BI__builtin_msa_maxi_u_w:
  3564. case Mips::BI__builtin_msa_maxi_u_d:
  3565. case Mips::BI__builtin_msa_mini_u_b:
  3566. case Mips::BI__builtin_msa_mini_u_h:
  3567. case Mips::BI__builtin_msa_mini_u_w:
  3568. case Mips::BI__builtin_msa_mini_u_d:
  3569. case Mips::BI__builtin_msa_addvi_b:
  3570. case Mips::BI__builtin_msa_addvi_h:
  3571. case Mips::BI__builtin_msa_addvi_w:
  3572. case Mips::BI__builtin_msa_addvi_d:
  3573. case Mips::BI__builtin_msa_bclri_w:
  3574. case Mips::BI__builtin_msa_bnegi_w:
  3575. case Mips::BI__builtin_msa_bseti_w:
  3576. case Mips::BI__builtin_msa_sat_s_w:
  3577. case Mips::BI__builtin_msa_sat_u_w:
  3578. case Mips::BI__builtin_msa_slli_w:
  3579. case Mips::BI__builtin_msa_srai_w:
  3580. case Mips::BI__builtin_msa_srari_w:
  3581. case Mips::BI__builtin_msa_srli_w:
  3582. case Mips::BI__builtin_msa_srlri_w:
  3583. case Mips::BI__builtin_msa_subvi_b:
  3584. case Mips::BI__builtin_msa_subvi_h:
  3585. case Mips::BI__builtin_msa_subvi_w:
  3586. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  3587. case Mips::BI__builtin_msa_binsli_w:
  3588. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  3589. // These intrinsics take an unsigned 6 bit immediate.
  3590. case Mips::BI__builtin_msa_bclri_d:
  3591. case Mips::BI__builtin_msa_bnegi_d:
  3592. case Mips::BI__builtin_msa_bseti_d:
  3593. case Mips::BI__builtin_msa_sat_s_d:
  3594. case Mips::BI__builtin_msa_sat_u_d:
  3595. case Mips::BI__builtin_msa_slli_d:
  3596. case Mips::BI__builtin_msa_srai_d:
  3597. case Mips::BI__builtin_msa_srari_d:
  3598. case Mips::BI__builtin_msa_srli_d:
  3599. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  3600. case Mips::BI__builtin_msa_binsli_d:
  3601. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  3602. // These intrinsics take a signed 5 bit immediate.
  3603. case Mips::BI__builtin_msa_ceqi_b:
  3604. case Mips::BI__builtin_msa_ceqi_h:
  3605. case Mips::BI__builtin_msa_ceqi_w:
  3606. case Mips::BI__builtin_msa_ceqi_d:
  3607. case Mips::BI__builtin_msa_clti_s_b:
  3608. case Mips::BI__builtin_msa_clti_s_h:
  3609. case Mips::BI__builtin_msa_clti_s_w:
  3610. case Mips::BI__builtin_msa_clti_s_d:
  3611. case Mips::BI__builtin_msa_clei_s_b:
  3612. case Mips::BI__builtin_msa_clei_s_h:
  3613. case Mips::BI__builtin_msa_clei_s_w:
  3614. case Mips::BI__builtin_msa_clei_s_d:
  3615. case Mips::BI__builtin_msa_maxi_s_b:
  3616. case Mips::BI__builtin_msa_maxi_s_h:
  3617. case Mips::BI__builtin_msa_maxi_s_w:
  3618. case Mips::BI__builtin_msa_maxi_s_d:
  3619. case Mips::BI__builtin_msa_mini_s_b:
  3620. case Mips::BI__builtin_msa_mini_s_h:
  3621. case Mips::BI__builtin_msa_mini_s_w:
  3622. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  3623. // These intrinsics take an unsigned 8 bit immediate.
  3624. case Mips::BI__builtin_msa_andi_b:
  3625. case Mips::BI__builtin_msa_nori_b:
  3626. case Mips::BI__builtin_msa_ori_b:
  3627. case Mips::BI__builtin_msa_shf_b:
  3628. case Mips::BI__builtin_msa_shf_h:
  3629. case Mips::BI__builtin_msa_shf_w:
  3630. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  3631. case Mips::BI__builtin_msa_bseli_b:
  3632. case Mips::BI__builtin_msa_bmnzi_b:
  3633. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  3634. // df/n format
  3635. // These intrinsics take an unsigned 4 bit immediate.
  3636. case Mips::BI__builtin_msa_copy_s_b:
  3637. case Mips::BI__builtin_msa_copy_u_b:
  3638. case Mips::BI__builtin_msa_insve_b:
  3639. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  3640. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  3641. // These intrinsics take an unsigned 3 bit immediate.
  3642. case Mips::BI__builtin_msa_copy_s_h:
  3643. case Mips::BI__builtin_msa_copy_u_h:
  3644. case Mips::BI__builtin_msa_insve_h:
  3645. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  3646. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  3647. // These intrinsics take an unsigned 2 bit immediate.
  3648. case Mips::BI__builtin_msa_copy_s_w:
  3649. case Mips::BI__builtin_msa_copy_u_w:
  3650. case Mips::BI__builtin_msa_insve_w:
  3651. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  3652. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  3653. // These intrinsics take an unsigned 1 bit immediate.
  3654. case Mips::BI__builtin_msa_copy_s_d:
  3655. case Mips::BI__builtin_msa_copy_u_d:
  3656. case Mips::BI__builtin_msa_insve_d:
  3657. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  3658. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  3659. // Memory offsets and immediate loads.
  3660. // These intrinsics take a signed 10 bit immediate.
  3661. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  3662. case Mips::BI__builtin_msa_ldi_h:
  3663. case Mips::BI__builtin_msa_ldi_w:
  3664. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  3665. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
  3666. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
  3667. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
  3668. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
  3669. case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
  3670. case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
  3671. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
  3672. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
  3673. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
  3674. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
  3675. case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
  3676. case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
  3677. }
  3678. if (!m)
  3679. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3680. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  3681. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  3682. }
  3683. /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
  3684. /// advancing the pointer over the consumed characters. The decoded type is
  3685. /// returned. If the decoded type represents a constant integer with a
  3686. /// constraint on its value then Mask is set to that value. The type descriptors
  3687. /// used in Str are specific to PPC MMA builtins and are documented in the file
  3688. /// defining the PPC builtins.
  3689. static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
  3690. unsigned &Mask) {
  3691. bool RequireICE = false;
  3692. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  3693. switch (*Str++) {
  3694. case 'V':
  3695. return Context.getVectorType(Context.UnsignedCharTy, 16,
  3696. VectorType::VectorKind::AltiVecVector);
  3697. case 'i': {
  3698. char *End;
  3699. unsigned size = strtoul(Str, &End, 10);
  3700. assert(End != Str && "Missing constant parameter constraint");
  3701. Str = End;
  3702. Mask = size;
  3703. return Context.IntTy;
  3704. }
  3705. case 'W': {
  3706. char *End;
  3707. unsigned size = strtoul(Str, &End, 10);
  3708. assert(End != Str && "Missing PowerPC MMA type size");
  3709. Str = End;
  3710. QualType Type;
  3711. switch (size) {
  3712. #define PPC_VECTOR_TYPE(typeName, Id, size) \
  3713. case size: Type = Context.Id##Ty; break;
  3714. #include "clang/Basic/PPCTypes.def"
  3715. default: llvm_unreachable("Invalid PowerPC MMA vector type");
  3716. }
  3717. bool CheckVectorArgs = false;
  3718. while (!CheckVectorArgs) {
  3719. switch (*Str++) {
  3720. case '*':
  3721. Type = Context.getPointerType(Type);
  3722. break;
  3723. case 'C':
  3724. Type = Type.withConst();
  3725. break;
  3726. default:
  3727. CheckVectorArgs = true;
  3728. --Str;
  3729. break;
  3730. }
  3731. }
  3732. return Type;
  3733. }
  3734. default:
  3735. return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
  3736. }
  3737. }
  3738. static bool isPPC_64Builtin(unsigned BuiltinID) {
  3739. // These builtins only work on PPC 64bit targets.
  3740. switch (BuiltinID) {
  3741. case PPC::BI__builtin_divde:
  3742. case PPC::BI__builtin_divdeu:
  3743. case PPC::BI__builtin_bpermd:
  3744. case PPC::BI__builtin_pdepd:
  3745. case PPC::BI__builtin_pextd:
  3746. case PPC::BI__builtin_ppc_ldarx:
  3747. case PPC::BI__builtin_ppc_stdcx:
  3748. case PPC::BI__builtin_ppc_tdw:
  3749. case PPC::BI__builtin_ppc_trapd:
  3750. case PPC::BI__builtin_ppc_cmpeqb:
  3751. case PPC::BI__builtin_ppc_setb:
  3752. case PPC::BI__builtin_ppc_mulhd:
  3753. case PPC::BI__builtin_ppc_mulhdu:
  3754. case PPC::BI__builtin_ppc_maddhd:
  3755. case PPC::BI__builtin_ppc_maddhdu:
  3756. case PPC::BI__builtin_ppc_maddld:
  3757. case PPC::BI__builtin_ppc_load8r:
  3758. case PPC::BI__builtin_ppc_store8r:
  3759. case PPC::BI__builtin_ppc_insert_exp:
  3760. case PPC::BI__builtin_ppc_extract_sig:
  3761. case PPC::BI__builtin_ppc_addex:
  3762. case PPC::BI__builtin_darn:
  3763. case PPC::BI__builtin_darn_raw:
  3764. case PPC::BI__builtin_ppc_compare_and_swaplp:
  3765. case PPC::BI__builtin_ppc_fetch_and_addlp:
  3766. case PPC::BI__builtin_ppc_fetch_and_andlp:
  3767. case PPC::BI__builtin_ppc_fetch_and_orlp:
  3768. case PPC::BI__builtin_ppc_fetch_and_swaplp:
  3769. return true;
  3770. }
  3771. return false;
  3772. }
  3773. static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
  3774. StringRef FeatureToCheck, unsigned DiagID,
  3775. StringRef DiagArg = "") {
  3776. if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
  3777. return false;
  3778. if (DiagArg.empty())
  3779. S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
  3780. else
  3781. S.Diag(TheCall->getBeginLoc(), DiagID)
  3782. << DiagArg << TheCall->getSourceRange();
  3783. return true;
  3784. }
  3785. /// Returns true if the argument consists of one contiguous run of 1s with any
  3786. /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
  3787. /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
  3788. /// since all 1s are not contiguous.
  3789. bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
  3790. llvm::APSInt Result;
  3791. // We can't check the value of a dependent argument.
  3792. Expr *Arg = TheCall->getArg(ArgNum);
  3793. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3794. return false;
  3795. // Check constant-ness first.
  3796. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3797. return true;
  3798. // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
  3799. if (Result.isShiftedMask() || (~Result).isShiftedMask())
  3800. return false;
  3801. return Diag(TheCall->getBeginLoc(),
  3802. diag::err_argument_not_contiguous_bit_field)
  3803. << ArgNum << Arg->getSourceRange();
  3804. }
  3805. bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
  3806. CallExpr *TheCall) {
  3807. unsigned i = 0, l = 0, u = 0;
  3808. bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
  3809. llvm::APSInt Result;
  3810. if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
  3811. return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
  3812. << TheCall->getSourceRange();
  3813. switch (BuiltinID) {
  3814. default: return false;
  3815. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  3816. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  3817. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  3818. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3819. case PPC::BI__builtin_altivec_dss:
  3820. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
  3821. case PPC::BI__builtin_tbegin:
  3822. case PPC::BI__builtin_tend:
  3823. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) ||
  3824. SemaFeatureCheck(*this, TheCall, "htm",
  3825. diag::err_ppc_builtin_requires_htm);
  3826. case PPC::BI__builtin_tsr:
  3827. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
  3828. SemaFeatureCheck(*this, TheCall, "htm",
  3829. diag::err_ppc_builtin_requires_htm);
  3830. case PPC::BI__builtin_tabortwc:
  3831. case PPC::BI__builtin_tabortdc:
  3832. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  3833. SemaFeatureCheck(*this, TheCall, "htm",
  3834. diag::err_ppc_builtin_requires_htm);
  3835. case PPC::BI__builtin_tabortwci:
  3836. case PPC::BI__builtin_tabortdci:
  3837. return SemaFeatureCheck(*this, TheCall, "htm",
  3838. diag::err_ppc_builtin_requires_htm) ||
  3839. (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  3840. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31));
  3841. case PPC::BI__builtin_tabort:
  3842. case PPC::BI__builtin_tcheck:
  3843. case PPC::BI__builtin_treclaim:
  3844. case PPC::BI__builtin_trechkpt:
  3845. case PPC::BI__builtin_tendall:
  3846. case PPC::BI__builtin_tresume:
  3847. case PPC::BI__builtin_tsuspend:
  3848. case PPC::BI__builtin_get_texasr:
  3849. case PPC::BI__builtin_get_texasru:
  3850. case PPC::BI__builtin_get_tfhar:
  3851. case PPC::BI__builtin_get_tfiar:
  3852. case PPC::BI__builtin_set_texasr:
  3853. case PPC::BI__builtin_set_texasru:
  3854. case PPC::BI__builtin_set_tfhar:
  3855. case PPC::BI__builtin_set_tfiar:
  3856. case PPC::BI__builtin_ttest:
  3857. return SemaFeatureCheck(*this, TheCall, "htm",
  3858. diag::err_ppc_builtin_requires_htm);
  3859. // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
  3860. // __builtin_(un)pack_longdouble are available only if long double uses IBM
  3861. // extended double representation.
  3862. case PPC::BI__builtin_unpack_longdouble:
  3863. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
  3864. return true;
  3865. [[fallthrough]];
  3866. case PPC::BI__builtin_pack_longdouble:
  3867. if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
  3868. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
  3869. << "ibmlongdouble";
  3870. return false;
  3871. case PPC::BI__builtin_altivec_dst:
  3872. case PPC::BI__builtin_altivec_dstt:
  3873. case PPC::BI__builtin_altivec_dstst:
  3874. case PPC::BI__builtin_altivec_dststt:
  3875. return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
  3876. case PPC::BI__builtin_vsx_xxpermdi:
  3877. case PPC::BI__builtin_vsx_xxsldwi:
  3878. return SemaBuiltinVSX(TheCall);
  3879. case PPC::BI__builtin_divwe:
  3880. case PPC::BI__builtin_divweu:
  3881. case PPC::BI__builtin_divde:
  3882. case PPC::BI__builtin_divdeu:
  3883. return SemaFeatureCheck(*this, TheCall, "extdiv",
  3884. diag::err_ppc_builtin_only_on_arch, "7");
  3885. case PPC::BI__builtin_bpermd:
  3886. return SemaFeatureCheck(*this, TheCall, "bpermd",
  3887. diag::err_ppc_builtin_only_on_arch, "7");
  3888. case PPC::BI__builtin_unpack_vector_int128:
  3889. return SemaFeatureCheck(*this, TheCall, "vsx",
  3890. diag::err_ppc_builtin_only_on_arch, "7") ||
  3891. SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  3892. case PPC::BI__builtin_pack_vector_int128:
  3893. return SemaFeatureCheck(*this, TheCall, "vsx",
  3894. diag::err_ppc_builtin_only_on_arch, "7");
  3895. case PPC::BI__builtin_pdepd:
  3896. case PPC::BI__builtin_pextd:
  3897. return SemaFeatureCheck(*this, TheCall, "isa-v31-instructions",
  3898. diag::err_ppc_builtin_only_on_arch, "10");
  3899. case PPC::BI__builtin_altivec_vgnb:
  3900. return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
  3901. case PPC::BI__builtin_vsx_xxeval:
  3902. return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
  3903. case PPC::BI__builtin_altivec_vsldbi:
  3904. return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
  3905. case PPC::BI__builtin_altivec_vsrdbi:
  3906. return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
  3907. case PPC::BI__builtin_vsx_xxpermx:
  3908. return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
  3909. case PPC::BI__builtin_ppc_tw:
  3910. case PPC::BI__builtin_ppc_tdw:
  3911. return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
  3912. case PPC::BI__builtin_ppc_cmpeqb:
  3913. case PPC::BI__builtin_ppc_setb:
  3914. case PPC::BI__builtin_ppc_maddhd:
  3915. case PPC::BI__builtin_ppc_maddhdu:
  3916. case PPC::BI__builtin_ppc_maddld:
  3917. return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
  3918. diag::err_ppc_builtin_only_on_arch, "9");
  3919. case PPC::BI__builtin_ppc_cmprb:
  3920. return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
  3921. diag::err_ppc_builtin_only_on_arch, "9") ||
  3922. SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
  3923. // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
  3924. // be a constant that represents a contiguous bit field.
  3925. case PPC::BI__builtin_ppc_rlwnm:
  3926. return SemaValueIsRunOfOnes(TheCall, 2);
  3927. case PPC::BI__builtin_ppc_rlwimi:
  3928. case PPC::BI__builtin_ppc_rldimi:
  3929. return SemaBuiltinConstantArg(TheCall, 2, Result) ||
  3930. SemaValueIsRunOfOnes(TheCall, 3);
  3931. case PPC::BI__builtin_ppc_extract_exp:
  3932. case PPC::BI__builtin_ppc_extract_sig:
  3933. case PPC::BI__builtin_ppc_insert_exp:
  3934. return SemaFeatureCheck(*this, TheCall, "power9-vector",
  3935. diag::err_ppc_builtin_only_on_arch, "9");
  3936. case PPC::BI__builtin_ppc_addex: {
  3937. if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
  3938. diag::err_ppc_builtin_only_on_arch, "9") ||
  3939. SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
  3940. return true;
  3941. // Output warning for reserved values 1 to 3.
  3942. int ArgValue =
  3943. TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
  3944. if (ArgValue != 0)
  3945. Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
  3946. << ArgValue;
  3947. return false;
  3948. }
  3949. case PPC::BI__builtin_ppc_mtfsb0:
  3950. case PPC::BI__builtin_ppc_mtfsb1:
  3951. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
  3952. case PPC::BI__builtin_ppc_mtfsf:
  3953. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
  3954. case PPC::BI__builtin_ppc_mtfsfi:
  3955. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
  3956. SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  3957. case PPC::BI__builtin_ppc_alignx:
  3958. return SemaBuiltinConstantArgPower2(TheCall, 0);
  3959. case PPC::BI__builtin_ppc_rdlam:
  3960. return SemaValueIsRunOfOnes(TheCall, 2);
  3961. case PPC::BI__builtin_ppc_icbt:
  3962. case PPC::BI__builtin_ppc_sthcx:
  3963. case PPC::BI__builtin_ppc_stbcx:
  3964. case PPC::BI__builtin_ppc_lharx:
  3965. case PPC::BI__builtin_ppc_lbarx:
  3966. return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
  3967. diag::err_ppc_builtin_only_on_arch, "8");
  3968. case PPC::BI__builtin_vsx_ldrmb:
  3969. case PPC::BI__builtin_vsx_strmb:
  3970. return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
  3971. diag::err_ppc_builtin_only_on_arch, "8") ||
  3972. SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  3973. case PPC::BI__builtin_altivec_vcntmbb:
  3974. case PPC::BI__builtin_altivec_vcntmbh:
  3975. case PPC::BI__builtin_altivec_vcntmbw:
  3976. case PPC::BI__builtin_altivec_vcntmbd:
  3977. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  3978. case PPC::BI__builtin_darn:
  3979. case PPC::BI__builtin_darn_raw:
  3980. case PPC::BI__builtin_darn_32:
  3981. return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
  3982. diag::err_ppc_builtin_only_on_arch, "9");
  3983. case PPC::BI__builtin_vsx_xxgenpcvbm:
  3984. case PPC::BI__builtin_vsx_xxgenpcvhm:
  3985. case PPC::BI__builtin_vsx_xxgenpcvwm:
  3986. case PPC::BI__builtin_vsx_xxgenpcvdm:
  3987. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
  3988. case PPC::BI__builtin_ppc_compare_exp_uo:
  3989. case PPC::BI__builtin_ppc_compare_exp_lt:
  3990. case PPC::BI__builtin_ppc_compare_exp_gt:
  3991. case PPC::BI__builtin_ppc_compare_exp_eq:
  3992. return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
  3993. diag::err_ppc_builtin_only_on_arch, "9") ||
  3994. SemaFeatureCheck(*this, TheCall, "vsx",
  3995. diag::err_ppc_builtin_requires_vsx);
  3996. case PPC::BI__builtin_ppc_test_data_class: {
  3997. // Check if the first argument of the __builtin_ppc_test_data_class call is
  3998. // valid. The argument must be 'float' or 'double' or '__float128'.
  3999. QualType ArgType = TheCall->getArg(0)->getType();
  4000. if (ArgType != QualType(Context.FloatTy) &&
  4001. ArgType != QualType(Context.DoubleTy) &&
  4002. ArgType != QualType(Context.Float128Ty))
  4003. return Diag(TheCall->getBeginLoc(),
  4004. diag::err_ppc_invalid_test_data_class_type);
  4005. return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
  4006. diag::err_ppc_builtin_only_on_arch, "9") ||
  4007. SemaFeatureCheck(*this, TheCall, "vsx",
  4008. diag::err_ppc_builtin_requires_vsx) ||
  4009. SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
  4010. }
  4011. case PPC::BI__builtin_ppc_maxfe:
  4012. case PPC::BI__builtin_ppc_minfe:
  4013. case PPC::BI__builtin_ppc_maxfl:
  4014. case PPC::BI__builtin_ppc_minfl:
  4015. case PPC::BI__builtin_ppc_maxfs:
  4016. case PPC::BI__builtin_ppc_minfs: {
  4017. if (Context.getTargetInfo().getTriple().isOSAIX() &&
  4018. (BuiltinID == PPC::BI__builtin_ppc_maxfe ||
  4019. BuiltinID == PPC::BI__builtin_ppc_minfe))
  4020. return Diag(TheCall->getBeginLoc(), diag::err_target_unsupported_type)
  4021. << "builtin" << true << 128 << QualType(Context.LongDoubleTy)
  4022. << false << Context.getTargetInfo().getTriple().str();
  4023. // Argument type should be exact.
  4024. QualType ArgType = QualType(Context.LongDoubleTy);
  4025. if (BuiltinID == PPC::BI__builtin_ppc_maxfl ||
  4026. BuiltinID == PPC::BI__builtin_ppc_minfl)
  4027. ArgType = QualType(Context.DoubleTy);
  4028. else if (BuiltinID == PPC::BI__builtin_ppc_maxfs ||
  4029. BuiltinID == PPC::BI__builtin_ppc_minfs)
  4030. ArgType = QualType(Context.FloatTy);
  4031. for (unsigned I = 0, E = TheCall->getNumArgs(); I < E; ++I)
  4032. if (TheCall->getArg(I)->getType() != ArgType)
  4033. return Diag(TheCall->getBeginLoc(),
  4034. diag::err_typecheck_convert_incompatible)
  4035. << TheCall->getArg(I)->getType() << ArgType << 1 << 0 << 0;
  4036. return false;
  4037. }
  4038. case PPC::BI__builtin_ppc_load8r:
  4039. case PPC::BI__builtin_ppc_store8r:
  4040. return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
  4041. diag::err_ppc_builtin_only_on_arch, "7");
  4042. #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
  4043. case PPC::BI__builtin_##Name: \
  4044. return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
  4045. #include "clang/Basic/BuiltinsPPC.def"
  4046. }
  4047. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  4048. }
  4049. // Check if the given type is a non-pointer PPC MMA type. This function is used
  4050. // in Sema to prevent invalid uses of restricted PPC MMA types.
  4051. bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
  4052. if (Type->isPointerType() || Type->isArrayType())
  4053. return false;
  4054. QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
  4055. #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
  4056. if (false
  4057. #include "clang/Basic/PPCTypes.def"
  4058. ) {
  4059. Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
  4060. return true;
  4061. }
  4062. return false;
  4063. }
  4064. bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
  4065. CallExpr *TheCall) {
  4066. // position of memory order and scope arguments in the builtin
  4067. unsigned OrderIndex, ScopeIndex;
  4068. switch (BuiltinID) {
  4069. case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
  4070. case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
  4071. case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
  4072. case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
  4073. OrderIndex = 2;
  4074. ScopeIndex = 3;
  4075. break;
  4076. case AMDGPU::BI__builtin_amdgcn_fence:
  4077. OrderIndex = 0;
  4078. ScopeIndex = 1;
  4079. break;
  4080. default:
  4081. return false;
  4082. }
  4083. ExprResult Arg = TheCall->getArg(OrderIndex);
  4084. auto ArgExpr = Arg.get();
  4085. Expr::EvalResult ArgResult;
  4086. if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
  4087. return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
  4088. << ArgExpr->getType();
  4089. auto Ord = ArgResult.Val.getInt().getZExtValue();
  4090. // Check validity of memory ordering as per C11 / C++11's memody model.
  4091. // Only fence needs check. Atomic dec/inc allow all memory orders.
  4092. if (!llvm::isValidAtomicOrderingCABI(Ord))
  4093. return Diag(ArgExpr->getBeginLoc(),
  4094. diag::warn_atomic_op_has_invalid_memory_order)
  4095. << ArgExpr->getSourceRange();
  4096. switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
  4097. case llvm::AtomicOrderingCABI::relaxed:
  4098. case llvm::AtomicOrderingCABI::consume:
  4099. if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
  4100. return Diag(ArgExpr->getBeginLoc(),
  4101. diag::warn_atomic_op_has_invalid_memory_order)
  4102. << ArgExpr->getSourceRange();
  4103. break;
  4104. case llvm::AtomicOrderingCABI::acquire:
  4105. case llvm::AtomicOrderingCABI::release:
  4106. case llvm::AtomicOrderingCABI::acq_rel:
  4107. case llvm::AtomicOrderingCABI::seq_cst:
  4108. break;
  4109. }
  4110. Arg = TheCall->getArg(ScopeIndex);
  4111. ArgExpr = Arg.get();
  4112. Expr::EvalResult ArgResult1;
  4113. // Check that sync scope is a constant literal
  4114. if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
  4115. return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
  4116. << ArgExpr->getType();
  4117. return false;
  4118. }
  4119. bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
  4120. llvm::APSInt Result;
  4121. // We can't check the value of a dependent argument.
  4122. Expr *Arg = TheCall->getArg(ArgNum);
  4123. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4124. return false;
  4125. // Check constant-ness first.
  4126. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4127. return true;
  4128. int64_t Val = Result.getSExtValue();
  4129. if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
  4130. return false;
  4131. return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
  4132. << Arg->getSourceRange();
  4133. }
  4134. bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
  4135. unsigned BuiltinID,
  4136. CallExpr *TheCall) {
  4137. // CodeGenFunction can also detect this, but this gives a better error
  4138. // message.
  4139. bool FeatureMissing = false;
  4140. SmallVector<StringRef> ReqFeatures;
  4141. StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
  4142. Features.split(ReqFeatures, ',');
  4143. // Check if each required feature is included
  4144. for (StringRef F : ReqFeatures) {
  4145. SmallVector<StringRef> ReqOpFeatures;
  4146. F.split(ReqOpFeatures, '|');
  4147. if (llvm::none_of(ReqOpFeatures,
  4148. [&TI](StringRef OF) { return TI.hasFeature(OF); })) {
  4149. std::string FeatureStrs;
  4150. bool IsExtension = true;
  4151. for (StringRef OF : ReqOpFeatures) {
  4152. // If the feature is 64bit, alter the string so it will print better in
  4153. // the diagnostic.
  4154. if (OF == "64bit") {
  4155. assert(ReqOpFeatures.size() == 1 && "Expected '64bit' to be alone");
  4156. OF = "RV64";
  4157. IsExtension = false;
  4158. }
  4159. if (OF == "32bit") {
  4160. assert(ReqOpFeatures.size() == 1 && "Expected '32bit' to be alone");
  4161. OF = "RV32";
  4162. IsExtension = false;
  4163. }
  4164. // Convert features like "zbr" and "experimental-zbr" to "Zbr".
  4165. OF.consume_front("experimental-");
  4166. std::string FeatureStr = OF.str();
  4167. FeatureStr[0] = std::toupper(FeatureStr[0]);
  4168. // Combine strings.
  4169. FeatureStrs += FeatureStrs == "" ? "" : ", ";
  4170. FeatureStrs += "'";
  4171. FeatureStrs += FeatureStr;
  4172. FeatureStrs += "'";
  4173. }
  4174. // Error message
  4175. FeatureMissing = true;
  4176. Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
  4177. << IsExtension
  4178. << TheCall->getSourceRange() << StringRef(FeatureStrs);
  4179. }
  4180. }
  4181. if (FeatureMissing)
  4182. return true;
  4183. switch (BuiltinID) {
  4184. case RISCVVector::BI__builtin_rvv_vsetvli:
  4185. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
  4186. CheckRISCVLMUL(TheCall, 2);
  4187. case RISCVVector::BI__builtin_rvv_vsetvlimax:
  4188. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
  4189. CheckRISCVLMUL(TheCall, 1);
  4190. case RISCVVector::BI__builtin_rvv_vget_v: {
  4191. ASTContext::BuiltinVectorTypeInfo ResVecInfo =
  4192. Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
  4193. TheCall->getType().getCanonicalType().getTypePtr()));
  4194. ASTContext::BuiltinVectorTypeInfo VecInfo =
  4195. Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
  4196. TheCall->getArg(0)->getType().getCanonicalType().getTypePtr()));
  4197. unsigned MaxIndex =
  4198. (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors) /
  4199. (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors);
  4200. return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
  4201. }
  4202. case RISCVVector::BI__builtin_rvv_vset_v: {
  4203. ASTContext::BuiltinVectorTypeInfo ResVecInfo =
  4204. Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
  4205. TheCall->getType().getCanonicalType().getTypePtr()));
  4206. ASTContext::BuiltinVectorTypeInfo VecInfo =
  4207. Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
  4208. TheCall->getArg(2)->getType().getCanonicalType().getTypePtr()));
  4209. unsigned MaxIndex =
  4210. (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors) /
  4211. (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors);
  4212. return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
  4213. }
  4214. // Check if byteselect is in [0, 3]
  4215. case RISCV::BI__builtin_riscv_aes32dsi_32:
  4216. case RISCV::BI__builtin_riscv_aes32dsmi_32:
  4217. case RISCV::BI__builtin_riscv_aes32esi_32:
  4218. case RISCV::BI__builtin_riscv_aes32esmi_32:
  4219. case RISCV::BI__builtin_riscv_sm4ks:
  4220. case RISCV::BI__builtin_riscv_sm4ed:
  4221. return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
  4222. // Check if rnum is in [0, 10]
  4223. case RISCV::BI__builtin_riscv_aes64ks1i_64:
  4224. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 10);
  4225. }
  4226. return false;
  4227. }
  4228. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  4229. CallExpr *TheCall) {
  4230. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  4231. Expr *Arg = TheCall->getArg(0);
  4232. if (std::optional<llvm::APSInt> AbortCode =
  4233. Arg->getIntegerConstantExpr(Context))
  4234. if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
  4235. return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
  4236. << Arg->getSourceRange();
  4237. }
  4238. // For intrinsics which take an immediate value as part of the instruction,
  4239. // range check them here.
  4240. unsigned i = 0, l = 0, u = 0;
  4241. switch (BuiltinID) {
  4242. default: return false;
  4243. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  4244. case SystemZ::BI__builtin_s390_verimb:
  4245. case SystemZ::BI__builtin_s390_verimh:
  4246. case SystemZ::BI__builtin_s390_verimf:
  4247. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  4248. case SystemZ::BI__builtin_s390_vfaeb:
  4249. case SystemZ::BI__builtin_s390_vfaeh:
  4250. case SystemZ::BI__builtin_s390_vfaef:
  4251. case SystemZ::BI__builtin_s390_vfaebs:
  4252. case SystemZ::BI__builtin_s390_vfaehs:
  4253. case SystemZ::BI__builtin_s390_vfaefs:
  4254. case SystemZ::BI__builtin_s390_vfaezb:
  4255. case SystemZ::BI__builtin_s390_vfaezh:
  4256. case SystemZ::BI__builtin_s390_vfaezf:
  4257. case SystemZ::BI__builtin_s390_vfaezbs:
  4258. case SystemZ::BI__builtin_s390_vfaezhs:
  4259. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  4260. case SystemZ::BI__builtin_s390_vfisb:
  4261. case SystemZ::BI__builtin_s390_vfidb:
  4262. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  4263. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  4264. case SystemZ::BI__builtin_s390_vftcisb:
  4265. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  4266. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  4267. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  4268. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  4269. case SystemZ::BI__builtin_s390_vstrcb:
  4270. case SystemZ::BI__builtin_s390_vstrch:
  4271. case SystemZ::BI__builtin_s390_vstrcf:
  4272. case SystemZ::BI__builtin_s390_vstrczb:
  4273. case SystemZ::BI__builtin_s390_vstrczh:
  4274. case SystemZ::BI__builtin_s390_vstrczf:
  4275. case SystemZ::BI__builtin_s390_vstrcbs:
  4276. case SystemZ::BI__builtin_s390_vstrchs:
  4277. case SystemZ::BI__builtin_s390_vstrcfs:
  4278. case SystemZ::BI__builtin_s390_vstrczbs:
  4279. case SystemZ::BI__builtin_s390_vstrczhs:
  4280. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  4281. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  4282. case SystemZ::BI__builtin_s390_vfminsb:
  4283. case SystemZ::BI__builtin_s390_vfmaxsb:
  4284. case SystemZ::BI__builtin_s390_vfmindb:
  4285. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  4286. case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
  4287. case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
  4288. case SystemZ::BI__builtin_s390_vclfnhs:
  4289. case SystemZ::BI__builtin_s390_vclfnls:
  4290. case SystemZ::BI__builtin_s390_vcfn:
  4291. case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
  4292. case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
  4293. }
  4294. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  4295. }
  4296. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  4297. /// This checks that the target supports __builtin_cpu_supports and
  4298. /// that the string argument is constant and valid.
  4299. static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
  4300. CallExpr *TheCall) {
  4301. Expr *Arg = TheCall->getArg(0);
  4302. // Check if the argument is a string literal.
  4303. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  4304. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  4305. << Arg->getSourceRange();
  4306. // Check the contents of the string.
  4307. StringRef Feature =
  4308. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  4309. if (!TI.validateCpuSupports(Feature))
  4310. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
  4311. << Arg->getSourceRange();
  4312. return false;
  4313. }
  4314. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  4315. /// This checks that the target supports __builtin_cpu_is and
  4316. /// that the string argument is constant and valid.
  4317. static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
  4318. Expr *Arg = TheCall->getArg(0);
  4319. // Check if the argument is a string literal.
  4320. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  4321. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  4322. << Arg->getSourceRange();
  4323. // Check the contents of the string.
  4324. StringRef Feature =
  4325. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  4326. if (!TI.validateCpuIs(Feature))
  4327. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
  4328. << Arg->getSourceRange();
  4329. return false;
  4330. }
  4331. // Check if the rounding mode is legal.
  4332. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  4333. // Indicates if this instruction has rounding control or just SAE.
  4334. bool HasRC = false;
  4335. unsigned ArgNum = 0;
  4336. switch (BuiltinID) {
  4337. default:
  4338. return false;
  4339. case X86::BI__builtin_ia32_vcvttsd2si32:
  4340. case X86::BI__builtin_ia32_vcvttsd2si64:
  4341. case X86::BI__builtin_ia32_vcvttsd2usi32:
  4342. case X86::BI__builtin_ia32_vcvttsd2usi64:
  4343. case X86::BI__builtin_ia32_vcvttss2si32:
  4344. case X86::BI__builtin_ia32_vcvttss2si64:
  4345. case X86::BI__builtin_ia32_vcvttss2usi32:
  4346. case X86::BI__builtin_ia32_vcvttss2usi64:
  4347. case X86::BI__builtin_ia32_vcvttsh2si32:
  4348. case X86::BI__builtin_ia32_vcvttsh2si64:
  4349. case X86::BI__builtin_ia32_vcvttsh2usi32:
  4350. case X86::BI__builtin_ia32_vcvttsh2usi64:
  4351. ArgNum = 1;
  4352. break;
  4353. case X86::BI__builtin_ia32_maxpd512:
  4354. case X86::BI__builtin_ia32_maxps512:
  4355. case X86::BI__builtin_ia32_minpd512:
  4356. case X86::BI__builtin_ia32_minps512:
  4357. case X86::BI__builtin_ia32_maxph512:
  4358. case X86::BI__builtin_ia32_minph512:
  4359. ArgNum = 2;
  4360. break;
  4361. case X86::BI__builtin_ia32_vcvtph2pd512_mask:
  4362. case X86::BI__builtin_ia32_vcvtph2psx512_mask:
  4363. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  4364. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  4365. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  4366. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  4367. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  4368. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  4369. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  4370. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  4371. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  4372. case X86::BI__builtin_ia32_vcvttph2w512_mask:
  4373. case X86::BI__builtin_ia32_vcvttph2uw512_mask:
  4374. case X86::BI__builtin_ia32_vcvttph2dq512_mask:
  4375. case X86::BI__builtin_ia32_vcvttph2udq512_mask:
  4376. case X86::BI__builtin_ia32_vcvttph2qq512_mask:
  4377. case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
  4378. case X86::BI__builtin_ia32_exp2pd_mask:
  4379. case X86::BI__builtin_ia32_exp2ps_mask:
  4380. case X86::BI__builtin_ia32_getexppd512_mask:
  4381. case X86::BI__builtin_ia32_getexpps512_mask:
  4382. case X86::BI__builtin_ia32_getexpph512_mask:
  4383. case X86::BI__builtin_ia32_rcp28pd_mask:
  4384. case X86::BI__builtin_ia32_rcp28ps_mask:
  4385. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  4386. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  4387. case X86::BI__builtin_ia32_vcomisd:
  4388. case X86::BI__builtin_ia32_vcomiss:
  4389. case X86::BI__builtin_ia32_vcomish:
  4390. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  4391. ArgNum = 3;
  4392. break;
  4393. case X86::BI__builtin_ia32_cmppd512_mask:
  4394. case X86::BI__builtin_ia32_cmpps512_mask:
  4395. case X86::BI__builtin_ia32_cmpsd_mask:
  4396. case X86::BI__builtin_ia32_cmpss_mask:
  4397. case X86::BI__builtin_ia32_cmpsh_mask:
  4398. case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
  4399. case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
  4400. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  4401. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  4402. case X86::BI__builtin_ia32_getexpss128_round_mask:
  4403. case X86::BI__builtin_ia32_getexpsh128_round_mask:
  4404. case X86::BI__builtin_ia32_getmantpd512_mask:
  4405. case X86::BI__builtin_ia32_getmantps512_mask:
  4406. case X86::BI__builtin_ia32_getmantph512_mask:
  4407. case X86::BI__builtin_ia32_maxsd_round_mask:
  4408. case X86::BI__builtin_ia32_maxss_round_mask:
  4409. case X86::BI__builtin_ia32_maxsh_round_mask:
  4410. case X86::BI__builtin_ia32_minsd_round_mask:
  4411. case X86::BI__builtin_ia32_minss_round_mask:
  4412. case X86::BI__builtin_ia32_minsh_round_mask:
  4413. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  4414. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  4415. case X86::BI__builtin_ia32_reducepd512_mask:
  4416. case X86::BI__builtin_ia32_reduceps512_mask:
  4417. case X86::BI__builtin_ia32_reduceph512_mask:
  4418. case X86::BI__builtin_ia32_rndscalepd_mask:
  4419. case X86::BI__builtin_ia32_rndscaleps_mask:
  4420. case X86::BI__builtin_ia32_rndscaleph_mask:
  4421. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  4422. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  4423. ArgNum = 4;
  4424. break;
  4425. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  4426. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  4427. case X86::BI__builtin_ia32_fixupimmps512_mask:
  4428. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  4429. case X86::BI__builtin_ia32_fixupimmsd_mask:
  4430. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  4431. case X86::BI__builtin_ia32_fixupimmss_mask:
  4432. case X86::BI__builtin_ia32_fixupimmss_maskz:
  4433. case X86::BI__builtin_ia32_getmantsd_round_mask:
  4434. case X86::BI__builtin_ia32_getmantss_round_mask:
  4435. case X86::BI__builtin_ia32_getmantsh_round_mask:
  4436. case X86::BI__builtin_ia32_rangepd512_mask:
  4437. case X86::BI__builtin_ia32_rangeps512_mask:
  4438. case X86::BI__builtin_ia32_rangesd128_round_mask:
  4439. case X86::BI__builtin_ia32_rangess128_round_mask:
  4440. case X86::BI__builtin_ia32_reducesd_mask:
  4441. case X86::BI__builtin_ia32_reducess_mask:
  4442. case X86::BI__builtin_ia32_reducesh_mask:
  4443. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  4444. case X86::BI__builtin_ia32_rndscaless_round_mask:
  4445. case X86::BI__builtin_ia32_rndscalesh_round_mask:
  4446. ArgNum = 5;
  4447. break;
  4448. case X86::BI__builtin_ia32_vcvtsd2si64:
  4449. case X86::BI__builtin_ia32_vcvtsd2si32:
  4450. case X86::BI__builtin_ia32_vcvtsd2usi32:
  4451. case X86::BI__builtin_ia32_vcvtsd2usi64:
  4452. case X86::BI__builtin_ia32_vcvtss2si32:
  4453. case X86::BI__builtin_ia32_vcvtss2si64:
  4454. case X86::BI__builtin_ia32_vcvtss2usi32:
  4455. case X86::BI__builtin_ia32_vcvtss2usi64:
  4456. case X86::BI__builtin_ia32_vcvtsh2si32:
  4457. case X86::BI__builtin_ia32_vcvtsh2si64:
  4458. case X86::BI__builtin_ia32_vcvtsh2usi32:
  4459. case X86::BI__builtin_ia32_vcvtsh2usi64:
  4460. case X86::BI__builtin_ia32_sqrtpd512:
  4461. case X86::BI__builtin_ia32_sqrtps512:
  4462. case X86::BI__builtin_ia32_sqrtph512:
  4463. ArgNum = 1;
  4464. HasRC = true;
  4465. break;
  4466. case X86::BI__builtin_ia32_addph512:
  4467. case X86::BI__builtin_ia32_divph512:
  4468. case X86::BI__builtin_ia32_mulph512:
  4469. case X86::BI__builtin_ia32_subph512:
  4470. case X86::BI__builtin_ia32_addpd512:
  4471. case X86::BI__builtin_ia32_addps512:
  4472. case X86::BI__builtin_ia32_divpd512:
  4473. case X86::BI__builtin_ia32_divps512:
  4474. case X86::BI__builtin_ia32_mulpd512:
  4475. case X86::BI__builtin_ia32_mulps512:
  4476. case X86::BI__builtin_ia32_subpd512:
  4477. case X86::BI__builtin_ia32_subps512:
  4478. case X86::BI__builtin_ia32_cvtsi2sd64:
  4479. case X86::BI__builtin_ia32_cvtsi2ss32:
  4480. case X86::BI__builtin_ia32_cvtsi2ss64:
  4481. case X86::BI__builtin_ia32_cvtusi2sd64:
  4482. case X86::BI__builtin_ia32_cvtusi2ss32:
  4483. case X86::BI__builtin_ia32_cvtusi2ss64:
  4484. case X86::BI__builtin_ia32_vcvtusi2sh:
  4485. case X86::BI__builtin_ia32_vcvtusi642sh:
  4486. case X86::BI__builtin_ia32_vcvtsi2sh:
  4487. case X86::BI__builtin_ia32_vcvtsi642sh:
  4488. ArgNum = 2;
  4489. HasRC = true;
  4490. break;
  4491. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  4492. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  4493. case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
  4494. case X86::BI__builtin_ia32_vcvtps2phx512_mask:
  4495. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  4496. case X86::BI__builtin_ia32_cvtpd2dq512_mask:
  4497. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  4498. case X86::BI__builtin_ia32_cvtpd2udq512_mask:
  4499. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  4500. case X86::BI__builtin_ia32_cvtps2dq512_mask:
  4501. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  4502. case X86::BI__builtin_ia32_cvtps2udq512_mask:
  4503. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  4504. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  4505. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  4506. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  4507. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  4508. case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
  4509. case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
  4510. case X86::BI__builtin_ia32_vcvtw2ph512_mask:
  4511. case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
  4512. case X86::BI__builtin_ia32_vcvtph2w512_mask:
  4513. case X86::BI__builtin_ia32_vcvtph2uw512_mask:
  4514. case X86::BI__builtin_ia32_vcvtph2dq512_mask:
  4515. case X86::BI__builtin_ia32_vcvtph2udq512_mask:
  4516. case X86::BI__builtin_ia32_vcvtph2qq512_mask:
  4517. case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
  4518. case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
  4519. case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
  4520. ArgNum = 3;
  4521. HasRC = true;
  4522. break;
  4523. case X86::BI__builtin_ia32_addsh_round_mask:
  4524. case X86::BI__builtin_ia32_addss_round_mask:
  4525. case X86::BI__builtin_ia32_addsd_round_mask:
  4526. case X86::BI__builtin_ia32_divsh_round_mask:
  4527. case X86::BI__builtin_ia32_divss_round_mask:
  4528. case X86::BI__builtin_ia32_divsd_round_mask:
  4529. case X86::BI__builtin_ia32_mulsh_round_mask:
  4530. case X86::BI__builtin_ia32_mulss_round_mask:
  4531. case X86::BI__builtin_ia32_mulsd_round_mask:
  4532. case X86::BI__builtin_ia32_subsh_round_mask:
  4533. case X86::BI__builtin_ia32_subss_round_mask:
  4534. case X86::BI__builtin_ia32_subsd_round_mask:
  4535. case X86::BI__builtin_ia32_scalefph512_mask:
  4536. case X86::BI__builtin_ia32_scalefpd512_mask:
  4537. case X86::BI__builtin_ia32_scalefps512_mask:
  4538. case X86::BI__builtin_ia32_scalefsd_round_mask:
  4539. case X86::BI__builtin_ia32_scalefss_round_mask:
  4540. case X86::BI__builtin_ia32_scalefsh_round_mask:
  4541. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  4542. case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
  4543. case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
  4544. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  4545. case X86::BI__builtin_ia32_sqrtss_round_mask:
  4546. case X86::BI__builtin_ia32_sqrtsh_round_mask:
  4547. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  4548. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  4549. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  4550. case X86::BI__builtin_ia32_vfmaddss3_mask:
  4551. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  4552. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  4553. case X86::BI__builtin_ia32_vfmaddsh3_mask:
  4554. case X86::BI__builtin_ia32_vfmaddsh3_maskz:
  4555. case X86::BI__builtin_ia32_vfmaddsh3_mask3:
  4556. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  4557. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  4558. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  4559. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  4560. case X86::BI__builtin_ia32_vfmaddps512_mask:
  4561. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  4562. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  4563. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  4564. case X86::BI__builtin_ia32_vfmaddph512_mask:
  4565. case X86::BI__builtin_ia32_vfmaddph512_maskz:
  4566. case X86::BI__builtin_ia32_vfmaddph512_mask3:
  4567. case X86::BI__builtin_ia32_vfmsubph512_mask3:
  4568. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  4569. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  4570. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  4571. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  4572. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  4573. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  4574. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  4575. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  4576. case X86::BI__builtin_ia32_vfmaddsubph512_mask:
  4577. case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
  4578. case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
  4579. case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
  4580. case X86::BI__builtin_ia32_vfmaddcsh_mask:
  4581. case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
  4582. case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
  4583. case X86::BI__builtin_ia32_vfmaddcph512_mask:
  4584. case X86::BI__builtin_ia32_vfmaddcph512_maskz:
  4585. case X86::BI__builtin_ia32_vfmaddcph512_mask3:
  4586. case X86::BI__builtin_ia32_vfcmaddcsh_mask:
  4587. case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
  4588. case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
  4589. case X86::BI__builtin_ia32_vfcmaddcph512_mask:
  4590. case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
  4591. case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
  4592. case X86::BI__builtin_ia32_vfmulcsh_mask:
  4593. case X86::BI__builtin_ia32_vfmulcph512_mask:
  4594. case X86::BI__builtin_ia32_vfcmulcsh_mask:
  4595. case X86::BI__builtin_ia32_vfcmulcph512_mask:
  4596. ArgNum = 4;
  4597. HasRC = true;
  4598. break;
  4599. }
  4600. llvm::APSInt Result;
  4601. // We can't check the value of a dependent argument.
  4602. Expr *Arg = TheCall->getArg(ArgNum);
  4603. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4604. return false;
  4605. // Check constant-ness first.
  4606. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4607. return true;
  4608. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  4609. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  4610. // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
  4611. // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
  4612. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  4613. Result == 8/*ROUND_NO_EXC*/ ||
  4614. (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
  4615. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  4616. return false;
  4617. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
  4618. << Arg->getSourceRange();
  4619. }
  4620. // Check if the gather/scatter scale is legal.
  4621. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  4622. CallExpr *TheCall) {
  4623. unsigned ArgNum = 0;
  4624. switch (BuiltinID) {
  4625. default:
  4626. return false;
  4627. case X86::BI__builtin_ia32_gatherpfdpd:
  4628. case X86::BI__builtin_ia32_gatherpfdps:
  4629. case X86::BI__builtin_ia32_gatherpfqpd:
  4630. case X86::BI__builtin_ia32_gatherpfqps:
  4631. case X86::BI__builtin_ia32_scatterpfdpd:
  4632. case X86::BI__builtin_ia32_scatterpfdps:
  4633. case X86::BI__builtin_ia32_scatterpfqpd:
  4634. case X86::BI__builtin_ia32_scatterpfqps:
  4635. ArgNum = 3;
  4636. break;
  4637. case X86::BI__builtin_ia32_gatherd_pd:
  4638. case X86::BI__builtin_ia32_gatherd_pd256:
  4639. case X86::BI__builtin_ia32_gatherq_pd:
  4640. case X86::BI__builtin_ia32_gatherq_pd256:
  4641. case X86::BI__builtin_ia32_gatherd_ps:
  4642. case X86::BI__builtin_ia32_gatherd_ps256:
  4643. case X86::BI__builtin_ia32_gatherq_ps:
  4644. case X86::BI__builtin_ia32_gatherq_ps256:
  4645. case X86::BI__builtin_ia32_gatherd_q:
  4646. case X86::BI__builtin_ia32_gatherd_q256:
  4647. case X86::BI__builtin_ia32_gatherq_q:
  4648. case X86::BI__builtin_ia32_gatherq_q256:
  4649. case X86::BI__builtin_ia32_gatherd_d:
  4650. case X86::BI__builtin_ia32_gatherd_d256:
  4651. case X86::BI__builtin_ia32_gatherq_d:
  4652. case X86::BI__builtin_ia32_gatherq_d256:
  4653. case X86::BI__builtin_ia32_gather3div2df:
  4654. case X86::BI__builtin_ia32_gather3div2di:
  4655. case X86::BI__builtin_ia32_gather3div4df:
  4656. case X86::BI__builtin_ia32_gather3div4di:
  4657. case X86::BI__builtin_ia32_gather3div4sf:
  4658. case X86::BI__builtin_ia32_gather3div4si:
  4659. case X86::BI__builtin_ia32_gather3div8sf:
  4660. case X86::BI__builtin_ia32_gather3div8si:
  4661. case X86::BI__builtin_ia32_gather3siv2df:
  4662. case X86::BI__builtin_ia32_gather3siv2di:
  4663. case X86::BI__builtin_ia32_gather3siv4df:
  4664. case X86::BI__builtin_ia32_gather3siv4di:
  4665. case X86::BI__builtin_ia32_gather3siv4sf:
  4666. case X86::BI__builtin_ia32_gather3siv4si:
  4667. case X86::BI__builtin_ia32_gather3siv8sf:
  4668. case X86::BI__builtin_ia32_gather3siv8si:
  4669. case X86::BI__builtin_ia32_gathersiv8df:
  4670. case X86::BI__builtin_ia32_gathersiv16sf:
  4671. case X86::BI__builtin_ia32_gatherdiv8df:
  4672. case X86::BI__builtin_ia32_gatherdiv16sf:
  4673. case X86::BI__builtin_ia32_gathersiv8di:
  4674. case X86::BI__builtin_ia32_gathersiv16si:
  4675. case X86::BI__builtin_ia32_gatherdiv8di:
  4676. case X86::BI__builtin_ia32_gatherdiv16si:
  4677. case X86::BI__builtin_ia32_scatterdiv2df:
  4678. case X86::BI__builtin_ia32_scatterdiv2di:
  4679. case X86::BI__builtin_ia32_scatterdiv4df:
  4680. case X86::BI__builtin_ia32_scatterdiv4di:
  4681. case X86::BI__builtin_ia32_scatterdiv4sf:
  4682. case X86::BI__builtin_ia32_scatterdiv4si:
  4683. case X86::BI__builtin_ia32_scatterdiv8sf:
  4684. case X86::BI__builtin_ia32_scatterdiv8si:
  4685. case X86::BI__builtin_ia32_scattersiv2df:
  4686. case X86::BI__builtin_ia32_scattersiv2di:
  4687. case X86::BI__builtin_ia32_scattersiv4df:
  4688. case X86::BI__builtin_ia32_scattersiv4di:
  4689. case X86::BI__builtin_ia32_scattersiv4sf:
  4690. case X86::BI__builtin_ia32_scattersiv4si:
  4691. case X86::BI__builtin_ia32_scattersiv8sf:
  4692. case X86::BI__builtin_ia32_scattersiv8si:
  4693. case X86::BI__builtin_ia32_scattersiv8df:
  4694. case X86::BI__builtin_ia32_scattersiv16sf:
  4695. case X86::BI__builtin_ia32_scatterdiv8df:
  4696. case X86::BI__builtin_ia32_scatterdiv16sf:
  4697. case X86::BI__builtin_ia32_scattersiv8di:
  4698. case X86::BI__builtin_ia32_scattersiv16si:
  4699. case X86::BI__builtin_ia32_scatterdiv8di:
  4700. case X86::BI__builtin_ia32_scatterdiv16si:
  4701. ArgNum = 4;
  4702. break;
  4703. }
  4704. llvm::APSInt Result;
  4705. // We can't check the value of a dependent argument.
  4706. Expr *Arg = TheCall->getArg(ArgNum);
  4707. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4708. return false;
  4709. // Check constant-ness first.
  4710. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4711. return true;
  4712. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  4713. return false;
  4714. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
  4715. << Arg->getSourceRange();
  4716. }
  4717. enum { TileRegLow = 0, TileRegHigh = 7 };
  4718. bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
  4719. ArrayRef<int> ArgNums) {
  4720. for (int ArgNum : ArgNums) {
  4721. if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
  4722. return true;
  4723. }
  4724. return false;
  4725. }
  4726. bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
  4727. ArrayRef<int> ArgNums) {
  4728. // Because the max number of tile register is TileRegHigh + 1, so here we use
  4729. // each bit to represent the usage of them in bitset.
  4730. std::bitset<TileRegHigh + 1> ArgValues;
  4731. for (int ArgNum : ArgNums) {
  4732. Expr *Arg = TheCall->getArg(ArgNum);
  4733. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4734. continue;
  4735. llvm::APSInt Result;
  4736. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4737. return true;
  4738. int ArgExtValue = Result.getExtValue();
  4739. assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
  4740. "Incorrect tile register num.");
  4741. if (ArgValues.test(ArgExtValue))
  4742. return Diag(TheCall->getBeginLoc(),
  4743. diag::err_x86_builtin_tile_arg_duplicate)
  4744. << TheCall->getArg(ArgNum)->getSourceRange();
  4745. ArgValues.set(ArgExtValue);
  4746. }
  4747. return false;
  4748. }
  4749. bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
  4750. ArrayRef<int> ArgNums) {
  4751. return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
  4752. CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
  4753. }
  4754. bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
  4755. switch (BuiltinID) {
  4756. default:
  4757. return false;
  4758. case X86::BI__builtin_ia32_tileloadd64:
  4759. case X86::BI__builtin_ia32_tileloaddt164:
  4760. case X86::BI__builtin_ia32_tilestored64:
  4761. case X86::BI__builtin_ia32_tilezero:
  4762. return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
  4763. case X86::BI__builtin_ia32_tdpbssd:
  4764. case X86::BI__builtin_ia32_tdpbsud:
  4765. case X86::BI__builtin_ia32_tdpbusd:
  4766. case X86::BI__builtin_ia32_tdpbuud:
  4767. case X86::BI__builtin_ia32_tdpbf16ps:
  4768. case X86::BI__builtin_ia32_tdpfp16ps:
  4769. return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
  4770. }
  4771. }
  4772. static bool isX86_32Builtin(unsigned BuiltinID) {
  4773. // These builtins only work on x86-32 targets.
  4774. switch (BuiltinID) {
  4775. case X86::BI__builtin_ia32_readeflags_u32:
  4776. case X86::BI__builtin_ia32_writeeflags_u32:
  4777. return true;
  4778. }
  4779. return false;
  4780. }
  4781. bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
  4782. CallExpr *TheCall) {
  4783. if (BuiltinID == X86::BI__builtin_cpu_supports)
  4784. return SemaBuiltinCpuSupports(*this, TI, TheCall);
  4785. if (BuiltinID == X86::BI__builtin_cpu_is)
  4786. return SemaBuiltinCpuIs(*this, TI, TheCall);
  4787. // Check for 32-bit only builtins on a 64-bit target.
  4788. const llvm::Triple &TT = TI.getTriple();
  4789. if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
  4790. return Diag(TheCall->getCallee()->getBeginLoc(),
  4791. diag::err_32_bit_builtin_64_bit_tgt);
  4792. // If the intrinsic has rounding or SAE make sure its valid.
  4793. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  4794. return true;
  4795. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  4796. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  4797. return true;
  4798. // If the intrinsic has a tile arguments, make sure they are valid.
  4799. if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
  4800. return true;
  4801. // For intrinsics which take an immediate value as part of the instruction,
  4802. // range check them here.
  4803. int i = 0, l = 0, u = 0;
  4804. switch (BuiltinID) {
  4805. default:
  4806. return false;
  4807. case X86::BI__builtin_ia32_vec_ext_v2si:
  4808. case X86::BI__builtin_ia32_vec_ext_v2di:
  4809. case X86::BI__builtin_ia32_vextractf128_pd256:
  4810. case X86::BI__builtin_ia32_vextractf128_ps256:
  4811. case X86::BI__builtin_ia32_vextractf128_si256:
  4812. case X86::BI__builtin_ia32_extract128i256:
  4813. case X86::BI__builtin_ia32_extractf64x4_mask:
  4814. case X86::BI__builtin_ia32_extracti64x4_mask:
  4815. case X86::BI__builtin_ia32_extractf32x8_mask:
  4816. case X86::BI__builtin_ia32_extracti32x8_mask:
  4817. case X86::BI__builtin_ia32_extractf64x2_256_mask:
  4818. case X86::BI__builtin_ia32_extracti64x2_256_mask:
  4819. case X86::BI__builtin_ia32_extractf32x4_256_mask:
  4820. case X86::BI__builtin_ia32_extracti32x4_256_mask:
  4821. i = 1; l = 0; u = 1;
  4822. break;
  4823. case X86::BI__builtin_ia32_vec_set_v2di:
  4824. case X86::BI__builtin_ia32_vinsertf128_pd256:
  4825. case X86::BI__builtin_ia32_vinsertf128_ps256:
  4826. case X86::BI__builtin_ia32_vinsertf128_si256:
  4827. case X86::BI__builtin_ia32_insert128i256:
  4828. case X86::BI__builtin_ia32_insertf32x8:
  4829. case X86::BI__builtin_ia32_inserti32x8:
  4830. case X86::BI__builtin_ia32_insertf64x4:
  4831. case X86::BI__builtin_ia32_inserti64x4:
  4832. case X86::BI__builtin_ia32_insertf64x2_256:
  4833. case X86::BI__builtin_ia32_inserti64x2_256:
  4834. case X86::BI__builtin_ia32_insertf32x4_256:
  4835. case X86::BI__builtin_ia32_inserti32x4_256:
  4836. i = 2; l = 0; u = 1;
  4837. break;
  4838. case X86::BI__builtin_ia32_vpermilpd:
  4839. case X86::BI__builtin_ia32_vec_ext_v4hi:
  4840. case X86::BI__builtin_ia32_vec_ext_v4si:
  4841. case X86::BI__builtin_ia32_vec_ext_v4sf:
  4842. case X86::BI__builtin_ia32_vec_ext_v4di:
  4843. case X86::BI__builtin_ia32_extractf32x4_mask:
  4844. case X86::BI__builtin_ia32_extracti32x4_mask:
  4845. case X86::BI__builtin_ia32_extractf64x2_512_mask:
  4846. case X86::BI__builtin_ia32_extracti64x2_512_mask:
  4847. i = 1; l = 0; u = 3;
  4848. break;
  4849. case X86::BI_mm_prefetch:
  4850. case X86::BI__builtin_ia32_vec_ext_v8hi:
  4851. case X86::BI__builtin_ia32_vec_ext_v8si:
  4852. i = 1; l = 0; u = 7;
  4853. break;
  4854. case X86::BI__builtin_ia32_sha1rnds4:
  4855. case X86::BI__builtin_ia32_blendpd:
  4856. case X86::BI__builtin_ia32_shufpd:
  4857. case X86::BI__builtin_ia32_vec_set_v4hi:
  4858. case X86::BI__builtin_ia32_vec_set_v4si:
  4859. case X86::BI__builtin_ia32_vec_set_v4di:
  4860. case X86::BI__builtin_ia32_shuf_f32x4_256:
  4861. case X86::BI__builtin_ia32_shuf_f64x2_256:
  4862. case X86::BI__builtin_ia32_shuf_i32x4_256:
  4863. case X86::BI__builtin_ia32_shuf_i64x2_256:
  4864. case X86::BI__builtin_ia32_insertf64x2_512:
  4865. case X86::BI__builtin_ia32_inserti64x2_512:
  4866. case X86::BI__builtin_ia32_insertf32x4:
  4867. case X86::BI__builtin_ia32_inserti32x4:
  4868. i = 2; l = 0; u = 3;
  4869. break;
  4870. case X86::BI__builtin_ia32_vpermil2pd:
  4871. case X86::BI__builtin_ia32_vpermil2pd256:
  4872. case X86::BI__builtin_ia32_vpermil2ps:
  4873. case X86::BI__builtin_ia32_vpermil2ps256:
  4874. i = 3; l = 0; u = 3;
  4875. break;
  4876. case X86::BI__builtin_ia32_cmpb128_mask:
  4877. case X86::BI__builtin_ia32_cmpw128_mask:
  4878. case X86::BI__builtin_ia32_cmpd128_mask:
  4879. case X86::BI__builtin_ia32_cmpq128_mask:
  4880. case X86::BI__builtin_ia32_cmpb256_mask:
  4881. case X86::BI__builtin_ia32_cmpw256_mask:
  4882. case X86::BI__builtin_ia32_cmpd256_mask:
  4883. case X86::BI__builtin_ia32_cmpq256_mask:
  4884. case X86::BI__builtin_ia32_cmpb512_mask:
  4885. case X86::BI__builtin_ia32_cmpw512_mask:
  4886. case X86::BI__builtin_ia32_cmpd512_mask:
  4887. case X86::BI__builtin_ia32_cmpq512_mask:
  4888. case X86::BI__builtin_ia32_ucmpb128_mask:
  4889. case X86::BI__builtin_ia32_ucmpw128_mask:
  4890. case X86::BI__builtin_ia32_ucmpd128_mask:
  4891. case X86::BI__builtin_ia32_ucmpq128_mask:
  4892. case X86::BI__builtin_ia32_ucmpb256_mask:
  4893. case X86::BI__builtin_ia32_ucmpw256_mask:
  4894. case X86::BI__builtin_ia32_ucmpd256_mask:
  4895. case X86::BI__builtin_ia32_ucmpq256_mask:
  4896. case X86::BI__builtin_ia32_ucmpb512_mask:
  4897. case X86::BI__builtin_ia32_ucmpw512_mask:
  4898. case X86::BI__builtin_ia32_ucmpd512_mask:
  4899. case X86::BI__builtin_ia32_ucmpq512_mask:
  4900. case X86::BI__builtin_ia32_vpcomub:
  4901. case X86::BI__builtin_ia32_vpcomuw:
  4902. case X86::BI__builtin_ia32_vpcomud:
  4903. case X86::BI__builtin_ia32_vpcomuq:
  4904. case X86::BI__builtin_ia32_vpcomb:
  4905. case X86::BI__builtin_ia32_vpcomw:
  4906. case X86::BI__builtin_ia32_vpcomd:
  4907. case X86::BI__builtin_ia32_vpcomq:
  4908. case X86::BI__builtin_ia32_vec_set_v8hi:
  4909. case X86::BI__builtin_ia32_vec_set_v8si:
  4910. i = 2; l = 0; u = 7;
  4911. break;
  4912. case X86::BI__builtin_ia32_vpermilpd256:
  4913. case X86::BI__builtin_ia32_roundps:
  4914. case X86::BI__builtin_ia32_roundpd:
  4915. case X86::BI__builtin_ia32_roundps256:
  4916. case X86::BI__builtin_ia32_roundpd256:
  4917. case X86::BI__builtin_ia32_getmantpd128_mask:
  4918. case X86::BI__builtin_ia32_getmantpd256_mask:
  4919. case X86::BI__builtin_ia32_getmantps128_mask:
  4920. case X86::BI__builtin_ia32_getmantps256_mask:
  4921. case X86::BI__builtin_ia32_getmantpd512_mask:
  4922. case X86::BI__builtin_ia32_getmantps512_mask:
  4923. case X86::BI__builtin_ia32_getmantph128_mask:
  4924. case X86::BI__builtin_ia32_getmantph256_mask:
  4925. case X86::BI__builtin_ia32_getmantph512_mask:
  4926. case X86::BI__builtin_ia32_vec_ext_v16qi:
  4927. case X86::BI__builtin_ia32_vec_ext_v16hi:
  4928. i = 1; l = 0; u = 15;
  4929. break;
  4930. case X86::BI__builtin_ia32_pblendd128:
  4931. case X86::BI__builtin_ia32_blendps:
  4932. case X86::BI__builtin_ia32_blendpd256:
  4933. case X86::BI__builtin_ia32_shufpd256:
  4934. case X86::BI__builtin_ia32_roundss:
  4935. case X86::BI__builtin_ia32_roundsd:
  4936. case X86::BI__builtin_ia32_rangepd128_mask:
  4937. case X86::BI__builtin_ia32_rangepd256_mask:
  4938. case X86::BI__builtin_ia32_rangepd512_mask:
  4939. case X86::BI__builtin_ia32_rangeps128_mask:
  4940. case X86::BI__builtin_ia32_rangeps256_mask:
  4941. case X86::BI__builtin_ia32_rangeps512_mask:
  4942. case X86::BI__builtin_ia32_getmantsd_round_mask:
  4943. case X86::BI__builtin_ia32_getmantss_round_mask:
  4944. case X86::BI__builtin_ia32_getmantsh_round_mask:
  4945. case X86::BI__builtin_ia32_vec_set_v16qi:
  4946. case X86::BI__builtin_ia32_vec_set_v16hi:
  4947. i = 2; l = 0; u = 15;
  4948. break;
  4949. case X86::BI__builtin_ia32_vec_ext_v32qi:
  4950. i = 1; l = 0; u = 31;
  4951. break;
  4952. case X86::BI__builtin_ia32_cmpps:
  4953. case X86::BI__builtin_ia32_cmpss:
  4954. case X86::BI__builtin_ia32_cmppd:
  4955. case X86::BI__builtin_ia32_cmpsd:
  4956. case X86::BI__builtin_ia32_cmpps256:
  4957. case X86::BI__builtin_ia32_cmppd256:
  4958. case X86::BI__builtin_ia32_cmpps128_mask:
  4959. case X86::BI__builtin_ia32_cmppd128_mask:
  4960. case X86::BI__builtin_ia32_cmpps256_mask:
  4961. case X86::BI__builtin_ia32_cmppd256_mask:
  4962. case X86::BI__builtin_ia32_cmpps512_mask:
  4963. case X86::BI__builtin_ia32_cmppd512_mask:
  4964. case X86::BI__builtin_ia32_cmpsd_mask:
  4965. case X86::BI__builtin_ia32_cmpss_mask:
  4966. case X86::BI__builtin_ia32_vec_set_v32qi:
  4967. i = 2; l = 0; u = 31;
  4968. break;
  4969. case X86::BI__builtin_ia32_permdf256:
  4970. case X86::BI__builtin_ia32_permdi256:
  4971. case X86::BI__builtin_ia32_permdf512:
  4972. case X86::BI__builtin_ia32_permdi512:
  4973. case X86::BI__builtin_ia32_vpermilps:
  4974. case X86::BI__builtin_ia32_vpermilps256:
  4975. case X86::BI__builtin_ia32_vpermilpd512:
  4976. case X86::BI__builtin_ia32_vpermilps512:
  4977. case X86::BI__builtin_ia32_pshufd:
  4978. case X86::BI__builtin_ia32_pshufd256:
  4979. case X86::BI__builtin_ia32_pshufd512:
  4980. case X86::BI__builtin_ia32_pshufhw:
  4981. case X86::BI__builtin_ia32_pshufhw256:
  4982. case X86::BI__builtin_ia32_pshufhw512:
  4983. case X86::BI__builtin_ia32_pshuflw:
  4984. case X86::BI__builtin_ia32_pshuflw256:
  4985. case X86::BI__builtin_ia32_pshuflw512:
  4986. case X86::BI__builtin_ia32_vcvtps2ph:
  4987. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  4988. case X86::BI__builtin_ia32_vcvtps2ph256:
  4989. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  4990. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  4991. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  4992. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  4993. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  4994. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  4995. case X86::BI__builtin_ia32_rndscaleps_mask:
  4996. case X86::BI__builtin_ia32_rndscalepd_mask:
  4997. case X86::BI__builtin_ia32_rndscaleph_mask:
  4998. case X86::BI__builtin_ia32_reducepd128_mask:
  4999. case X86::BI__builtin_ia32_reducepd256_mask:
  5000. case X86::BI__builtin_ia32_reducepd512_mask:
  5001. case X86::BI__builtin_ia32_reduceps128_mask:
  5002. case X86::BI__builtin_ia32_reduceps256_mask:
  5003. case X86::BI__builtin_ia32_reduceps512_mask:
  5004. case X86::BI__builtin_ia32_reduceph128_mask:
  5005. case X86::BI__builtin_ia32_reduceph256_mask:
  5006. case X86::BI__builtin_ia32_reduceph512_mask:
  5007. case X86::BI__builtin_ia32_prold512:
  5008. case X86::BI__builtin_ia32_prolq512:
  5009. case X86::BI__builtin_ia32_prold128:
  5010. case X86::BI__builtin_ia32_prold256:
  5011. case X86::BI__builtin_ia32_prolq128:
  5012. case X86::BI__builtin_ia32_prolq256:
  5013. case X86::BI__builtin_ia32_prord512:
  5014. case X86::BI__builtin_ia32_prorq512:
  5015. case X86::BI__builtin_ia32_prord128:
  5016. case X86::BI__builtin_ia32_prord256:
  5017. case X86::BI__builtin_ia32_prorq128:
  5018. case X86::BI__builtin_ia32_prorq256:
  5019. case X86::BI__builtin_ia32_fpclasspd128_mask:
  5020. case X86::BI__builtin_ia32_fpclasspd256_mask:
  5021. case X86::BI__builtin_ia32_fpclassps128_mask:
  5022. case X86::BI__builtin_ia32_fpclassps256_mask:
  5023. case X86::BI__builtin_ia32_fpclassps512_mask:
  5024. case X86::BI__builtin_ia32_fpclasspd512_mask:
  5025. case X86::BI__builtin_ia32_fpclassph128_mask:
  5026. case X86::BI__builtin_ia32_fpclassph256_mask:
  5027. case X86::BI__builtin_ia32_fpclassph512_mask:
  5028. case X86::BI__builtin_ia32_fpclasssd_mask:
  5029. case X86::BI__builtin_ia32_fpclassss_mask:
  5030. case X86::BI__builtin_ia32_fpclasssh_mask:
  5031. case X86::BI__builtin_ia32_pslldqi128_byteshift:
  5032. case X86::BI__builtin_ia32_pslldqi256_byteshift:
  5033. case X86::BI__builtin_ia32_pslldqi512_byteshift:
  5034. case X86::BI__builtin_ia32_psrldqi128_byteshift:
  5035. case X86::BI__builtin_ia32_psrldqi256_byteshift:
  5036. case X86::BI__builtin_ia32_psrldqi512_byteshift:
  5037. case X86::BI__builtin_ia32_kshiftliqi:
  5038. case X86::BI__builtin_ia32_kshiftlihi:
  5039. case X86::BI__builtin_ia32_kshiftlisi:
  5040. case X86::BI__builtin_ia32_kshiftlidi:
  5041. case X86::BI__builtin_ia32_kshiftriqi:
  5042. case X86::BI__builtin_ia32_kshiftrihi:
  5043. case X86::BI__builtin_ia32_kshiftrisi:
  5044. case X86::BI__builtin_ia32_kshiftridi:
  5045. i = 1; l = 0; u = 255;
  5046. break;
  5047. case X86::BI__builtin_ia32_vperm2f128_pd256:
  5048. case X86::BI__builtin_ia32_vperm2f128_ps256:
  5049. case X86::BI__builtin_ia32_vperm2f128_si256:
  5050. case X86::BI__builtin_ia32_permti256:
  5051. case X86::BI__builtin_ia32_pblendw128:
  5052. case X86::BI__builtin_ia32_pblendw256:
  5053. case X86::BI__builtin_ia32_blendps256:
  5054. case X86::BI__builtin_ia32_pblendd256:
  5055. case X86::BI__builtin_ia32_palignr128:
  5056. case X86::BI__builtin_ia32_palignr256:
  5057. case X86::BI__builtin_ia32_palignr512:
  5058. case X86::BI__builtin_ia32_alignq512:
  5059. case X86::BI__builtin_ia32_alignd512:
  5060. case X86::BI__builtin_ia32_alignd128:
  5061. case X86::BI__builtin_ia32_alignd256:
  5062. case X86::BI__builtin_ia32_alignq128:
  5063. case X86::BI__builtin_ia32_alignq256:
  5064. case X86::BI__builtin_ia32_vcomisd:
  5065. case X86::BI__builtin_ia32_vcomiss:
  5066. case X86::BI__builtin_ia32_shuf_f32x4:
  5067. case X86::BI__builtin_ia32_shuf_f64x2:
  5068. case X86::BI__builtin_ia32_shuf_i32x4:
  5069. case X86::BI__builtin_ia32_shuf_i64x2:
  5070. case X86::BI__builtin_ia32_shufpd512:
  5071. case X86::BI__builtin_ia32_shufps:
  5072. case X86::BI__builtin_ia32_shufps256:
  5073. case X86::BI__builtin_ia32_shufps512:
  5074. case X86::BI__builtin_ia32_dbpsadbw128:
  5075. case X86::BI__builtin_ia32_dbpsadbw256:
  5076. case X86::BI__builtin_ia32_dbpsadbw512:
  5077. case X86::BI__builtin_ia32_vpshldd128:
  5078. case X86::BI__builtin_ia32_vpshldd256:
  5079. case X86::BI__builtin_ia32_vpshldd512:
  5080. case X86::BI__builtin_ia32_vpshldq128:
  5081. case X86::BI__builtin_ia32_vpshldq256:
  5082. case X86::BI__builtin_ia32_vpshldq512:
  5083. case X86::BI__builtin_ia32_vpshldw128:
  5084. case X86::BI__builtin_ia32_vpshldw256:
  5085. case X86::BI__builtin_ia32_vpshldw512:
  5086. case X86::BI__builtin_ia32_vpshrdd128:
  5087. case X86::BI__builtin_ia32_vpshrdd256:
  5088. case X86::BI__builtin_ia32_vpshrdd512:
  5089. case X86::BI__builtin_ia32_vpshrdq128:
  5090. case X86::BI__builtin_ia32_vpshrdq256:
  5091. case X86::BI__builtin_ia32_vpshrdq512:
  5092. case X86::BI__builtin_ia32_vpshrdw128:
  5093. case X86::BI__builtin_ia32_vpshrdw256:
  5094. case X86::BI__builtin_ia32_vpshrdw512:
  5095. i = 2; l = 0; u = 255;
  5096. break;
  5097. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  5098. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  5099. case X86::BI__builtin_ia32_fixupimmps512_mask:
  5100. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  5101. case X86::BI__builtin_ia32_fixupimmsd_mask:
  5102. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  5103. case X86::BI__builtin_ia32_fixupimmss_mask:
  5104. case X86::BI__builtin_ia32_fixupimmss_maskz:
  5105. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  5106. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  5107. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  5108. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  5109. case X86::BI__builtin_ia32_fixupimmps128_mask:
  5110. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  5111. case X86::BI__builtin_ia32_fixupimmps256_mask:
  5112. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  5113. case X86::BI__builtin_ia32_pternlogd512_mask:
  5114. case X86::BI__builtin_ia32_pternlogd512_maskz:
  5115. case X86::BI__builtin_ia32_pternlogq512_mask:
  5116. case X86::BI__builtin_ia32_pternlogq512_maskz:
  5117. case X86::BI__builtin_ia32_pternlogd128_mask:
  5118. case X86::BI__builtin_ia32_pternlogd128_maskz:
  5119. case X86::BI__builtin_ia32_pternlogd256_mask:
  5120. case X86::BI__builtin_ia32_pternlogd256_maskz:
  5121. case X86::BI__builtin_ia32_pternlogq128_mask:
  5122. case X86::BI__builtin_ia32_pternlogq128_maskz:
  5123. case X86::BI__builtin_ia32_pternlogq256_mask:
  5124. case X86::BI__builtin_ia32_pternlogq256_maskz:
  5125. i = 3; l = 0; u = 255;
  5126. break;
  5127. case X86::BI__builtin_ia32_gatherpfdpd:
  5128. case X86::BI__builtin_ia32_gatherpfdps:
  5129. case X86::BI__builtin_ia32_gatherpfqpd:
  5130. case X86::BI__builtin_ia32_gatherpfqps:
  5131. case X86::BI__builtin_ia32_scatterpfdpd:
  5132. case X86::BI__builtin_ia32_scatterpfdps:
  5133. case X86::BI__builtin_ia32_scatterpfqpd:
  5134. case X86::BI__builtin_ia32_scatterpfqps:
  5135. i = 4; l = 2; u = 3;
  5136. break;
  5137. case X86::BI__builtin_ia32_reducesd_mask:
  5138. case X86::BI__builtin_ia32_reducess_mask:
  5139. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  5140. case X86::BI__builtin_ia32_rndscaless_round_mask:
  5141. case X86::BI__builtin_ia32_rndscalesh_round_mask:
  5142. case X86::BI__builtin_ia32_reducesh_mask:
  5143. i = 4; l = 0; u = 255;
  5144. break;
  5145. case X86::BI__builtin_ia32_cmpccxadd32:
  5146. case X86::BI__builtin_ia32_cmpccxadd64:
  5147. i = 3; l = 0; u = 15;
  5148. break;
  5149. }
  5150. // Note that we don't force a hard error on the range check here, allowing
  5151. // template-generated or macro-generated dead code to potentially have out-of-
  5152. // range values. These need to code generate, but don't need to necessarily
  5153. // make any sense. We use a warning that defaults to an error.
  5154. return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
  5155. }
  5156. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  5157. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  5158. /// Returns true when the format fits the function and the FormatStringInfo has
  5159. /// been populated.
  5160. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  5161. bool IsVariadic, FormatStringInfo *FSI) {
  5162. if (Format->getFirstArg() == 0)
  5163. FSI->ArgPassingKind = FAPK_VAList;
  5164. else if (IsVariadic)
  5165. FSI->ArgPassingKind = FAPK_Variadic;
  5166. else
  5167. FSI->ArgPassingKind = FAPK_Fixed;
  5168. FSI->FormatIdx = Format->getFormatIdx() - 1;
  5169. FSI->FirstDataArg =
  5170. FSI->ArgPassingKind == FAPK_VAList ? 0 : Format->getFirstArg() - 1;
  5171. // The way the format attribute works in GCC, the implicit this argument
  5172. // of member functions is counted. However, it doesn't appear in our own
  5173. // lists, so decrement format_idx in that case.
  5174. if (IsCXXMember) {
  5175. if(FSI->FormatIdx == 0)
  5176. return false;
  5177. --FSI->FormatIdx;
  5178. if (FSI->FirstDataArg != 0)
  5179. --FSI->FirstDataArg;
  5180. }
  5181. return true;
  5182. }
  5183. /// Checks if a the given expression evaluates to null.
  5184. ///
  5185. /// Returns true if the value evaluates to null.
  5186. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  5187. // If the expression has non-null type, it doesn't evaluate to null.
  5188. if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
  5189. if (*nullability == NullabilityKind::NonNull)
  5190. return false;
  5191. }
  5192. // As a special case, transparent unions initialized with zero are
  5193. // considered null for the purposes of the nonnull attribute.
  5194. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  5195. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  5196. if (const CompoundLiteralExpr *CLE =
  5197. dyn_cast<CompoundLiteralExpr>(Expr))
  5198. if (const InitListExpr *ILE =
  5199. dyn_cast<InitListExpr>(CLE->getInitializer()))
  5200. Expr = ILE->getInit(0);
  5201. }
  5202. bool Result;
  5203. return (!Expr->isValueDependent() &&
  5204. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  5205. !Result);
  5206. }
  5207. static void CheckNonNullArgument(Sema &S,
  5208. const Expr *ArgExpr,
  5209. SourceLocation CallSiteLoc) {
  5210. if (CheckNonNullExpr(S, ArgExpr))
  5211. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  5212. S.PDiag(diag::warn_null_arg)
  5213. << ArgExpr->getSourceRange());
  5214. }
  5215. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  5216. FormatStringInfo FSI;
  5217. if ((GetFormatStringType(Format) == FST_NSString) &&
  5218. getFormatStringInfo(Format, false, true, &FSI)) {
  5219. Idx = FSI.FormatIdx;
  5220. return true;
  5221. }
  5222. return false;
  5223. }
  5224. /// Diagnose use of %s directive in an NSString which is being passed
  5225. /// as formatting string to formatting method.
  5226. static void
  5227. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  5228. const NamedDecl *FDecl,
  5229. Expr **Args,
  5230. unsigned NumArgs) {
  5231. unsigned Idx = 0;
  5232. bool Format = false;
  5233. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  5234. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  5235. Idx = 2;
  5236. Format = true;
  5237. }
  5238. else
  5239. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  5240. if (S.GetFormatNSStringIdx(I, Idx)) {
  5241. Format = true;
  5242. break;
  5243. }
  5244. }
  5245. if (!Format || NumArgs <= Idx)
  5246. return;
  5247. const Expr *FormatExpr = Args[Idx];
  5248. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  5249. FormatExpr = CSCE->getSubExpr();
  5250. const StringLiteral *FormatString;
  5251. if (const ObjCStringLiteral *OSL =
  5252. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  5253. FormatString = OSL->getString();
  5254. else
  5255. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  5256. if (!FormatString)
  5257. return;
  5258. if (S.FormatStringHasSArg(FormatString)) {
  5259. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  5260. << "%s" << 1 << 1;
  5261. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  5262. << FDecl->getDeclName();
  5263. }
  5264. }
  5265. /// Determine whether the given type has a non-null nullability annotation.
  5266. static bool isNonNullType(QualType type) {
  5267. if (auto nullability = type->getNullability())
  5268. return *nullability == NullabilityKind::NonNull;
  5269. return false;
  5270. }
  5271. static void CheckNonNullArguments(Sema &S,
  5272. const NamedDecl *FDecl,
  5273. const FunctionProtoType *Proto,
  5274. ArrayRef<const Expr *> Args,
  5275. SourceLocation CallSiteLoc) {
  5276. assert((FDecl || Proto) && "Need a function declaration or prototype");
  5277. // Already checked by constant evaluator.
  5278. if (S.isConstantEvaluated())
  5279. return;
  5280. // Check the attributes attached to the method/function itself.
  5281. llvm::SmallBitVector NonNullArgs;
  5282. if (FDecl) {
  5283. // Handle the nonnull attribute on the function/method declaration itself.
  5284. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  5285. if (!NonNull->args_size()) {
  5286. // Easy case: all pointer arguments are nonnull.
  5287. for (const auto *Arg : Args)
  5288. if (S.isValidPointerAttrType(Arg->getType()))
  5289. CheckNonNullArgument(S, Arg, CallSiteLoc);
  5290. return;
  5291. }
  5292. for (const ParamIdx &Idx : NonNull->args()) {
  5293. unsigned IdxAST = Idx.getASTIndex();
  5294. if (IdxAST >= Args.size())
  5295. continue;
  5296. if (NonNullArgs.empty())
  5297. NonNullArgs.resize(Args.size());
  5298. NonNullArgs.set(IdxAST);
  5299. }
  5300. }
  5301. }
  5302. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  5303. // Handle the nonnull attribute on the parameters of the
  5304. // function/method.
  5305. ArrayRef<ParmVarDecl*> parms;
  5306. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  5307. parms = FD->parameters();
  5308. else
  5309. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  5310. unsigned ParamIndex = 0;
  5311. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  5312. I != E; ++I, ++ParamIndex) {
  5313. const ParmVarDecl *PVD = *I;
  5314. if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
  5315. if (NonNullArgs.empty())
  5316. NonNullArgs.resize(Args.size());
  5317. NonNullArgs.set(ParamIndex);
  5318. }
  5319. }
  5320. } else {
  5321. // If we have a non-function, non-method declaration but no
  5322. // function prototype, try to dig out the function prototype.
  5323. if (!Proto) {
  5324. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  5325. QualType type = VD->getType().getNonReferenceType();
  5326. if (auto pointerType = type->getAs<PointerType>())
  5327. type = pointerType->getPointeeType();
  5328. else if (auto blockType = type->getAs<BlockPointerType>())
  5329. type = blockType->getPointeeType();
  5330. // FIXME: data member pointers?
  5331. // Dig out the function prototype, if there is one.
  5332. Proto = type->getAs<FunctionProtoType>();
  5333. }
  5334. }
  5335. // Fill in non-null argument information from the nullability
  5336. // information on the parameter types (if we have them).
  5337. if (Proto) {
  5338. unsigned Index = 0;
  5339. for (auto paramType : Proto->getParamTypes()) {
  5340. if (isNonNullType(paramType)) {
  5341. if (NonNullArgs.empty())
  5342. NonNullArgs.resize(Args.size());
  5343. NonNullArgs.set(Index);
  5344. }
  5345. ++Index;
  5346. }
  5347. }
  5348. }
  5349. // Check for non-null arguments.
  5350. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  5351. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  5352. if (NonNullArgs[ArgIndex])
  5353. CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
  5354. }
  5355. }
  5356. // 16 byte ByVal alignment not due to a vector member is not honoured by XL
  5357. // on AIX. Emit a warning here that users are generating binary incompatible
  5358. // code to be safe.
  5359. // Here we try to get information about the alignment of the struct member
  5360. // from the struct passed to the caller function. We only warn when the struct
  5361. // is passed byval, hence the series of checks and early returns if we are a not
  5362. // passing a struct byval.
  5363. void Sema::checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg) {
  5364. const auto *ICE = dyn_cast<ImplicitCastExpr>(Arg->IgnoreParens());
  5365. if (!ICE)
  5366. return;
  5367. const auto *DR = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
  5368. if (!DR)
  5369. return;
  5370. const auto *PD = dyn_cast<ParmVarDecl>(DR->getDecl());
  5371. if (!PD || !PD->getType()->isRecordType())
  5372. return;
  5373. QualType ArgType = Arg->getType();
  5374. for (const FieldDecl *FD :
  5375. ArgType->castAs<RecordType>()->getDecl()->fields()) {
  5376. if (const auto *AA = FD->getAttr<AlignedAttr>()) {
  5377. CharUnits Alignment =
  5378. Context.toCharUnitsFromBits(AA->getAlignment(Context));
  5379. if (Alignment.getQuantity() == 16) {
  5380. Diag(FD->getLocation(), diag::warn_not_xl_compatible) << FD;
  5381. Diag(Loc, diag::note_misaligned_member_used_here) << PD;
  5382. }
  5383. }
  5384. }
  5385. }
  5386. /// Warn if a pointer or reference argument passed to a function points to an
  5387. /// object that is less aligned than the parameter. This can happen when
  5388. /// creating a typedef with a lower alignment than the original type and then
  5389. /// calling functions defined in terms of the original type.
  5390. void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
  5391. StringRef ParamName, QualType ArgTy,
  5392. QualType ParamTy) {
  5393. // If a function accepts a pointer or reference type
  5394. if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
  5395. return;
  5396. // If the parameter is a pointer type, get the pointee type for the
  5397. // argument too. If the parameter is a reference type, don't try to get
  5398. // the pointee type for the argument.
  5399. if (ParamTy->isPointerType())
  5400. ArgTy = ArgTy->getPointeeType();
  5401. // Remove reference or pointer
  5402. ParamTy = ParamTy->getPointeeType();
  5403. // Find expected alignment, and the actual alignment of the passed object.
  5404. // getTypeAlignInChars requires complete types
  5405. if (ArgTy.isNull() || ParamTy->isDependentType() ||
  5406. ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
  5407. ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
  5408. return;
  5409. CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
  5410. CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
  5411. // If the argument is less aligned than the parameter, there is a
  5412. // potential alignment issue.
  5413. if (ArgAlign < ParamAlign)
  5414. Diag(Loc, diag::warn_param_mismatched_alignment)
  5415. << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
  5416. << ParamName << (FDecl != nullptr) << FDecl;
  5417. }
  5418. /// Handles the checks for format strings, non-POD arguments to vararg
  5419. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  5420. /// attributes.
  5421. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  5422. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  5423. bool IsMemberFunction, SourceLocation Loc,
  5424. SourceRange Range, VariadicCallType CallType) {
  5425. // FIXME: We should check as much as we can in the template definition.
  5426. if (CurContext->isDependentContext())
  5427. return;
  5428. // Printf and scanf checking.
  5429. llvm::SmallBitVector CheckedVarArgs;
  5430. if (FDecl) {
  5431. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  5432. // Only create vector if there are format attributes.
  5433. CheckedVarArgs.resize(Args.size());
  5434. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  5435. CheckedVarArgs);
  5436. }
  5437. }
  5438. // Refuse POD arguments that weren't caught by the format string
  5439. // checks above.
  5440. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  5441. if (CallType != VariadicDoesNotApply &&
  5442. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  5443. unsigned NumParams = Proto ? Proto->getNumParams()
  5444. : FDecl && isa<FunctionDecl>(FDecl)
  5445. ? cast<FunctionDecl>(FDecl)->getNumParams()
  5446. : FDecl && isa<ObjCMethodDecl>(FDecl)
  5447. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  5448. : 0;
  5449. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  5450. // Args[ArgIdx] can be null in malformed code.
  5451. if (const Expr *Arg = Args[ArgIdx]) {
  5452. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  5453. checkVariadicArgument(Arg, CallType);
  5454. }
  5455. }
  5456. }
  5457. if (FDecl || Proto) {
  5458. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  5459. // Type safety checking.
  5460. if (FDecl) {
  5461. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  5462. CheckArgumentWithTypeTag(I, Args, Loc);
  5463. }
  5464. }
  5465. // Check that passed arguments match the alignment of original arguments.
  5466. // Try to get the missing prototype from the declaration.
  5467. if (!Proto && FDecl) {
  5468. const auto *FT = FDecl->getFunctionType();
  5469. if (isa_and_nonnull<FunctionProtoType>(FT))
  5470. Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
  5471. }
  5472. if (Proto) {
  5473. // For variadic functions, we may have more args than parameters.
  5474. // For some K&R functions, we may have less args than parameters.
  5475. const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
  5476. for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
  5477. // Args[ArgIdx] can be null in malformed code.
  5478. if (const Expr *Arg = Args[ArgIdx]) {
  5479. if (Arg->containsErrors())
  5480. continue;
  5481. if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
  5482. FDecl->hasLinkage() &&
  5483. FDecl->getFormalLinkage() != InternalLinkage &&
  5484. CallType == VariadicDoesNotApply)
  5485. checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
  5486. QualType ParamTy = Proto->getParamType(ArgIdx);
  5487. QualType ArgTy = Arg->getType();
  5488. CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
  5489. ArgTy, ParamTy);
  5490. }
  5491. }
  5492. }
  5493. if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
  5494. auto *AA = FDecl->getAttr<AllocAlignAttr>();
  5495. const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
  5496. if (!Arg->isValueDependent()) {
  5497. Expr::EvalResult Align;
  5498. if (Arg->EvaluateAsInt(Align, Context)) {
  5499. const llvm::APSInt &I = Align.Val.getInt();
  5500. if (!I.isPowerOf2())
  5501. Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
  5502. << Arg->getSourceRange();
  5503. if (I > Sema::MaximumAlignment)
  5504. Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
  5505. << Arg->getSourceRange() << Sema::MaximumAlignment;
  5506. }
  5507. }
  5508. }
  5509. if (FD)
  5510. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  5511. }
  5512. /// CheckConstructorCall - Check a constructor call for correctness and safety
  5513. /// properties not enforced by the C type system.
  5514. void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
  5515. ArrayRef<const Expr *> Args,
  5516. const FunctionProtoType *Proto,
  5517. SourceLocation Loc) {
  5518. VariadicCallType CallType =
  5519. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  5520. auto *Ctor = cast<CXXConstructorDecl>(FDecl);
  5521. CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
  5522. Context.getPointerType(Ctor->getThisObjectType()));
  5523. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  5524. Loc, SourceRange(), CallType);
  5525. }
  5526. /// CheckFunctionCall - Check a direct function call for various correctness
  5527. /// and safety properties not strictly enforced by the C type system.
  5528. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  5529. const FunctionProtoType *Proto) {
  5530. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  5531. isa<CXXMethodDecl>(FDecl);
  5532. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  5533. IsMemberOperatorCall;
  5534. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  5535. TheCall->getCallee());
  5536. Expr** Args = TheCall->getArgs();
  5537. unsigned NumArgs = TheCall->getNumArgs();
  5538. Expr *ImplicitThis = nullptr;
  5539. if (IsMemberOperatorCall && !FDecl->isStatic()) {
  5540. // If this is a call to a non-static member operator, hide the first
  5541. // argument from checkCall.
  5542. // FIXME: Our choice of AST representation here is less than ideal.
  5543. ImplicitThis = Args[0];
  5544. ++Args;
  5545. --NumArgs;
  5546. } else if (IsMemberFunction && !FDecl->isStatic())
  5547. ImplicitThis =
  5548. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  5549. if (ImplicitThis) {
  5550. // ImplicitThis may or may not be a pointer, depending on whether . or -> is
  5551. // used.
  5552. QualType ThisType = ImplicitThis->getType();
  5553. if (!ThisType->isPointerType()) {
  5554. assert(!ThisType->isReferenceType());
  5555. ThisType = Context.getPointerType(ThisType);
  5556. }
  5557. QualType ThisTypeFromDecl =
  5558. Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
  5559. CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
  5560. ThisTypeFromDecl);
  5561. }
  5562. checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
  5563. IsMemberFunction, TheCall->getRParenLoc(),
  5564. TheCall->getCallee()->getSourceRange(), CallType);
  5565. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  5566. // None of the checks below are needed for functions that don't have
  5567. // simple names (e.g., C++ conversion functions).
  5568. if (!FnInfo)
  5569. return false;
  5570. // Enforce TCB except for builtin calls, which are always allowed.
  5571. if (FDecl->getBuiltinID() == 0)
  5572. CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
  5573. CheckAbsoluteValueFunction(TheCall, FDecl);
  5574. CheckMaxUnsignedZero(TheCall, FDecl);
  5575. if (getLangOpts().ObjC)
  5576. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  5577. unsigned CMId = FDecl->getMemoryFunctionKind();
  5578. // Handle memory setting and copying functions.
  5579. switch (CMId) {
  5580. case 0:
  5581. return false;
  5582. case Builtin::BIstrlcpy: // fallthrough
  5583. case Builtin::BIstrlcat:
  5584. CheckStrlcpycatArguments(TheCall, FnInfo);
  5585. break;
  5586. case Builtin::BIstrncat:
  5587. CheckStrncatArguments(TheCall, FnInfo);
  5588. break;
  5589. case Builtin::BIfree:
  5590. CheckFreeArguments(TheCall);
  5591. break;
  5592. default:
  5593. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  5594. }
  5595. return false;
  5596. }
  5597. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  5598. ArrayRef<const Expr *> Args) {
  5599. VariadicCallType CallType =
  5600. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  5601. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  5602. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  5603. CallType);
  5604. CheckTCBEnforcement(lbrac, Method);
  5605. return false;
  5606. }
  5607. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  5608. const FunctionProtoType *Proto) {
  5609. QualType Ty;
  5610. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  5611. Ty = V->getType().getNonReferenceType();
  5612. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  5613. Ty = F->getType().getNonReferenceType();
  5614. else
  5615. return false;
  5616. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  5617. !Ty->isFunctionProtoType())
  5618. return false;
  5619. VariadicCallType CallType;
  5620. if (!Proto || !Proto->isVariadic()) {
  5621. CallType = VariadicDoesNotApply;
  5622. } else if (Ty->isBlockPointerType()) {
  5623. CallType = VariadicBlock;
  5624. } else { // Ty->isFunctionPointerType()
  5625. CallType = VariadicFunction;
  5626. }
  5627. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  5628. llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  5629. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  5630. TheCall->getCallee()->getSourceRange(), CallType);
  5631. return false;
  5632. }
  5633. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  5634. /// such as function pointers returned from functions.
  5635. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  5636. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  5637. TheCall->getCallee());
  5638. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  5639. llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  5640. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  5641. TheCall->getCallee()->getSourceRange(), CallType);
  5642. return false;
  5643. }
  5644. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  5645. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  5646. return false;
  5647. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  5648. switch (Op) {
  5649. case AtomicExpr::AO__c11_atomic_init:
  5650. case AtomicExpr::AO__opencl_atomic_init:
  5651. llvm_unreachable("There is no ordering argument for an init");
  5652. case AtomicExpr::AO__c11_atomic_load:
  5653. case AtomicExpr::AO__opencl_atomic_load:
  5654. case AtomicExpr::AO__hip_atomic_load:
  5655. case AtomicExpr::AO__atomic_load_n:
  5656. case AtomicExpr::AO__atomic_load:
  5657. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  5658. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  5659. case AtomicExpr::AO__c11_atomic_store:
  5660. case AtomicExpr::AO__opencl_atomic_store:
  5661. case AtomicExpr::AO__hip_atomic_store:
  5662. case AtomicExpr::AO__atomic_store:
  5663. case AtomicExpr::AO__atomic_store_n:
  5664. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  5665. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  5666. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  5667. default:
  5668. return true;
  5669. }
  5670. }
  5671. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  5672. AtomicExpr::AtomicOp Op) {
  5673. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  5674. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5675. MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
  5676. return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
  5677. DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
  5678. Op);
  5679. }
  5680. ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
  5681. SourceLocation RParenLoc, MultiExprArg Args,
  5682. AtomicExpr::AtomicOp Op,
  5683. AtomicArgumentOrder ArgOrder) {
  5684. // All the non-OpenCL operations take one of the following forms.
  5685. // The OpenCL operations take the __c11 forms with one extra argument for
  5686. // synchronization scope.
  5687. enum {
  5688. // C __c11_atomic_init(A *, C)
  5689. Init,
  5690. // C __c11_atomic_load(A *, int)
  5691. Load,
  5692. // void __atomic_load(A *, CP, int)
  5693. LoadCopy,
  5694. // void __atomic_store(A *, CP, int)
  5695. Copy,
  5696. // C __c11_atomic_add(A *, M, int)
  5697. Arithmetic,
  5698. // C __atomic_exchange_n(A *, CP, int)
  5699. Xchg,
  5700. // void __atomic_exchange(A *, C *, CP, int)
  5701. GNUXchg,
  5702. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  5703. C11CmpXchg,
  5704. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  5705. GNUCmpXchg
  5706. } Form = Init;
  5707. const unsigned NumForm = GNUCmpXchg + 1;
  5708. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  5709. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  5710. // where:
  5711. // C is an appropriate type,
  5712. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  5713. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  5714. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  5715. // the int parameters are for orderings.
  5716. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  5717. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  5718. "need to update code for modified forms");
  5719. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  5720. AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
  5721. AtomicExpr::AO__atomic_load,
  5722. "need to update code for modified C11 atomics");
  5723. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  5724. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  5725. bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
  5726. Op <= AtomicExpr::AO__hip_atomic_fetch_max;
  5727. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  5728. Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
  5729. IsOpenCL;
  5730. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  5731. Op == AtomicExpr::AO__atomic_store_n ||
  5732. Op == AtomicExpr::AO__atomic_exchange_n ||
  5733. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  5734. bool IsAddSub = false;
  5735. switch (Op) {
  5736. case AtomicExpr::AO__c11_atomic_init:
  5737. case AtomicExpr::AO__opencl_atomic_init:
  5738. Form = Init;
  5739. break;
  5740. case AtomicExpr::AO__c11_atomic_load:
  5741. case AtomicExpr::AO__opencl_atomic_load:
  5742. case AtomicExpr::AO__hip_atomic_load:
  5743. case AtomicExpr::AO__atomic_load_n:
  5744. Form = Load;
  5745. break;
  5746. case AtomicExpr::AO__atomic_load:
  5747. Form = LoadCopy;
  5748. break;
  5749. case AtomicExpr::AO__c11_atomic_store:
  5750. case AtomicExpr::AO__opencl_atomic_store:
  5751. case AtomicExpr::AO__hip_atomic_store:
  5752. case AtomicExpr::AO__atomic_store:
  5753. case AtomicExpr::AO__atomic_store_n:
  5754. Form = Copy;
  5755. break;
  5756. case AtomicExpr::AO__hip_atomic_fetch_add:
  5757. case AtomicExpr::AO__hip_atomic_fetch_min:
  5758. case AtomicExpr::AO__hip_atomic_fetch_max:
  5759. case AtomicExpr::AO__c11_atomic_fetch_add:
  5760. case AtomicExpr::AO__c11_atomic_fetch_sub:
  5761. case AtomicExpr::AO__opencl_atomic_fetch_add:
  5762. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  5763. case AtomicExpr::AO__atomic_fetch_add:
  5764. case AtomicExpr::AO__atomic_fetch_sub:
  5765. case AtomicExpr::AO__atomic_add_fetch:
  5766. case AtomicExpr::AO__atomic_sub_fetch:
  5767. IsAddSub = true;
  5768. Form = Arithmetic;
  5769. break;
  5770. case AtomicExpr::AO__c11_atomic_fetch_and:
  5771. case AtomicExpr::AO__c11_atomic_fetch_or:
  5772. case AtomicExpr::AO__c11_atomic_fetch_xor:
  5773. case AtomicExpr::AO__hip_atomic_fetch_and:
  5774. case AtomicExpr::AO__hip_atomic_fetch_or:
  5775. case AtomicExpr::AO__hip_atomic_fetch_xor:
  5776. case AtomicExpr::AO__c11_atomic_fetch_nand:
  5777. case AtomicExpr::AO__opencl_atomic_fetch_and:
  5778. case AtomicExpr::AO__opencl_atomic_fetch_or:
  5779. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  5780. case AtomicExpr::AO__atomic_fetch_and:
  5781. case AtomicExpr::AO__atomic_fetch_or:
  5782. case AtomicExpr::AO__atomic_fetch_xor:
  5783. case AtomicExpr::AO__atomic_fetch_nand:
  5784. case AtomicExpr::AO__atomic_and_fetch:
  5785. case AtomicExpr::AO__atomic_or_fetch:
  5786. case AtomicExpr::AO__atomic_xor_fetch:
  5787. case AtomicExpr::AO__atomic_nand_fetch:
  5788. Form = Arithmetic;
  5789. break;
  5790. case AtomicExpr::AO__c11_atomic_fetch_min:
  5791. case AtomicExpr::AO__c11_atomic_fetch_max:
  5792. case AtomicExpr::AO__opencl_atomic_fetch_min:
  5793. case AtomicExpr::AO__opencl_atomic_fetch_max:
  5794. case AtomicExpr::AO__atomic_min_fetch:
  5795. case AtomicExpr::AO__atomic_max_fetch:
  5796. case AtomicExpr::AO__atomic_fetch_min:
  5797. case AtomicExpr::AO__atomic_fetch_max:
  5798. Form = Arithmetic;
  5799. break;
  5800. case AtomicExpr::AO__c11_atomic_exchange:
  5801. case AtomicExpr::AO__hip_atomic_exchange:
  5802. case AtomicExpr::AO__opencl_atomic_exchange:
  5803. case AtomicExpr::AO__atomic_exchange_n:
  5804. Form = Xchg;
  5805. break;
  5806. case AtomicExpr::AO__atomic_exchange:
  5807. Form = GNUXchg;
  5808. break;
  5809. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  5810. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  5811. case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
  5812. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  5813. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  5814. case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
  5815. Form = C11CmpXchg;
  5816. break;
  5817. case AtomicExpr::AO__atomic_compare_exchange:
  5818. case AtomicExpr::AO__atomic_compare_exchange_n:
  5819. Form = GNUCmpXchg;
  5820. break;
  5821. }
  5822. unsigned AdjustedNumArgs = NumArgs[Form];
  5823. if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
  5824. ++AdjustedNumArgs;
  5825. // Check we have the right number of arguments.
  5826. if (Args.size() < AdjustedNumArgs) {
  5827. Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
  5828. << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
  5829. << ExprRange;
  5830. return ExprError();
  5831. } else if (Args.size() > AdjustedNumArgs) {
  5832. Diag(Args[AdjustedNumArgs]->getBeginLoc(),
  5833. diag::err_typecheck_call_too_many_args)
  5834. << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
  5835. << ExprRange;
  5836. return ExprError();
  5837. }
  5838. // Inspect the first argument of the atomic operation.
  5839. Expr *Ptr = Args[0];
  5840. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  5841. if (ConvertedPtr.isInvalid())
  5842. return ExprError();
  5843. Ptr = ConvertedPtr.get();
  5844. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  5845. if (!pointerType) {
  5846. Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
  5847. << Ptr->getType() << Ptr->getSourceRange();
  5848. return ExprError();
  5849. }
  5850. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  5851. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  5852. QualType ValType = AtomTy; // 'C'
  5853. if (IsC11) {
  5854. if (!AtomTy->isAtomicType()) {
  5855. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
  5856. << Ptr->getType() << Ptr->getSourceRange();
  5857. return ExprError();
  5858. }
  5859. if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
  5860. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  5861. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
  5862. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  5863. << Ptr->getSourceRange();
  5864. return ExprError();
  5865. }
  5866. ValType = AtomTy->castAs<AtomicType>()->getValueType();
  5867. } else if (Form != Load && Form != LoadCopy) {
  5868. if (ValType.isConstQualified()) {
  5869. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
  5870. << Ptr->getType() << Ptr->getSourceRange();
  5871. return ExprError();
  5872. }
  5873. }
  5874. // For an arithmetic operation, the implied arithmetic must be well-formed.
  5875. if (Form == Arithmetic) {
  5876. // GCC does not enforce these rules for GNU atomics, but we do to help catch
  5877. // trivial type errors.
  5878. auto IsAllowedValueType = [&](QualType ValType) {
  5879. if (ValType->isIntegerType())
  5880. return true;
  5881. if (ValType->isPointerType())
  5882. return true;
  5883. if (!ValType->isFloatingType())
  5884. return false;
  5885. // LLVM Parser does not allow atomicrmw with x86_fp80 type.
  5886. if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
  5887. &Context.getTargetInfo().getLongDoubleFormat() ==
  5888. &llvm::APFloat::x87DoubleExtended())
  5889. return false;
  5890. return true;
  5891. };
  5892. if (IsAddSub && !IsAllowedValueType(ValType)) {
  5893. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
  5894. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  5895. return ExprError();
  5896. }
  5897. if (!IsAddSub && !ValType->isIntegerType()) {
  5898. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
  5899. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  5900. return ExprError();
  5901. }
  5902. if (IsC11 && ValType->isPointerType() &&
  5903. RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
  5904. diag::err_incomplete_type)) {
  5905. return ExprError();
  5906. }
  5907. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  5908. // For __atomic_*_n operations, the value type must be a scalar integral or
  5909. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  5910. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  5911. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  5912. return ExprError();
  5913. }
  5914. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  5915. !AtomTy->isScalarType()) {
  5916. // For GNU atomics, require a trivially-copyable type. This is not part of
  5917. // the GNU atomics specification but we enforce it for consistency with
  5918. // other atomics which generally all require a trivially-copyable type. This
  5919. // is because atomics just copy bits.
  5920. Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
  5921. << Ptr->getType() << Ptr->getSourceRange();
  5922. return ExprError();
  5923. }
  5924. switch (ValType.getObjCLifetime()) {
  5925. case Qualifiers::OCL_None:
  5926. case Qualifiers::OCL_ExplicitNone:
  5927. // okay
  5928. break;
  5929. case Qualifiers::OCL_Weak:
  5930. case Qualifiers::OCL_Strong:
  5931. case Qualifiers::OCL_Autoreleasing:
  5932. // FIXME: Can this happen? By this point, ValType should be known
  5933. // to be trivially copyable.
  5934. Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
  5935. << ValType << Ptr->getSourceRange();
  5936. return ExprError();
  5937. }
  5938. // All atomic operations have an overload which takes a pointer to a volatile
  5939. // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
  5940. // into the result or the other operands. Similarly atomic_load takes a
  5941. // pointer to a const 'A'.
  5942. ValType.removeLocalVolatile();
  5943. ValType.removeLocalConst();
  5944. QualType ResultType = ValType;
  5945. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  5946. Form == Init)
  5947. ResultType = Context.VoidTy;
  5948. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  5949. ResultType = Context.BoolTy;
  5950. // The type of a parameter passed 'by value'. In the GNU atomics, such
  5951. // arguments are actually passed as pointers.
  5952. QualType ByValType = ValType; // 'CP'
  5953. bool IsPassedByAddress = false;
  5954. if (!IsC11 && !IsHIP && !IsN) {
  5955. ByValType = Ptr->getType();
  5956. IsPassedByAddress = true;
  5957. }
  5958. SmallVector<Expr *, 5> APIOrderedArgs;
  5959. if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
  5960. APIOrderedArgs.push_back(Args[0]);
  5961. switch (Form) {
  5962. case Init:
  5963. case Load:
  5964. APIOrderedArgs.push_back(Args[1]); // Val1/Order
  5965. break;
  5966. case LoadCopy:
  5967. case Copy:
  5968. case Arithmetic:
  5969. case Xchg:
  5970. APIOrderedArgs.push_back(Args[2]); // Val1
  5971. APIOrderedArgs.push_back(Args[1]); // Order
  5972. break;
  5973. case GNUXchg:
  5974. APIOrderedArgs.push_back(Args[2]); // Val1
  5975. APIOrderedArgs.push_back(Args[3]); // Val2
  5976. APIOrderedArgs.push_back(Args[1]); // Order
  5977. break;
  5978. case C11CmpXchg:
  5979. APIOrderedArgs.push_back(Args[2]); // Val1
  5980. APIOrderedArgs.push_back(Args[4]); // Val2
  5981. APIOrderedArgs.push_back(Args[1]); // Order
  5982. APIOrderedArgs.push_back(Args[3]); // OrderFail
  5983. break;
  5984. case GNUCmpXchg:
  5985. APIOrderedArgs.push_back(Args[2]); // Val1
  5986. APIOrderedArgs.push_back(Args[4]); // Val2
  5987. APIOrderedArgs.push_back(Args[5]); // Weak
  5988. APIOrderedArgs.push_back(Args[1]); // Order
  5989. APIOrderedArgs.push_back(Args[3]); // OrderFail
  5990. break;
  5991. }
  5992. } else
  5993. APIOrderedArgs.append(Args.begin(), Args.end());
  5994. // The first argument's non-CV pointer type is used to deduce the type of
  5995. // subsequent arguments, except for:
  5996. // - weak flag (always converted to bool)
  5997. // - memory order (always converted to int)
  5998. // - scope (always converted to int)
  5999. for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
  6000. QualType Ty;
  6001. if (i < NumVals[Form] + 1) {
  6002. switch (i) {
  6003. case 0:
  6004. // The first argument is always a pointer. It has a fixed type.
  6005. // It is always dereferenced, a nullptr is undefined.
  6006. CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
  6007. // Nothing else to do: we already know all we want about this pointer.
  6008. continue;
  6009. case 1:
  6010. // The second argument is the non-atomic operand. For arithmetic, this
  6011. // is always passed by value, and for a compare_exchange it is always
  6012. // passed by address. For the rest, GNU uses by-address and C11 uses
  6013. // by-value.
  6014. assert(Form != Load);
  6015. if (Form == Arithmetic && ValType->isPointerType())
  6016. Ty = Context.getPointerDiffType();
  6017. else if (Form == Init || Form == Arithmetic)
  6018. Ty = ValType;
  6019. else if (Form == Copy || Form == Xchg) {
  6020. if (IsPassedByAddress) {
  6021. // The value pointer is always dereferenced, a nullptr is undefined.
  6022. CheckNonNullArgument(*this, APIOrderedArgs[i],
  6023. ExprRange.getBegin());
  6024. }
  6025. Ty = ByValType;
  6026. } else {
  6027. Expr *ValArg = APIOrderedArgs[i];
  6028. // The value pointer is always dereferenced, a nullptr is undefined.
  6029. CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
  6030. LangAS AS = LangAS::Default;
  6031. // Keep address space of non-atomic pointer type.
  6032. if (const PointerType *PtrTy =
  6033. ValArg->getType()->getAs<PointerType>()) {
  6034. AS = PtrTy->getPointeeType().getAddressSpace();
  6035. }
  6036. Ty = Context.getPointerType(
  6037. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  6038. }
  6039. break;
  6040. case 2:
  6041. // The third argument to compare_exchange / GNU exchange is the desired
  6042. // value, either by-value (for the C11 and *_n variant) or as a pointer.
  6043. if (IsPassedByAddress)
  6044. CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
  6045. Ty = ByValType;
  6046. break;
  6047. case 3:
  6048. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  6049. Ty = Context.BoolTy;
  6050. break;
  6051. }
  6052. } else {
  6053. // The order(s) and scope are always converted to int.
  6054. Ty = Context.IntTy;
  6055. }
  6056. InitializedEntity Entity =
  6057. InitializedEntity::InitializeParameter(Context, Ty, false);
  6058. ExprResult Arg = APIOrderedArgs[i];
  6059. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  6060. if (Arg.isInvalid())
  6061. return true;
  6062. APIOrderedArgs[i] = Arg.get();
  6063. }
  6064. // Permute the arguments into a 'consistent' order.
  6065. SmallVector<Expr*, 5> SubExprs;
  6066. SubExprs.push_back(Ptr);
  6067. switch (Form) {
  6068. case Init:
  6069. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  6070. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  6071. break;
  6072. case Load:
  6073. SubExprs.push_back(APIOrderedArgs[1]); // Order
  6074. break;
  6075. case LoadCopy:
  6076. case Copy:
  6077. case Arithmetic:
  6078. case Xchg:
  6079. SubExprs.push_back(APIOrderedArgs[2]); // Order
  6080. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  6081. break;
  6082. case GNUXchg:
  6083. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  6084. SubExprs.push_back(APIOrderedArgs[3]); // Order
  6085. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  6086. SubExprs.push_back(APIOrderedArgs[2]); // Val2
  6087. break;
  6088. case C11CmpXchg:
  6089. SubExprs.push_back(APIOrderedArgs[3]); // Order
  6090. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  6091. SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
  6092. SubExprs.push_back(APIOrderedArgs[2]); // Val2
  6093. break;
  6094. case GNUCmpXchg:
  6095. SubExprs.push_back(APIOrderedArgs[4]); // Order
  6096. SubExprs.push_back(APIOrderedArgs[1]); // Val1
  6097. SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
  6098. SubExprs.push_back(APIOrderedArgs[2]); // Val2
  6099. SubExprs.push_back(APIOrderedArgs[3]); // Weak
  6100. break;
  6101. }
  6102. if (SubExprs.size() >= 2 && Form != Init) {
  6103. if (std::optional<llvm::APSInt> Result =
  6104. SubExprs[1]->getIntegerConstantExpr(Context))
  6105. if (!isValidOrderingForOp(Result->getSExtValue(), Op))
  6106. Diag(SubExprs[1]->getBeginLoc(),
  6107. diag::warn_atomic_op_has_invalid_memory_order)
  6108. << SubExprs[1]->getSourceRange();
  6109. }
  6110. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  6111. auto *Scope = Args[Args.size() - 1];
  6112. if (std::optional<llvm::APSInt> Result =
  6113. Scope->getIntegerConstantExpr(Context)) {
  6114. if (!ScopeModel->isValid(Result->getZExtValue()))
  6115. Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
  6116. << Scope->getSourceRange();
  6117. }
  6118. SubExprs.push_back(Scope);
  6119. }
  6120. AtomicExpr *AE = new (Context)
  6121. AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
  6122. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  6123. Op == AtomicExpr::AO__c11_atomic_store ||
  6124. Op == AtomicExpr::AO__opencl_atomic_load ||
  6125. Op == AtomicExpr::AO__hip_atomic_load ||
  6126. Op == AtomicExpr::AO__opencl_atomic_store ||
  6127. Op == AtomicExpr::AO__hip_atomic_store) &&
  6128. Context.AtomicUsesUnsupportedLibcall(AE))
  6129. Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
  6130. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  6131. Op == AtomicExpr::AO__opencl_atomic_load ||
  6132. Op == AtomicExpr::AO__hip_atomic_load)
  6133. ? 0
  6134. : 1);
  6135. if (ValType->isBitIntType()) {
  6136. Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
  6137. return ExprError();
  6138. }
  6139. return AE;
  6140. }
  6141. /// checkBuiltinArgument - Given a call to a builtin function, perform
  6142. /// normal type-checking on the given argument, updating the call in
  6143. /// place. This is useful when a builtin function requires custom
  6144. /// type-checking for some of its arguments but not necessarily all of
  6145. /// them.
  6146. ///
  6147. /// Returns true on error.
  6148. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  6149. FunctionDecl *Fn = E->getDirectCallee();
  6150. assert(Fn && "builtin call without direct callee!");
  6151. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  6152. InitializedEntity Entity =
  6153. InitializedEntity::InitializeParameter(S.Context, Param);
  6154. ExprResult Arg = E->getArg(ArgIndex);
  6155. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  6156. if (Arg.isInvalid())
  6157. return true;
  6158. E->setArg(ArgIndex, Arg.get());
  6159. return false;
  6160. }
  6161. /// We have a call to a function like __sync_fetch_and_add, which is an
  6162. /// overloaded function based on the pointer type of its first argument.
  6163. /// The main BuildCallExpr routines have already promoted the types of
  6164. /// arguments because all of these calls are prototyped as void(...).
  6165. ///
  6166. /// This function goes through and does final semantic checking for these
  6167. /// builtins, as well as generating any warnings.
  6168. ExprResult
  6169. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  6170. CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
  6171. Expr *Callee = TheCall->getCallee();
  6172. DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
  6173. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  6174. // Ensure that we have at least one argument to do type inference from.
  6175. if (TheCall->getNumArgs() < 1) {
  6176. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  6177. << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
  6178. return ExprError();
  6179. }
  6180. // Inspect the first argument of the atomic builtin. This should always be
  6181. // a pointer type, whose element is an integral scalar or pointer type.
  6182. // Because it is a pointer type, we don't have to worry about any implicit
  6183. // casts here.
  6184. // FIXME: We don't allow floating point scalars as input.
  6185. Expr *FirstArg = TheCall->getArg(0);
  6186. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  6187. if (FirstArgResult.isInvalid())
  6188. return ExprError();
  6189. FirstArg = FirstArgResult.get();
  6190. TheCall->setArg(0, FirstArg);
  6191. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  6192. if (!pointerType) {
  6193. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  6194. << FirstArg->getType() << FirstArg->getSourceRange();
  6195. return ExprError();
  6196. }
  6197. QualType ValType = pointerType->getPointeeType();
  6198. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  6199. !ValType->isBlockPointerType()) {
  6200. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
  6201. << FirstArg->getType() << FirstArg->getSourceRange();
  6202. return ExprError();
  6203. }
  6204. if (ValType.isConstQualified()) {
  6205. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
  6206. << FirstArg->getType() << FirstArg->getSourceRange();
  6207. return ExprError();
  6208. }
  6209. switch (ValType.getObjCLifetime()) {
  6210. case Qualifiers::OCL_None:
  6211. case Qualifiers::OCL_ExplicitNone:
  6212. // okay
  6213. break;
  6214. case Qualifiers::OCL_Weak:
  6215. case Qualifiers::OCL_Strong:
  6216. case Qualifiers::OCL_Autoreleasing:
  6217. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  6218. << ValType << FirstArg->getSourceRange();
  6219. return ExprError();
  6220. }
  6221. // Strip any qualifiers off ValType.
  6222. ValType = ValType.getUnqualifiedType();
  6223. // The majority of builtins return a value, but a few have special return
  6224. // types, so allow them to override appropriately below.
  6225. QualType ResultType = ValType;
  6226. // We need to figure out which concrete builtin this maps onto. For example,
  6227. // __sync_fetch_and_add with a 2 byte object turns into
  6228. // __sync_fetch_and_add_2.
  6229. #define BUILTIN_ROW(x) \
  6230. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  6231. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  6232. static const unsigned BuiltinIndices[][5] = {
  6233. BUILTIN_ROW(__sync_fetch_and_add),
  6234. BUILTIN_ROW(__sync_fetch_and_sub),
  6235. BUILTIN_ROW(__sync_fetch_and_or),
  6236. BUILTIN_ROW(__sync_fetch_and_and),
  6237. BUILTIN_ROW(__sync_fetch_and_xor),
  6238. BUILTIN_ROW(__sync_fetch_and_nand),
  6239. BUILTIN_ROW(__sync_add_and_fetch),
  6240. BUILTIN_ROW(__sync_sub_and_fetch),
  6241. BUILTIN_ROW(__sync_and_and_fetch),
  6242. BUILTIN_ROW(__sync_or_and_fetch),
  6243. BUILTIN_ROW(__sync_xor_and_fetch),
  6244. BUILTIN_ROW(__sync_nand_and_fetch),
  6245. BUILTIN_ROW(__sync_val_compare_and_swap),
  6246. BUILTIN_ROW(__sync_bool_compare_and_swap),
  6247. BUILTIN_ROW(__sync_lock_test_and_set),
  6248. BUILTIN_ROW(__sync_lock_release),
  6249. BUILTIN_ROW(__sync_swap)
  6250. };
  6251. #undef BUILTIN_ROW
  6252. // Determine the index of the size.
  6253. unsigned SizeIndex;
  6254. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  6255. case 1: SizeIndex = 0; break;
  6256. case 2: SizeIndex = 1; break;
  6257. case 4: SizeIndex = 2; break;
  6258. case 8: SizeIndex = 3; break;
  6259. case 16: SizeIndex = 4; break;
  6260. default:
  6261. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
  6262. << FirstArg->getType() << FirstArg->getSourceRange();
  6263. return ExprError();
  6264. }
  6265. // Each of these builtins has one pointer argument, followed by some number of
  6266. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  6267. // that we ignore. Find out which row of BuiltinIndices to read from as well
  6268. // as the number of fixed args.
  6269. unsigned BuiltinID = FDecl->getBuiltinID();
  6270. unsigned BuiltinIndex, NumFixed = 1;
  6271. bool WarnAboutSemanticsChange = false;
  6272. switch (BuiltinID) {
  6273. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  6274. case Builtin::BI__sync_fetch_and_add:
  6275. case Builtin::BI__sync_fetch_and_add_1:
  6276. case Builtin::BI__sync_fetch_and_add_2:
  6277. case Builtin::BI__sync_fetch_and_add_4:
  6278. case Builtin::BI__sync_fetch_and_add_8:
  6279. case Builtin::BI__sync_fetch_and_add_16:
  6280. BuiltinIndex = 0;
  6281. break;
  6282. case Builtin::BI__sync_fetch_and_sub:
  6283. case Builtin::BI__sync_fetch_and_sub_1:
  6284. case Builtin::BI__sync_fetch_and_sub_2:
  6285. case Builtin::BI__sync_fetch_and_sub_4:
  6286. case Builtin::BI__sync_fetch_and_sub_8:
  6287. case Builtin::BI__sync_fetch_and_sub_16:
  6288. BuiltinIndex = 1;
  6289. break;
  6290. case Builtin::BI__sync_fetch_and_or:
  6291. case Builtin::BI__sync_fetch_and_or_1:
  6292. case Builtin::BI__sync_fetch_and_or_2:
  6293. case Builtin::BI__sync_fetch_and_or_4:
  6294. case Builtin::BI__sync_fetch_and_or_8:
  6295. case Builtin::BI__sync_fetch_and_or_16:
  6296. BuiltinIndex = 2;
  6297. break;
  6298. case Builtin::BI__sync_fetch_and_and:
  6299. case Builtin::BI__sync_fetch_and_and_1:
  6300. case Builtin::BI__sync_fetch_and_and_2:
  6301. case Builtin::BI__sync_fetch_and_and_4:
  6302. case Builtin::BI__sync_fetch_and_and_8:
  6303. case Builtin::BI__sync_fetch_and_and_16:
  6304. BuiltinIndex = 3;
  6305. break;
  6306. case Builtin::BI__sync_fetch_and_xor:
  6307. case Builtin::BI__sync_fetch_and_xor_1:
  6308. case Builtin::BI__sync_fetch_and_xor_2:
  6309. case Builtin::BI__sync_fetch_and_xor_4:
  6310. case Builtin::BI__sync_fetch_and_xor_8:
  6311. case Builtin::BI__sync_fetch_and_xor_16:
  6312. BuiltinIndex = 4;
  6313. break;
  6314. case Builtin::BI__sync_fetch_and_nand:
  6315. case Builtin::BI__sync_fetch_and_nand_1:
  6316. case Builtin::BI__sync_fetch_and_nand_2:
  6317. case Builtin::BI__sync_fetch_and_nand_4:
  6318. case Builtin::BI__sync_fetch_and_nand_8:
  6319. case Builtin::BI__sync_fetch_and_nand_16:
  6320. BuiltinIndex = 5;
  6321. WarnAboutSemanticsChange = true;
  6322. break;
  6323. case Builtin::BI__sync_add_and_fetch:
  6324. case Builtin::BI__sync_add_and_fetch_1:
  6325. case Builtin::BI__sync_add_and_fetch_2:
  6326. case Builtin::BI__sync_add_and_fetch_4:
  6327. case Builtin::BI__sync_add_and_fetch_8:
  6328. case Builtin::BI__sync_add_and_fetch_16:
  6329. BuiltinIndex = 6;
  6330. break;
  6331. case Builtin::BI__sync_sub_and_fetch:
  6332. case Builtin::BI__sync_sub_and_fetch_1:
  6333. case Builtin::BI__sync_sub_and_fetch_2:
  6334. case Builtin::BI__sync_sub_and_fetch_4:
  6335. case Builtin::BI__sync_sub_and_fetch_8:
  6336. case Builtin::BI__sync_sub_and_fetch_16:
  6337. BuiltinIndex = 7;
  6338. break;
  6339. case Builtin::BI__sync_and_and_fetch:
  6340. case Builtin::BI__sync_and_and_fetch_1:
  6341. case Builtin::BI__sync_and_and_fetch_2:
  6342. case Builtin::BI__sync_and_and_fetch_4:
  6343. case Builtin::BI__sync_and_and_fetch_8:
  6344. case Builtin::BI__sync_and_and_fetch_16:
  6345. BuiltinIndex = 8;
  6346. break;
  6347. case Builtin::BI__sync_or_and_fetch:
  6348. case Builtin::BI__sync_or_and_fetch_1:
  6349. case Builtin::BI__sync_or_and_fetch_2:
  6350. case Builtin::BI__sync_or_and_fetch_4:
  6351. case Builtin::BI__sync_or_and_fetch_8:
  6352. case Builtin::BI__sync_or_and_fetch_16:
  6353. BuiltinIndex = 9;
  6354. break;
  6355. case Builtin::BI__sync_xor_and_fetch:
  6356. case Builtin::BI__sync_xor_and_fetch_1:
  6357. case Builtin::BI__sync_xor_and_fetch_2:
  6358. case Builtin::BI__sync_xor_and_fetch_4:
  6359. case Builtin::BI__sync_xor_and_fetch_8:
  6360. case Builtin::BI__sync_xor_and_fetch_16:
  6361. BuiltinIndex = 10;
  6362. break;
  6363. case Builtin::BI__sync_nand_and_fetch:
  6364. case Builtin::BI__sync_nand_and_fetch_1:
  6365. case Builtin::BI__sync_nand_and_fetch_2:
  6366. case Builtin::BI__sync_nand_and_fetch_4:
  6367. case Builtin::BI__sync_nand_and_fetch_8:
  6368. case Builtin::BI__sync_nand_and_fetch_16:
  6369. BuiltinIndex = 11;
  6370. WarnAboutSemanticsChange = true;
  6371. break;
  6372. case Builtin::BI__sync_val_compare_and_swap:
  6373. case Builtin::BI__sync_val_compare_and_swap_1:
  6374. case Builtin::BI__sync_val_compare_and_swap_2:
  6375. case Builtin::BI__sync_val_compare_and_swap_4:
  6376. case Builtin::BI__sync_val_compare_and_swap_8:
  6377. case Builtin::BI__sync_val_compare_and_swap_16:
  6378. BuiltinIndex = 12;
  6379. NumFixed = 2;
  6380. break;
  6381. case Builtin::BI__sync_bool_compare_and_swap:
  6382. case Builtin::BI__sync_bool_compare_and_swap_1:
  6383. case Builtin::BI__sync_bool_compare_and_swap_2:
  6384. case Builtin::BI__sync_bool_compare_and_swap_4:
  6385. case Builtin::BI__sync_bool_compare_and_swap_8:
  6386. case Builtin::BI__sync_bool_compare_and_swap_16:
  6387. BuiltinIndex = 13;
  6388. NumFixed = 2;
  6389. ResultType = Context.BoolTy;
  6390. break;
  6391. case Builtin::BI__sync_lock_test_and_set:
  6392. case Builtin::BI__sync_lock_test_and_set_1:
  6393. case Builtin::BI__sync_lock_test_and_set_2:
  6394. case Builtin::BI__sync_lock_test_and_set_4:
  6395. case Builtin::BI__sync_lock_test_and_set_8:
  6396. case Builtin::BI__sync_lock_test_and_set_16:
  6397. BuiltinIndex = 14;
  6398. break;
  6399. case Builtin::BI__sync_lock_release:
  6400. case Builtin::BI__sync_lock_release_1:
  6401. case Builtin::BI__sync_lock_release_2:
  6402. case Builtin::BI__sync_lock_release_4:
  6403. case Builtin::BI__sync_lock_release_8:
  6404. case Builtin::BI__sync_lock_release_16:
  6405. BuiltinIndex = 15;
  6406. NumFixed = 0;
  6407. ResultType = Context.VoidTy;
  6408. break;
  6409. case Builtin::BI__sync_swap:
  6410. case Builtin::BI__sync_swap_1:
  6411. case Builtin::BI__sync_swap_2:
  6412. case Builtin::BI__sync_swap_4:
  6413. case Builtin::BI__sync_swap_8:
  6414. case Builtin::BI__sync_swap_16:
  6415. BuiltinIndex = 16;
  6416. break;
  6417. }
  6418. // Now that we know how many fixed arguments we expect, first check that we
  6419. // have at least that many.
  6420. if (TheCall->getNumArgs() < 1+NumFixed) {
  6421. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  6422. << 0 << 1 + NumFixed << TheCall->getNumArgs()
  6423. << Callee->getSourceRange();
  6424. return ExprError();
  6425. }
  6426. Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
  6427. << Callee->getSourceRange();
  6428. if (WarnAboutSemanticsChange) {
  6429. Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
  6430. << Callee->getSourceRange();
  6431. }
  6432. // Get the decl for the concrete builtin from this, we can tell what the
  6433. // concrete integer type we should convert to is.
  6434. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  6435. StringRef NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  6436. FunctionDecl *NewBuiltinDecl;
  6437. if (NewBuiltinID == BuiltinID)
  6438. NewBuiltinDecl = FDecl;
  6439. else {
  6440. // Perform builtin lookup to avoid redeclaring it.
  6441. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  6442. LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
  6443. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  6444. assert(Res.getFoundDecl());
  6445. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  6446. if (!NewBuiltinDecl)
  6447. return ExprError();
  6448. }
  6449. // The first argument --- the pointer --- has a fixed type; we
  6450. // deduce the types of the rest of the arguments accordingly. Walk
  6451. // the remaining arguments, converting them to the deduced value type.
  6452. for (unsigned i = 0; i != NumFixed; ++i) {
  6453. ExprResult Arg = TheCall->getArg(i+1);
  6454. // GCC does an implicit conversion to the pointer or integer ValType. This
  6455. // can fail in some cases (1i -> int**), check for this error case now.
  6456. // Initialize the argument.
  6457. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  6458. ValType, /*consume*/ false);
  6459. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  6460. if (Arg.isInvalid())
  6461. return ExprError();
  6462. // Okay, we have something that *can* be converted to the right type. Check
  6463. // to see if there is a potentially weird extension going on here. This can
  6464. // happen when you do an atomic operation on something like an char* and
  6465. // pass in 42. The 42 gets converted to char. This is even more strange
  6466. // for things like 45.123 -> char, etc.
  6467. // FIXME: Do this check.
  6468. TheCall->setArg(i+1, Arg.get());
  6469. }
  6470. // Create a new DeclRefExpr to refer to the new decl.
  6471. DeclRefExpr *NewDRE = DeclRefExpr::Create(
  6472. Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
  6473. /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
  6474. DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
  6475. // Set the callee in the CallExpr.
  6476. // FIXME: This loses syntactic information.
  6477. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  6478. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  6479. CK_BuiltinFnToFnPtr);
  6480. TheCall->setCallee(PromotedCall.get());
  6481. // Change the result type of the call to match the original value type. This
  6482. // is arbitrary, but the codegen for these builtins ins design to handle it
  6483. // gracefully.
  6484. TheCall->setType(ResultType);
  6485. // Prohibit problematic uses of bit-precise integer types with atomic
  6486. // builtins. The arguments would have already been converted to the first
  6487. // argument's type, so only need to check the first argument.
  6488. const auto *BitIntValType = ValType->getAs<BitIntType>();
  6489. if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
  6490. Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
  6491. return ExprError();
  6492. }
  6493. return TheCallResult;
  6494. }
  6495. /// SemaBuiltinNontemporalOverloaded - We have a call to
  6496. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  6497. /// overloaded function based on the pointer type of its last argument.
  6498. ///
  6499. /// This function goes through and does final semantic checking for these
  6500. /// builtins.
  6501. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  6502. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  6503. DeclRefExpr *DRE =
  6504. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  6505. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  6506. unsigned BuiltinID = FDecl->getBuiltinID();
  6507. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  6508. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  6509. "Unexpected nontemporal load/store builtin!");
  6510. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  6511. unsigned numArgs = isStore ? 2 : 1;
  6512. // Ensure that we have the proper number of arguments.
  6513. if (checkArgCount(*this, TheCall, numArgs))
  6514. return ExprError();
  6515. // Inspect the last argument of the nontemporal builtin. This should always
  6516. // be a pointer type, from which we imply the type of the memory access.
  6517. // Because it is a pointer type, we don't have to worry about any implicit
  6518. // casts here.
  6519. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  6520. ExprResult PointerArgResult =
  6521. DefaultFunctionArrayLvalueConversion(PointerArg);
  6522. if (PointerArgResult.isInvalid())
  6523. return ExprError();
  6524. PointerArg = PointerArgResult.get();
  6525. TheCall->setArg(numArgs - 1, PointerArg);
  6526. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  6527. if (!pointerType) {
  6528. Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
  6529. << PointerArg->getType() << PointerArg->getSourceRange();
  6530. return ExprError();
  6531. }
  6532. QualType ValType = pointerType->getPointeeType();
  6533. // Strip any qualifiers off ValType.
  6534. ValType = ValType.getUnqualifiedType();
  6535. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  6536. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  6537. !ValType->isVectorType()) {
  6538. Diag(DRE->getBeginLoc(),
  6539. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  6540. << PointerArg->getType() << PointerArg->getSourceRange();
  6541. return ExprError();
  6542. }
  6543. if (!isStore) {
  6544. TheCall->setType(ValType);
  6545. return TheCallResult;
  6546. }
  6547. ExprResult ValArg = TheCall->getArg(0);
  6548. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  6549. Context, ValType, /*consume*/ false);
  6550. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  6551. if (ValArg.isInvalid())
  6552. return ExprError();
  6553. TheCall->setArg(0, ValArg.get());
  6554. TheCall->setType(Context.VoidTy);
  6555. return TheCallResult;
  6556. }
  6557. /// CheckObjCString - Checks that the argument to the builtin
  6558. /// CFString constructor is correct
  6559. /// Note: It might also make sense to do the UTF-16 conversion here (would
  6560. /// simplify the backend).
  6561. bool Sema::CheckObjCString(Expr *Arg) {
  6562. Arg = Arg->IgnoreParenCasts();
  6563. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  6564. if (!Literal || !Literal->isOrdinary()) {
  6565. Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
  6566. << Arg->getSourceRange();
  6567. return true;
  6568. }
  6569. if (Literal->containsNonAsciiOrNull()) {
  6570. StringRef String = Literal->getString();
  6571. unsigned NumBytes = String.size();
  6572. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  6573. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  6574. llvm::UTF16 *ToPtr = &ToBuf[0];
  6575. llvm::ConversionResult Result =
  6576. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  6577. ToPtr + NumBytes, llvm::strictConversion);
  6578. // Check for conversion failure.
  6579. if (Result != llvm::conversionOK)
  6580. Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
  6581. << Arg->getSourceRange();
  6582. }
  6583. return false;
  6584. }
  6585. /// CheckObjCString - Checks that the format string argument to the os_log()
  6586. /// and os_trace() functions is correct, and converts it to const char *.
  6587. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  6588. Arg = Arg->IgnoreParenCasts();
  6589. auto *Literal = dyn_cast<StringLiteral>(Arg);
  6590. if (!Literal) {
  6591. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  6592. Literal = ObjcLiteral->getString();
  6593. }
  6594. }
  6595. if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
  6596. return ExprError(
  6597. Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
  6598. << Arg->getSourceRange());
  6599. }
  6600. ExprResult Result(Literal);
  6601. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  6602. InitializedEntity Entity =
  6603. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  6604. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  6605. return Result;
  6606. }
  6607. /// Check that the user is calling the appropriate va_start builtin for the
  6608. /// target and calling convention.
  6609. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  6610. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  6611. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  6612. bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
  6613. TT.getArch() == llvm::Triple::aarch64_32);
  6614. bool IsWindows = TT.isOSWindows();
  6615. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  6616. if (IsX64 || IsAArch64) {
  6617. CallingConv CC = CC_C;
  6618. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  6619. CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  6620. if (IsMSVAStart) {
  6621. // Don't allow this in System V ABI functions.
  6622. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  6623. return S.Diag(Fn->getBeginLoc(),
  6624. diag::err_ms_va_start_used_in_sysv_function);
  6625. } else {
  6626. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  6627. // On x64 Windows, don't allow this in System V ABI functions.
  6628. // (Yes, that means there's no corresponding way to support variadic
  6629. // System V ABI functions on Windows.)
  6630. if ((IsWindows && CC == CC_X86_64SysV) ||
  6631. (!IsWindows && CC == CC_Win64))
  6632. return S.Diag(Fn->getBeginLoc(),
  6633. diag::err_va_start_used_in_wrong_abi_function)
  6634. << !IsWindows;
  6635. }
  6636. return false;
  6637. }
  6638. if (IsMSVAStart)
  6639. return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
  6640. return false;
  6641. }
  6642. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  6643. ParmVarDecl **LastParam = nullptr) {
  6644. // Determine whether the current function, block, or obj-c method is variadic
  6645. // and get its parameter list.
  6646. bool IsVariadic = false;
  6647. ArrayRef<ParmVarDecl *> Params;
  6648. DeclContext *Caller = S.CurContext;
  6649. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  6650. IsVariadic = Block->isVariadic();
  6651. Params = Block->parameters();
  6652. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  6653. IsVariadic = FD->isVariadic();
  6654. Params = FD->parameters();
  6655. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  6656. IsVariadic = MD->isVariadic();
  6657. // FIXME: This isn't correct for methods (results in bogus warning).
  6658. Params = MD->parameters();
  6659. } else if (isa<CapturedDecl>(Caller)) {
  6660. // We don't support va_start in a CapturedDecl.
  6661. S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
  6662. return true;
  6663. } else {
  6664. // This must be some other declcontext that parses exprs.
  6665. S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
  6666. return true;
  6667. }
  6668. if (!IsVariadic) {
  6669. S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
  6670. return true;
  6671. }
  6672. if (LastParam)
  6673. *LastParam = Params.empty() ? nullptr : Params.back();
  6674. return false;
  6675. }
  6676. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  6677. /// for validity. Emit an error and return true on failure; return false
  6678. /// on success.
  6679. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  6680. Expr *Fn = TheCall->getCallee();
  6681. if (checkVAStartABI(*this, BuiltinID, Fn))
  6682. return true;
  6683. // In C2x mode, va_start only needs one argument. However, the builtin still
  6684. // requires two arguments (which matches the behavior of the GCC builtin),
  6685. // <stdarg.h> passes `0` as the second argument in C2x mode.
  6686. if (checkArgCount(*this, TheCall, 2))
  6687. return true;
  6688. // Type-check the first argument normally.
  6689. if (checkBuiltinArgument(*this, TheCall, 0))
  6690. return true;
  6691. // Check that the current function is variadic, and get its last parameter.
  6692. ParmVarDecl *LastParam;
  6693. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  6694. return true;
  6695. // Verify that the second argument to the builtin is the last argument of the
  6696. // current function or method. In C2x mode, if the second argument is an
  6697. // integer constant expression with value 0, then we don't bother with this
  6698. // check.
  6699. bool SecondArgIsLastNamedArgument = false;
  6700. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  6701. if (std::optional<llvm::APSInt> Val =
  6702. TheCall->getArg(1)->getIntegerConstantExpr(Context);
  6703. Val && LangOpts.C2x && *Val == 0)
  6704. return false;
  6705. // These are valid if SecondArgIsLastNamedArgument is false after the next
  6706. // block.
  6707. QualType Type;
  6708. SourceLocation ParamLoc;
  6709. bool IsCRegister = false;
  6710. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  6711. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  6712. SecondArgIsLastNamedArgument = PV == LastParam;
  6713. Type = PV->getType();
  6714. ParamLoc = PV->getLocation();
  6715. IsCRegister =
  6716. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  6717. }
  6718. }
  6719. if (!SecondArgIsLastNamedArgument)
  6720. Diag(TheCall->getArg(1)->getBeginLoc(),
  6721. diag::warn_second_arg_of_va_start_not_last_named_param);
  6722. else if (IsCRegister || Type->isReferenceType() ||
  6723. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  6724. // Promotable integers are UB, but enumerations need a bit of
  6725. // extra checking to see what their promotable type actually is.
  6726. if (!Context.isPromotableIntegerType(Type))
  6727. return false;
  6728. if (!Type->isEnumeralType())
  6729. return true;
  6730. const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
  6731. return !(ED &&
  6732. Context.typesAreCompatible(ED->getPromotionType(), Type));
  6733. }()) {
  6734. unsigned Reason = 0;
  6735. if (Type->isReferenceType()) Reason = 1;
  6736. else if (IsCRegister) Reason = 2;
  6737. Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
  6738. Diag(ParamLoc, diag::note_parameter_type) << Type;
  6739. }
  6740. return false;
  6741. }
  6742. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  6743. auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
  6744. const LangOptions &LO = getLangOpts();
  6745. if (LO.CPlusPlus)
  6746. return Arg->getType()
  6747. .getCanonicalType()
  6748. .getTypePtr()
  6749. ->getPointeeType()
  6750. .withoutLocalFastQualifiers() == Context.CharTy;
  6751. // In C, allow aliasing through `char *`, this is required for AArch64 at
  6752. // least.
  6753. return true;
  6754. };
  6755. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  6756. // const char *named_addr);
  6757. Expr *Func = Call->getCallee();
  6758. if (Call->getNumArgs() < 3)
  6759. return Diag(Call->getEndLoc(),
  6760. diag::err_typecheck_call_too_few_args_at_least)
  6761. << 0 /*function call*/ << 3 << Call->getNumArgs();
  6762. // Type-check the first argument normally.
  6763. if (checkBuiltinArgument(*this, Call, 0))
  6764. return true;
  6765. // Check that the current function is variadic.
  6766. if (checkVAStartIsInVariadicFunction(*this, Func))
  6767. return true;
  6768. // __va_start on Windows does not validate the parameter qualifiers
  6769. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  6770. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  6771. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  6772. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  6773. const QualType &ConstCharPtrTy =
  6774. Context.getPointerType(Context.CharTy.withConst());
  6775. if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
  6776. Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  6777. << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
  6778. << 0 /* qualifier difference */
  6779. << 3 /* parameter mismatch */
  6780. << 2 << Arg1->getType() << ConstCharPtrTy;
  6781. const QualType SizeTy = Context.getSizeType();
  6782. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  6783. Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  6784. << Arg2->getType() << SizeTy << 1 /* different class */
  6785. << 0 /* qualifier difference */
  6786. << 3 /* parameter mismatch */
  6787. << 3 << Arg2->getType() << SizeTy;
  6788. return false;
  6789. }
  6790. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  6791. /// friends. This is declared to take (...), so we have to check everything.
  6792. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  6793. if (checkArgCount(*this, TheCall, 2))
  6794. return true;
  6795. ExprResult OrigArg0 = TheCall->getArg(0);
  6796. ExprResult OrigArg1 = TheCall->getArg(1);
  6797. // Do standard promotions between the two arguments, returning their common
  6798. // type.
  6799. QualType Res = UsualArithmeticConversions(
  6800. OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
  6801. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  6802. return true;
  6803. // Make sure any conversions are pushed back into the call; this is
  6804. // type safe since unordered compare builtins are declared as "_Bool
  6805. // foo(...)".
  6806. TheCall->setArg(0, OrigArg0.get());
  6807. TheCall->setArg(1, OrigArg1.get());
  6808. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  6809. return false;
  6810. // If the common type isn't a real floating type, then the arguments were
  6811. // invalid for this operation.
  6812. if (Res.isNull() || !Res->isRealFloatingType())
  6813. return Diag(OrigArg0.get()->getBeginLoc(),
  6814. diag::err_typecheck_call_invalid_ordered_compare)
  6815. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  6816. << SourceRange(OrigArg0.get()->getBeginLoc(),
  6817. OrigArg1.get()->getEndLoc());
  6818. return false;
  6819. }
  6820. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  6821. /// __builtin_isnan and friends. This is declared to take (...), so we have
  6822. /// to check everything. We expect the last argument to be a floating point
  6823. /// value.
  6824. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  6825. if (checkArgCount(*this, TheCall, NumArgs))
  6826. return true;
  6827. // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
  6828. // on all preceding parameters just being int. Try all of those.
  6829. for (unsigned i = 0; i < NumArgs - 1; ++i) {
  6830. Expr *Arg = TheCall->getArg(i);
  6831. if (Arg->isTypeDependent())
  6832. return false;
  6833. ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
  6834. if (Res.isInvalid())
  6835. return true;
  6836. TheCall->setArg(i, Res.get());
  6837. }
  6838. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  6839. if (OrigArg->isTypeDependent())
  6840. return false;
  6841. // Usual Unary Conversions will convert half to float, which we want for
  6842. // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
  6843. // type how it is, but do normal L->Rvalue conversions.
  6844. if (Context.getTargetInfo().useFP16ConversionIntrinsics())
  6845. OrigArg = UsualUnaryConversions(OrigArg).get();
  6846. else
  6847. OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
  6848. TheCall->setArg(NumArgs - 1, OrigArg);
  6849. // This operation requires a non-_Complex floating-point number.
  6850. if (!OrigArg->getType()->isRealFloatingType())
  6851. return Diag(OrigArg->getBeginLoc(),
  6852. diag::err_typecheck_call_invalid_unary_fp)
  6853. << OrigArg->getType() << OrigArg->getSourceRange();
  6854. return false;
  6855. }
  6856. /// Perform semantic analysis for a call to __builtin_complex.
  6857. bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
  6858. if (checkArgCount(*this, TheCall, 2))
  6859. return true;
  6860. bool Dependent = false;
  6861. for (unsigned I = 0; I != 2; ++I) {
  6862. Expr *Arg = TheCall->getArg(I);
  6863. QualType T = Arg->getType();
  6864. if (T->isDependentType()) {
  6865. Dependent = true;
  6866. continue;
  6867. }
  6868. // Despite supporting _Complex int, GCC requires a real floating point type
  6869. // for the operands of __builtin_complex.
  6870. if (!T->isRealFloatingType()) {
  6871. return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
  6872. << Arg->getType() << Arg->getSourceRange();
  6873. }
  6874. ExprResult Converted = DefaultLvalueConversion(Arg);
  6875. if (Converted.isInvalid())
  6876. return true;
  6877. TheCall->setArg(I, Converted.get());
  6878. }
  6879. if (Dependent) {
  6880. TheCall->setType(Context.DependentTy);
  6881. return false;
  6882. }
  6883. Expr *Real = TheCall->getArg(0);
  6884. Expr *Imag = TheCall->getArg(1);
  6885. if (!Context.hasSameType(Real->getType(), Imag->getType())) {
  6886. return Diag(Real->getBeginLoc(),
  6887. diag::err_typecheck_call_different_arg_types)
  6888. << Real->getType() << Imag->getType()
  6889. << Real->getSourceRange() << Imag->getSourceRange();
  6890. }
  6891. // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
  6892. // don't allow this builtin to form those types either.
  6893. // FIXME: Should we allow these types?
  6894. if (Real->getType()->isFloat16Type())
  6895. return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
  6896. << "_Float16";
  6897. if (Real->getType()->isHalfType())
  6898. return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
  6899. << "half";
  6900. TheCall->setType(Context.getComplexType(Real->getType()));
  6901. return false;
  6902. }
  6903. // Customized Sema Checking for VSX builtins that have the following signature:
  6904. // vector [...] builtinName(vector [...], vector [...], const int);
  6905. // Which takes the same type of vectors (any legal vector type) for the first
  6906. // two arguments and takes compile time constant for the third argument.
  6907. // Example builtins are :
  6908. // vector double vec_xxpermdi(vector double, vector double, int);
  6909. // vector short vec_xxsldwi(vector short, vector short, int);
  6910. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  6911. unsigned ExpectedNumArgs = 3;
  6912. if (checkArgCount(*this, TheCall, ExpectedNumArgs))
  6913. return true;
  6914. // Check the third argument is a compile time constant
  6915. if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
  6916. return Diag(TheCall->getBeginLoc(),
  6917. diag::err_vsx_builtin_nonconstant_argument)
  6918. << 3 /* argument index */ << TheCall->getDirectCallee()
  6919. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  6920. TheCall->getArg(2)->getEndLoc());
  6921. QualType Arg1Ty = TheCall->getArg(0)->getType();
  6922. QualType Arg2Ty = TheCall->getArg(1)->getType();
  6923. // Check the type of argument 1 and argument 2 are vectors.
  6924. SourceLocation BuiltinLoc = TheCall->getBeginLoc();
  6925. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  6926. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  6927. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  6928. << TheCall->getDirectCallee()
  6929. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  6930. TheCall->getArg(1)->getEndLoc());
  6931. }
  6932. // Check the first two arguments are the same type.
  6933. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  6934. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  6935. << TheCall->getDirectCallee()
  6936. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  6937. TheCall->getArg(1)->getEndLoc());
  6938. }
  6939. // When default clang type checking is turned off and the customized type
  6940. // checking is used, the returning type of the function must be explicitly
  6941. // set. Otherwise it is _Bool by default.
  6942. TheCall->setType(Arg1Ty);
  6943. return false;
  6944. }
  6945. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  6946. // This is declared to take (...), so we have to check everything.
  6947. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  6948. if (TheCall->getNumArgs() < 2)
  6949. return ExprError(Diag(TheCall->getEndLoc(),
  6950. diag::err_typecheck_call_too_few_args_at_least)
  6951. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  6952. << TheCall->getSourceRange());
  6953. // Determine which of the following types of shufflevector we're checking:
  6954. // 1) unary, vector mask: (lhs, mask)
  6955. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  6956. QualType resType = TheCall->getArg(0)->getType();
  6957. unsigned numElements = 0;
  6958. if (!TheCall->getArg(0)->isTypeDependent() &&
  6959. !TheCall->getArg(1)->isTypeDependent()) {
  6960. QualType LHSType = TheCall->getArg(0)->getType();
  6961. QualType RHSType = TheCall->getArg(1)->getType();
  6962. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  6963. return ExprError(
  6964. Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
  6965. << TheCall->getDirectCallee()
  6966. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  6967. TheCall->getArg(1)->getEndLoc()));
  6968. numElements = LHSType->castAs<VectorType>()->getNumElements();
  6969. unsigned numResElements = TheCall->getNumArgs() - 2;
  6970. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  6971. // with mask. If so, verify that RHS is an integer vector type with the
  6972. // same number of elts as lhs.
  6973. if (TheCall->getNumArgs() == 2) {
  6974. if (!RHSType->hasIntegerRepresentation() ||
  6975. RHSType->castAs<VectorType>()->getNumElements() != numElements)
  6976. return ExprError(Diag(TheCall->getBeginLoc(),
  6977. diag::err_vec_builtin_incompatible_vector)
  6978. << TheCall->getDirectCallee()
  6979. << SourceRange(TheCall->getArg(1)->getBeginLoc(),
  6980. TheCall->getArg(1)->getEndLoc()));
  6981. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  6982. return ExprError(Diag(TheCall->getBeginLoc(),
  6983. diag::err_vec_builtin_incompatible_vector)
  6984. << TheCall->getDirectCallee()
  6985. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  6986. TheCall->getArg(1)->getEndLoc()));
  6987. } else if (numElements != numResElements) {
  6988. QualType eltType = LHSType->castAs<VectorType>()->getElementType();
  6989. resType = Context.getVectorType(eltType, numResElements,
  6990. VectorType::GenericVector);
  6991. }
  6992. }
  6993. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  6994. if (TheCall->getArg(i)->isTypeDependent() ||
  6995. TheCall->getArg(i)->isValueDependent())
  6996. continue;
  6997. std::optional<llvm::APSInt> Result;
  6998. if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
  6999. return ExprError(Diag(TheCall->getBeginLoc(),
  7000. diag::err_shufflevector_nonconstant_argument)
  7001. << TheCall->getArg(i)->getSourceRange());
  7002. // Allow -1 which will be translated to undef in the IR.
  7003. if (Result->isSigned() && Result->isAllOnes())
  7004. continue;
  7005. if (Result->getActiveBits() > 64 ||
  7006. Result->getZExtValue() >= numElements * 2)
  7007. return ExprError(Diag(TheCall->getBeginLoc(),
  7008. diag::err_shufflevector_argument_too_large)
  7009. << TheCall->getArg(i)->getSourceRange());
  7010. }
  7011. SmallVector<Expr*, 32> exprs;
  7012. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  7013. exprs.push_back(TheCall->getArg(i));
  7014. TheCall->setArg(i, nullptr);
  7015. }
  7016. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  7017. TheCall->getCallee()->getBeginLoc(),
  7018. TheCall->getRParenLoc());
  7019. }
  7020. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  7021. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  7022. SourceLocation BuiltinLoc,
  7023. SourceLocation RParenLoc) {
  7024. ExprValueKind VK = VK_PRValue;
  7025. ExprObjectKind OK = OK_Ordinary;
  7026. QualType DstTy = TInfo->getType();
  7027. QualType SrcTy = E->getType();
  7028. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  7029. return ExprError(Diag(BuiltinLoc,
  7030. diag::err_convertvector_non_vector)
  7031. << E->getSourceRange());
  7032. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  7033. return ExprError(Diag(BuiltinLoc,
  7034. diag::err_convertvector_non_vector_type));
  7035. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  7036. unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
  7037. unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
  7038. if (SrcElts != DstElts)
  7039. return ExprError(Diag(BuiltinLoc,
  7040. diag::err_convertvector_incompatible_vector)
  7041. << E->getSourceRange());
  7042. }
  7043. return new (Context)
  7044. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  7045. }
  7046. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  7047. // This is declared to take (const void*, ...) and can take two
  7048. // optional constant int args.
  7049. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  7050. unsigned NumArgs = TheCall->getNumArgs();
  7051. if (NumArgs > 3)
  7052. return Diag(TheCall->getEndLoc(),
  7053. diag::err_typecheck_call_too_many_args_at_most)
  7054. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  7055. // Argument 0 is checked for us and the remaining arguments must be
  7056. // constant integers.
  7057. for (unsigned i = 1; i != NumArgs; ++i)
  7058. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  7059. return true;
  7060. return false;
  7061. }
  7062. /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
  7063. bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
  7064. if (!Context.getTargetInfo().checkArithmeticFenceSupported())
  7065. return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  7066. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  7067. if (checkArgCount(*this, TheCall, 1))
  7068. return true;
  7069. Expr *Arg = TheCall->getArg(0);
  7070. if (Arg->isInstantiationDependent())
  7071. return false;
  7072. QualType ArgTy = Arg->getType();
  7073. if (!ArgTy->hasFloatingRepresentation())
  7074. return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
  7075. << ArgTy;
  7076. if (Arg->isLValue()) {
  7077. ExprResult FirstArg = DefaultLvalueConversion(Arg);
  7078. TheCall->setArg(0, FirstArg.get());
  7079. }
  7080. TheCall->setType(TheCall->getArg(0)->getType());
  7081. return false;
  7082. }
  7083. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  7084. // __assume does not evaluate its arguments, and should warn if its argument
  7085. // has side effects.
  7086. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  7087. Expr *Arg = TheCall->getArg(0);
  7088. if (Arg->isInstantiationDependent()) return false;
  7089. if (Arg->HasSideEffects(Context))
  7090. Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
  7091. << Arg->getSourceRange()
  7092. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  7093. return false;
  7094. }
  7095. /// Handle __builtin_alloca_with_align. This is declared
  7096. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  7097. /// than 8.
  7098. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  7099. // The alignment must be a constant integer.
  7100. Expr *Arg = TheCall->getArg(1);
  7101. // We can't check the value of a dependent argument.
  7102. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  7103. if (const auto *UE =
  7104. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  7105. if (UE->getKind() == UETT_AlignOf ||
  7106. UE->getKind() == UETT_PreferredAlignOf)
  7107. Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
  7108. << Arg->getSourceRange();
  7109. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  7110. if (!Result.isPowerOf2())
  7111. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  7112. << Arg->getSourceRange();
  7113. if (Result < Context.getCharWidth())
  7114. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
  7115. << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
  7116. if (Result > std::numeric_limits<int32_t>::max())
  7117. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
  7118. << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
  7119. }
  7120. return false;
  7121. }
  7122. /// Handle __builtin_assume_aligned. This is declared
  7123. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  7124. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  7125. if (checkArgCountRange(*this, TheCall, 2, 3))
  7126. return true;
  7127. unsigned NumArgs = TheCall->getNumArgs();
  7128. Expr *FirstArg = TheCall->getArg(0);
  7129. {
  7130. ExprResult FirstArgResult =
  7131. DefaultFunctionArrayLvalueConversion(FirstArg);
  7132. if (FirstArgResult.isInvalid())
  7133. return true;
  7134. TheCall->setArg(0, FirstArgResult.get());
  7135. }
  7136. // The alignment must be a constant integer.
  7137. Expr *SecondArg = TheCall->getArg(1);
  7138. // We can't check the value of a dependent argument.
  7139. if (!SecondArg->isValueDependent()) {
  7140. llvm::APSInt Result;
  7141. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  7142. return true;
  7143. if (!Result.isPowerOf2())
  7144. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  7145. << SecondArg->getSourceRange();
  7146. if (Result > Sema::MaximumAlignment)
  7147. Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
  7148. << SecondArg->getSourceRange() << Sema::MaximumAlignment;
  7149. }
  7150. if (NumArgs > 2) {
  7151. Expr *ThirdArg = TheCall->getArg(2);
  7152. if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
  7153. return true;
  7154. TheCall->setArg(2, ThirdArg);
  7155. }
  7156. return false;
  7157. }
  7158. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  7159. unsigned BuiltinID =
  7160. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  7161. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  7162. unsigned NumArgs = TheCall->getNumArgs();
  7163. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  7164. if (NumArgs < NumRequiredArgs) {
  7165. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  7166. << 0 /* function call */ << NumRequiredArgs << NumArgs
  7167. << TheCall->getSourceRange();
  7168. }
  7169. if (NumArgs >= NumRequiredArgs + 0x100) {
  7170. return Diag(TheCall->getEndLoc(),
  7171. diag::err_typecheck_call_too_many_args_at_most)
  7172. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  7173. << TheCall->getSourceRange();
  7174. }
  7175. unsigned i = 0;
  7176. // For formatting call, check buffer arg.
  7177. if (!IsSizeCall) {
  7178. ExprResult Arg(TheCall->getArg(i));
  7179. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  7180. Context, Context.VoidPtrTy, false);
  7181. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  7182. if (Arg.isInvalid())
  7183. return true;
  7184. TheCall->setArg(i, Arg.get());
  7185. i++;
  7186. }
  7187. // Check string literal arg.
  7188. unsigned FormatIdx = i;
  7189. {
  7190. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  7191. if (Arg.isInvalid())
  7192. return true;
  7193. TheCall->setArg(i, Arg.get());
  7194. i++;
  7195. }
  7196. // Make sure variadic args are scalar.
  7197. unsigned FirstDataArg = i;
  7198. while (i < NumArgs) {
  7199. ExprResult Arg = DefaultVariadicArgumentPromotion(
  7200. TheCall->getArg(i), VariadicFunction, nullptr);
  7201. if (Arg.isInvalid())
  7202. return true;
  7203. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  7204. if (ArgSize.getQuantity() >= 0x100) {
  7205. return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
  7206. << i << (int)ArgSize.getQuantity() << 0xff
  7207. << TheCall->getSourceRange();
  7208. }
  7209. TheCall->setArg(i, Arg.get());
  7210. i++;
  7211. }
  7212. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  7213. // call to avoid duplicate diagnostics.
  7214. if (!IsSizeCall) {
  7215. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  7216. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  7217. bool Success = CheckFormatArguments(
  7218. Args, FAPK_Variadic, FormatIdx, FirstDataArg, FST_OSLog,
  7219. VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
  7220. CheckedVarArgs);
  7221. if (!Success)
  7222. return true;
  7223. }
  7224. if (IsSizeCall) {
  7225. TheCall->setType(Context.getSizeType());
  7226. } else {
  7227. TheCall->setType(Context.VoidPtrTy);
  7228. }
  7229. return false;
  7230. }
  7231. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  7232. /// TheCall is a constant expression.
  7233. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  7234. llvm::APSInt &Result) {
  7235. Expr *Arg = TheCall->getArg(ArgNum);
  7236. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  7237. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  7238. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  7239. std::optional<llvm::APSInt> R;
  7240. if (!(R = Arg->getIntegerConstantExpr(Context)))
  7241. return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
  7242. << FDecl->getDeclName() << Arg->getSourceRange();
  7243. Result = *R;
  7244. return false;
  7245. }
  7246. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  7247. /// TheCall is a constant expression in the range [Low, High].
  7248. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  7249. int Low, int High, bool RangeIsError) {
  7250. if (isConstantEvaluated())
  7251. return false;
  7252. llvm::APSInt Result;
  7253. // We can't check the value of a dependent argument.
  7254. Expr *Arg = TheCall->getArg(ArgNum);
  7255. if (Arg->isTypeDependent() || Arg->isValueDependent())
  7256. return false;
  7257. // Check constant-ness first.
  7258. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  7259. return true;
  7260. if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
  7261. if (RangeIsError)
  7262. return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
  7263. << toString(Result, 10) << Low << High << Arg->getSourceRange();
  7264. else
  7265. // Defer the warning until we know if the code will be emitted so that
  7266. // dead code can ignore this.
  7267. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  7268. PDiag(diag::warn_argument_invalid_range)
  7269. << toString(Result, 10) << Low << High
  7270. << Arg->getSourceRange());
  7271. }
  7272. return false;
  7273. }
  7274. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  7275. /// TheCall is a constant expression is a multiple of Num..
  7276. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  7277. unsigned Num) {
  7278. llvm::APSInt Result;
  7279. // We can't check the value of a dependent argument.
  7280. Expr *Arg = TheCall->getArg(ArgNum);
  7281. if (Arg->isTypeDependent() || Arg->isValueDependent())
  7282. return false;
  7283. // Check constant-ness first.
  7284. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  7285. return true;
  7286. if (Result.getSExtValue() % Num != 0)
  7287. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
  7288. << Num << Arg->getSourceRange();
  7289. return false;
  7290. }
  7291. /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
  7292. /// constant expression representing a power of 2.
  7293. bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
  7294. llvm::APSInt Result;
  7295. // We can't check the value of a dependent argument.
  7296. Expr *Arg = TheCall->getArg(ArgNum);
  7297. if (Arg->isTypeDependent() || Arg->isValueDependent())
  7298. return false;
  7299. // Check constant-ness first.
  7300. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  7301. return true;
  7302. // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
  7303. // and only if x is a power of 2.
  7304. if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
  7305. return false;
  7306. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
  7307. << Arg->getSourceRange();
  7308. }
  7309. static bool IsShiftedByte(llvm::APSInt Value) {
  7310. if (Value.isNegative())
  7311. return false;
  7312. // Check if it's a shifted byte, by shifting it down
  7313. while (true) {
  7314. // If the value fits in the bottom byte, the check passes.
  7315. if (Value < 0x100)
  7316. return true;
  7317. // Otherwise, if the value has _any_ bits in the bottom byte, the check
  7318. // fails.
  7319. if ((Value & 0xFF) != 0)
  7320. return false;
  7321. // If the bottom 8 bits are all 0, but something above that is nonzero,
  7322. // then shifting the value right by 8 bits won't affect whether it's a
  7323. // shifted byte or not. So do that, and go round again.
  7324. Value >>= 8;
  7325. }
  7326. }
  7327. /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
  7328. /// a constant expression representing an arbitrary byte value shifted left by
  7329. /// a multiple of 8 bits.
  7330. bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
  7331. unsigned ArgBits) {
  7332. llvm::APSInt Result;
  7333. // We can't check the value of a dependent argument.
  7334. Expr *Arg = TheCall->getArg(ArgNum);
  7335. if (Arg->isTypeDependent() || Arg->isValueDependent())
  7336. return false;
  7337. // Check constant-ness first.
  7338. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  7339. return true;
  7340. // Truncate to the given size.
  7341. Result = Result.getLoBits(ArgBits);
  7342. Result.setIsUnsigned(true);
  7343. if (IsShiftedByte(Result))
  7344. return false;
  7345. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
  7346. << Arg->getSourceRange();
  7347. }
  7348. /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
  7349. /// TheCall is a constant expression representing either a shifted byte value,
  7350. /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
  7351. /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
  7352. /// Arm MVE intrinsics.
  7353. bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
  7354. int ArgNum,
  7355. unsigned ArgBits) {
  7356. llvm::APSInt Result;
  7357. // We can't check the value of a dependent argument.
  7358. Expr *Arg = TheCall->getArg(ArgNum);
  7359. if (Arg->isTypeDependent() || Arg->isValueDependent())
  7360. return false;
  7361. // Check constant-ness first.
  7362. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  7363. return true;
  7364. // Truncate to the given size.
  7365. Result = Result.getLoBits(ArgBits);
  7366. Result.setIsUnsigned(true);
  7367. // Check to see if it's in either of the required forms.
  7368. if (IsShiftedByte(Result) ||
  7369. (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
  7370. return false;
  7371. return Diag(TheCall->getBeginLoc(),
  7372. diag::err_argument_not_shifted_byte_or_xxff)
  7373. << Arg->getSourceRange();
  7374. }
  7375. /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
  7376. bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
  7377. if (BuiltinID == AArch64::BI__builtin_arm_irg) {
  7378. if (checkArgCount(*this, TheCall, 2))
  7379. return true;
  7380. Expr *Arg0 = TheCall->getArg(0);
  7381. Expr *Arg1 = TheCall->getArg(1);
  7382. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  7383. if (FirstArg.isInvalid())
  7384. return true;
  7385. QualType FirstArgType = FirstArg.get()->getType();
  7386. if (!FirstArgType->isAnyPointerType())
  7387. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  7388. << "first" << FirstArgType << Arg0->getSourceRange();
  7389. TheCall->setArg(0, FirstArg.get());
  7390. ExprResult SecArg = DefaultLvalueConversion(Arg1);
  7391. if (SecArg.isInvalid())
  7392. return true;
  7393. QualType SecArgType = SecArg.get()->getType();
  7394. if (!SecArgType->isIntegerType())
  7395. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  7396. << "second" << SecArgType << Arg1->getSourceRange();
  7397. // Derive the return type from the pointer argument.
  7398. TheCall->setType(FirstArgType);
  7399. return false;
  7400. }
  7401. if (BuiltinID == AArch64::BI__builtin_arm_addg) {
  7402. if (checkArgCount(*this, TheCall, 2))
  7403. return true;
  7404. Expr *Arg0 = TheCall->getArg(0);
  7405. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  7406. if (FirstArg.isInvalid())
  7407. return true;
  7408. QualType FirstArgType = FirstArg.get()->getType();
  7409. if (!FirstArgType->isAnyPointerType())
  7410. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  7411. << "first" << FirstArgType << Arg0->getSourceRange();
  7412. TheCall->setArg(0, FirstArg.get());
  7413. // Derive the return type from the pointer argument.
  7414. TheCall->setType(FirstArgType);
  7415. // Second arg must be an constant in range [0,15]
  7416. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  7417. }
  7418. if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
  7419. if (checkArgCount(*this, TheCall, 2))
  7420. return true;
  7421. Expr *Arg0 = TheCall->getArg(0);
  7422. Expr *Arg1 = TheCall->getArg(1);
  7423. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  7424. if (FirstArg.isInvalid())
  7425. return true;
  7426. QualType FirstArgType = FirstArg.get()->getType();
  7427. if (!FirstArgType->isAnyPointerType())
  7428. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  7429. << "first" << FirstArgType << Arg0->getSourceRange();
  7430. QualType SecArgType = Arg1->getType();
  7431. if (!SecArgType->isIntegerType())
  7432. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  7433. << "second" << SecArgType << Arg1->getSourceRange();
  7434. TheCall->setType(Context.IntTy);
  7435. return false;
  7436. }
  7437. if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
  7438. BuiltinID == AArch64::BI__builtin_arm_stg) {
  7439. if (checkArgCount(*this, TheCall, 1))
  7440. return true;
  7441. Expr *Arg0 = TheCall->getArg(0);
  7442. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  7443. if (FirstArg.isInvalid())
  7444. return true;
  7445. QualType FirstArgType = FirstArg.get()->getType();
  7446. if (!FirstArgType->isAnyPointerType())
  7447. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  7448. << "first" << FirstArgType << Arg0->getSourceRange();
  7449. TheCall->setArg(0, FirstArg.get());
  7450. // Derive the return type from the pointer argument.
  7451. if (BuiltinID == AArch64::BI__builtin_arm_ldg)
  7452. TheCall->setType(FirstArgType);
  7453. return false;
  7454. }
  7455. if (BuiltinID == AArch64::BI__builtin_arm_subp) {
  7456. Expr *ArgA = TheCall->getArg(0);
  7457. Expr *ArgB = TheCall->getArg(1);
  7458. ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
  7459. ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
  7460. if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
  7461. return true;
  7462. QualType ArgTypeA = ArgExprA.get()->getType();
  7463. QualType ArgTypeB = ArgExprB.get()->getType();
  7464. auto isNull = [&] (Expr *E) -> bool {
  7465. return E->isNullPointerConstant(
  7466. Context, Expr::NPC_ValueDependentIsNotNull); };
  7467. // argument should be either a pointer or null
  7468. if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
  7469. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  7470. << "first" << ArgTypeA << ArgA->getSourceRange();
  7471. if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
  7472. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  7473. << "second" << ArgTypeB << ArgB->getSourceRange();
  7474. // Ensure Pointee types are compatible
  7475. if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
  7476. ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
  7477. QualType pointeeA = ArgTypeA->getPointeeType();
  7478. QualType pointeeB = ArgTypeB->getPointeeType();
  7479. if (!Context.typesAreCompatible(
  7480. Context.getCanonicalType(pointeeA).getUnqualifiedType(),
  7481. Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
  7482. return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
  7483. << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
  7484. << ArgB->getSourceRange();
  7485. }
  7486. }
  7487. // at least one argument should be pointer type
  7488. if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
  7489. return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
  7490. << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
  7491. if (isNull(ArgA)) // adopt type of the other pointer
  7492. ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
  7493. if (isNull(ArgB))
  7494. ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
  7495. TheCall->setArg(0, ArgExprA.get());
  7496. TheCall->setArg(1, ArgExprB.get());
  7497. TheCall->setType(Context.LongLongTy);
  7498. return false;
  7499. }
  7500. assert(false && "Unhandled ARM MTE intrinsic");
  7501. return true;
  7502. }
  7503. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  7504. /// TheCall is an ARM/AArch64 special register string literal.
  7505. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  7506. int ArgNum, unsigned ExpectedFieldNum,
  7507. bool AllowName) {
  7508. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  7509. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  7510. BuiltinID == ARM::BI__builtin_arm_rsr ||
  7511. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  7512. BuiltinID == ARM::BI__builtin_arm_wsr ||
  7513. BuiltinID == ARM::BI__builtin_arm_wsrp;
  7514. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  7515. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  7516. BuiltinID == AArch64::BI__builtin_arm_rsr128 ||
  7517. BuiltinID == AArch64::BI__builtin_arm_wsr128 ||
  7518. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  7519. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  7520. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  7521. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  7522. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  7523. // We can't check the value of a dependent argument.
  7524. Expr *Arg = TheCall->getArg(ArgNum);
  7525. if (Arg->isTypeDependent() || Arg->isValueDependent())
  7526. return false;
  7527. // Check if the argument is a string literal.
  7528. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  7529. return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  7530. << Arg->getSourceRange();
  7531. // Check the type of special register given.
  7532. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  7533. SmallVector<StringRef, 6> Fields;
  7534. Reg.split(Fields, ":");
  7535. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  7536. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  7537. << Arg->getSourceRange();
  7538. // If the string is the name of a register then we cannot check that it is
  7539. // valid here but if the string is of one the forms described in ACLE then we
  7540. // can check that the supplied fields are integers and within the valid
  7541. // ranges.
  7542. if (Fields.size() > 1) {
  7543. bool FiveFields = Fields.size() == 5;
  7544. bool ValidString = true;
  7545. if (IsARMBuiltin) {
  7546. ValidString &= Fields[0].startswith_insensitive("cp") ||
  7547. Fields[0].startswith_insensitive("p");
  7548. if (ValidString)
  7549. Fields[0] = Fields[0].drop_front(
  7550. Fields[0].startswith_insensitive("cp") ? 2 : 1);
  7551. ValidString &= Fields[2].startswith_insensitive("c");
  7552. if (ValidString)
  7553. Fields[2] = Fields[2].drop_front(1);
  7554. if (FiveFields) {
  7555. ValidString &= Fields[3].startswith_insensitive("c");
  7556. if (ValidString)
  7557. Fields[3] = Fields[3].drop_front(1);
  7558. }
  7559. }
  7560. SmallVector<int, 5> Ranges;
  7561. if (FiveFields)
  7562. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  7563. else
  7564. Ranges.append({15, 7, 15});
  7565. for (unsigned i=0; i<Fields.size(); ++i) {
  7566. int IntField;
  7567. ValidString &= !Fields[i].getAsInteger(10, IntField);
  7568. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  7569. }
  7570. if (!ValidString)
  7571. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  7572. << Arg->getSourceRange();
  7573. } else if (IsAArch64Builtin && Fields.size() == 1) {
  7574. // This code validates writes to PSTATE registers.
  7575. // Not a write.
  7576. if (TheCall->getNumArgs() != 2)
  7577. return false;
  7578. // The 128-bit system register accesses do not touch PSTATE.
  7579. if (BuiltinID == AArch64::BI__builtin_arm_rsr128 ||
  7580. BuiltinID == AArch64::BI__builtin_arm_wsr128)
  7581. return false;
  7582. // These are the named PSTATE accesses using "MSR (immediate)" instructions,
  7583. // along with the upper limit on the immediates allowed.
  7584. auto MaxLimit = llvm::StringSwitch<std::optional<unsigned>>(Reg)
  7585. .CaseLower("spsel", 15)
  7586. .CaseLower("daifclr", 15)
  7587. .CaseLower("daifset", 15)
  7588. .CaseLower("pan", 15)
  7589. .CaseLower("uao", 15)
  7590. .CaseLower("dit", 15)
  7591. .CaseLower("ssbs", 15)
  7592. .CaseLower("tco", 15)
  7593. .CaseLower("allint", 1)
  7594. .CaseLower("pm", 1)
  7595. .Default(std::nullopt);
  7596. // If this is not a named PSTATE, just continue without validating, as this
  7597. // will be lowered to an "MSR (register)" instruction directly
  7598. if (!MaxLimit)
  7599. return false;
  7600. // Here we only allow constants in the range for that pstate, as required by
  7601. // the ACLE.
  7602. //
  7603. // While clang also accepts the names of system registers in its ACLE
  7604. // intrinsics, we prevent this with the PSTATE names used in MSR (immediate)
  7605. // as the value written via a register is different to the value used as an
  7606. // immediate to have the same effect. e.g., for the instruction `msr tco,
  7607. // x0`, it is bit 25 of register x0 that is written into PSTATE.TCO, but
  7608. // with `msr tco, #imm`, it is bit 0 of xN that is written into PSTATE.TCO.
  7609. //
  7610. // If a programmer wants to codegen the MSR (register) form of `msr tco,
  7611. // xN`, they can still do so by specifying the register using five
  7612. // colon-separated numbers in a string.
  7613. return SemaBuiltinConstantArgRange(TheCall, 1, 0, *MaxLimit);
  7614. }
  7615. return false;
  7616. }
  7617. /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
  7618. /// Emit an error and return true on failure; return false on success.
  7619. /// TypeStr is a string containing the type descriptor of the value returned by
  7620. /// the builtin and the descriptors of the expected type of the arguments.
  7621. bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
  7622. const char *TypeStr) {
  7623. assert((TypeStr[0] != '\0') &&
  7624. "Invalid types in PPC MMA builtin declaration");
  7625. switch (BuiltinID) {
  7626. default:
  7627. // This function is called in CheckPPCBuiltinFunctionCall where the
  7628. // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
  7629. // we are isolating the pair vector memop builtins that can be used with mma
  7630. // off so the default case is every builtin that requires mma and paired
  7631. // vector memops.
  7632. if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
  7633. diag::err_ppc_builtin_only_on_arch, "10") ||
  7634. SemaFeatureCheck(*this, TheCall, "mma",
  7635. diag::err_ppc_builtin_only_on_arch, "10"))
  7636. return true;
  7637. break;
  7638. case PPC::BI__builtin_vsx_lxvp:
  7639. case PPC::BI__builtin_vsx_stxvp:
  7640. case PPC::BI__builtin_vsx_assemble_pair:
  7641. case PPC::BI__builtin_vsx_disassemble_pair:
  7642. if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
  7643. diag::err_ppc_builtin_only_on_arch, "10"))
  7644. return true;
  7645. break;
  7646. }
  7647. unsigned Mask = 0;
  7648. unsigned ArgNum = 0;
  7649. // The first type in TypeStr is the type of the value returned by the
  7650. // builtin. So we first read that type and change the type of TheCall.
  7651. QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
  7652. TheCall->setType(type);
  7653. while (*TypeStr != '\0') {
  7654. Mask = 0;
  7655. QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
  7656. if (ArgNum >= TheCall->getNumArgs()) {
  7657. ArgNum++;
  7658. break;
  7659. }
  7660. Expr *Arg = TheCall->getArg(ArgNum);
  7661. QualType PassedType = Arg->getType();
  7662. QualType StrippedRVType = PassedType.getCanonicalType();
  7663. // Strip Restrict/Volatile qualifiers.
  7664. if (StrippedRVType.isRestrictQualified() ||
  7665. StrippedRVType.isVolatileQualified())
  7666. StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
  7667. // The only case where the argument type and expected type are allowed to
  7668. // mismatch is if the argument type is a non-void pointer (or array) and
  7669. // expected type is a void pointer.
  7670. if (StrippedRVType != ExpectedType)
  7671. if (!(ExpectedType->isVoidPointerType() &&
  7672. (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
  7673. return Diag(Arg->getBeginLoc(),
  7674. diag::err_typecheck_convert_incompatible)
  7675. << PassedType << ExpectedType << 1 << 0 << 0;
  7676. // If the value of the Mask is not 0, we have a constraint in the size of
  7677. // the integer argument so here we ensure the argument is a constant that
  7678. // is in the valid range.
  7679. if (Mask != 0 &&
  7680. SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
  7681. return true;
  7682. ArgNum++;
  7683. }
  7684. // In case we exited early from the previous loop, there are other types to
  7685. // read from TypeStr. So we need to read them all to ensure we have the right
  7686. // number of arguments in TheCall and if it is not the case, to display a
  7687. // better error message.
  7688. while (*TypeStr != '\0') {
  7689. (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
  7690. ArgNum++;
  7691. }
  7692. if (checkArgCount(*this, TheCall, ArgNum))
  7693. return true;
  7694. return false;
  7695. }
  7696. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  7697. /// This checks that the target supports __builtin_longjmp and
  7698. /// that val is a constant 1.
  7699. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  7700. if (!Context.getTargetInfo().hasSjLjLowering())
  7701. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
  7702. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  7703. Expr *Arg = TheCall->getArg(1);
  7704. llvm::APSInt Result;
  7705. // TODO: This is less than ideal. Overload this to take a value.
  7706. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  7707. return true;
  7708. if (Result != 1)
  7709. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
  7710. << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
  7711. return false;
  7712. }
  7713. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  7714. /// This checks that the target supports __builtin_setjmp.
  7715. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  7716. if (!Context.getTargetInfo().hasSjLjLowering())
  7717. return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
  7718. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  7719. return false;
  7720. }
  7721. namespace {
  7722. class UncoveredArgHandler {
  7723. enum { Unknown = -1, AllCovered = -2 };
  7724. signed FirstUncoveredArg = Unknown;
  7725. SmallVector<const Expr *, 4> DiagnosticExprs;
  7726. public:
  7727. UncoveredArgHandler() = default;
  7728. bool hasUncoveredArg() const {
  7729. return (FirstUncoveredArg >= 0);
  7730. }
  7731. unsigned getUncoveredArg() const {
  7732. assert(hasUncoveredArg() && "no uncovered argument");
  7733. return FirstUncoveredArg;
  7734. }
  7735. void setAllCovered() {
  7736. // A string has been found with all arguments covered, so clear out
  7737. // the diagnostics.
  7738. DiagnosticExprs.clear();
  7739. FirstUncoveredArg = AllCovered;
  7740. }
  7741. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  7742. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  7743. // Don't update if a previous string covers all arguments.
  7744. if (FirstUncoveredArg == AllCovered)
  7745. return;
  7746. // UncoveredArgHandler tracks the highest uncovered argument index
  7747. // and with it all the strings that match this index.
  7748. if (NewFirstUncoveredArg == FirstUncoveredArg)
  7749. DiagnosticExprs.push_back(StrExpr);
  7750. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  7751. DiagnosticExprs.clear();
  7752. DiagnosticExprs.push_back(StrExpr);
  7753. FirstUncoveredArg = NewFirstUncoveredArg;
  7754. }
  7755. }
  7756. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  7757. };
  7758. enum StringLiteralCheckType {
  7759. SLCT_NotALiteral,
  7760. SLCT_UncheckedLiteral,
  7761. SLCT_CheckedLiteral
  7762. };
  7763. } // namespace
  7764. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  7765. BinaryOperatorKind BinOpKind,
  7766. bool AddendIsRight) {
  7767. unsigned BitWidth = Offset.getBitWidth();
  7768. unsigned AddendBitWidth = Addend.getBitWidth();
  7769. // There might be negative interim results.
  7770. if (Addend.isUnsigned()) {
  7771. Addend = Addend.zext(++AddendBitWidth);
  7772. Addend.setIsSigned(true);
  7773. }
  7774. // Adjust the bit width of the APSInts.
  7775. if (AddendBitWidth > BitWidth) {
  7776. Offset = Offset.sext(AddendBitWidth);
  7777. BitWidth = AddendBitWidth;
  7778. } else if (BitWidth > AddendBitWidth) {
  7779. Addend = Addend.sext(BitWidth);
  7780. }
  7781. bool Ov = false;
  7782. llvm::APSInt ResOffset = Offset;
  7783. if (BinOpKind == BO_Add)
  7784. ResOffset = Offset.sadd_ov(Addend, Ov);
  7785. else {
  7786. assert(AddendIsRight && BinOpKind == BO_Sub &&
  7787. "operator must be add or sub with addend on the right");
  7788. ResOffset = Offset.ssub_ov(Addend, Ov);
  7789. }
  7790. // We add an offset to a pointer here so we should support an offset as big as
  7791. // possible.
  7792. if (Ov) {
  7793. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  7794. "index (intermediate) result too big");
  7795. Offset = Offset.sext(2 * BitWidth);
  7796. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  7797. return;
  7798. }
  7799. Offset = ResOffset;
  7800. }
  7801. namespace {
  7802. // This is a wrapper class around StringLiteral to support offsetted string
  7803. // literals as format strings. It takes the offset into account when returning
  7804. // the string and its length or the source locations to display notes correctly.
  7805. class FormatStringLiteral {
  7806. const StringLiteral *FExpr;
  7807. int64_t Offset;
  7808. public:
  7809. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  7810. : FExpr(fexpr), Offset(Offset) {}
  7811. StringRef getString() const {
  7812. return FExpr->getString().drop_front(Offset);
  7813. }
  7814. unsigned getByteLength() const {
  7815. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  7816. }
  7817. unsigned getLength() const { return FExpr->getLength() - Offset; }
  7818. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  7819. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  7820. QualType getType() const { return FExpr->getType(); }
  7821. bool isAscii() const { return FExpr->isOrdinary(); }
  7822. bool isWide() const { return FExpr->isWide(); }
  7823. bool isUTF8() const { return FExpr->isUTF8(); }
  7824. bool isUTF16() const { return FExpr->isUTF16(); }
  7825. bool isUTF32() const { return FExpr->isUTF32(); }
  7826. bool isPascal() const { return FExpr->isPascal(); }
  7827. SourceLocation getLocationOfByte(
  7828. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  7829. const TargetInfo &Target, unsigned *StartToken = nullptr,
  7830. unsigned *StartTokenByteOffset = nullptr) const {
  7831. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  7832. StartToken, StartTokenByteOffset);
  7833. }
  7834. SourceLocation getBeginLoc() const LLVM_READONLY {
  7835. return FExpr->getBeginLoc().getLocWithOffset(Offset);
  7836. }
  7837. SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
  7838. };
  7839. } // namespace
  7840. static void CheckFormatString(
  7841. Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
  7842. ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
  7843. unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
  7844. bool inFunctionCall, Sema::VariadicCallType CallType,
  7845. llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
  7846. bool IgnoreStringsWithoutSpecifiers);
  7847. static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
  7848. const Expr *E);
  7849. // Determine if an expression is a string literal or constant string.
  7850. // If this function returns false on the arguments to a function expecting a
  7851. // format string, we will usually need to emit a warning.
  7852. // True string literals are then checked by CheckFormatString.
  7853. static StringLiteralCheckType
  7854. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  7855. Sema::FormatArgumentPassingKind APK, unsigned format_idx,
  7856. unsigned firstDataArg, Sema::FormatStringType Type,
  7857. Sema::VariadicCallType CallType, bool InFunctionCall,
  7858. llvm::SmallBitVector &CheckedVarArgs,
  7859. UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
  7860. bool IgnoreStringsWithoutSpecifiers = false) {
  7861. if (S.isConstantEvaluated())
  7862. return SLCT_NotALiteral;
  7863. tryAgain:
  7864. assert(Offset.isSigned() && "invalid offset");
  7865. if (E->isTypeDependent() || E->isValueDependent())
  7866. return SLCT_NotALiteral;
  7867. E = E->IgnoreParenCasts();
  7868. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  7869. // Technically -Wformat-nonliteral does not warn about this case.
  7870. // The behavior of printf and friends in this case is implementation
  7871. // dependent. Ideally if the format string cannot be null then
  7872. // it should have a 'nonnull' attribute in the function prototype.
  7873. return SLCT_UncheckedLiteral;
  7874. switch (E->getStmtClass()) {
  7875. case Stmt::InitListExprClass:
  7876. // Handle expressions like {"foobar"}.
  7877. if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
  7878. return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
  7879. Type, CallType, /*InFunctionCall*/ false,
  7880. CheckedVarArgs, UncoveredArg, Offset,
  7881. IgnoreStringsWithoutSpecifiers);
  7882. }
  7883. return SLCT_NotALiteral;
  7884. case Stmt::BinaryConditionalOperatorClass:
  7885. case Stmt::ConditionalOperatorClass: {
  7886. // The expression is a literal if both sub-expressions were, and it was
  7887. // completely checked only if both sub-expressions were checked.
  7888. const AbstractConditionalOperator *C =
  7889. cast<AbstractConditionalOperator>(E);
  7890. // Determine whether it is necessary to check both sub-expressions, for
  7891. // example, because the condition expression is a constant that can be
  7892. // evaluated at compile time.
  7893. bool CheckLeft = true, CheckRight = true;
  7894. bool Cond;
  7895. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
  7896. S.isConstantEvaluated())) {
  7897. if (Cond)
  7898. CheckRight = false;
  7899. else
  7900. CheckLeft = false;
  7901. }
  7902. // We need to maintain the offsets for the right and the left hand side
  7903. // separately to check if every possible indexed expression is a valid
  7904. // string literal. They might have different offsets for different string
  7905. // literals in the end.
  7906. StringLiteralCheckType Left;
  7907. if (!CheckLeft)
  7908. Left = SLCT_UncheckedLiteral;
  7909. else {
  7910. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, APK, format_idx,
  7911. firstDataArg, Type, CallType, InFunctionCall,
  7912. CheckedVarArgs, UncoveredArg, Offset,
  7913. IgnoreStringsWithoutSpecifiers);
  7914. if (Left == SLCT_NotALiteral || !CheckRight) {
  7915. return Left;
  7916. }
  7917. }
  7918. StringLiteralCheckType Right = checkFormatStringExpr(
  7919. S, C->getFalseExpr(), Args, APK, format_idx, firstDataArg, Type,
  7920. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  7921. IgnoreStringsWithoutSpecifiers);
  7922. return (CheckLeft && Left < Right) ? Left : Right;
  7923. }
  7924. case Stmt::ImplicitCastExprClass:
  7925. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  7926. goto tryAgain;
  7927. case Stmt::OpaqueValueExprClass:
  7928. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  7929. E = src;
  7930. goto tryAgain;
  7931. }
  7932. return SLCT_NotALiteral;
  7933. case Stmt::PredefinedExprClass:
  7934. // While __func__, etc., are technically not string literals, they
  7935. // cannot contain format specifiers and thus are not a security
  7936. // liability.
  7937. return SLCT_UncheckedLiteral;
  7938. case Stmt::DeclRefExprClass: {
  7939. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  7940. // As an exception, do not flag errors for variables binding to
  7941. // const string literals.
  7942. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  7943. bool isConstant = false;
  7944. QualType T = DR->getType();
  7945. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  7946. isConstant = AT->getElementType().isConstant(S.Context);
  7947. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  7948. isConstant = T.isConstant(S.Context) &&
  7949. PT->getPointeeType().isConstant(S.Context);
  7950. } else if (T->isObjCObjectPointerType()) {
  7951. // In ObjC, there is usually no "const ObjectPointer" type,
  7952. // so don't check if the pointee type is constant.
  7953. isConstant = T.isConstant(S.Context);
  7954. }
  7955. if (isConstant) {
  7956. if (const Expr *Init = VD->getAnyInitializer()) {
  7957. // Look through initializers like const char c[] = { "foo" }
  7958. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  7959. if (InitList->isStringLiteralInit())
  7960. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  7961. }
  7962. return checkFormatStringExpr(
  7963. S, Init, Args, APK, format_idx, firstDataArg, Type, CallType,
  7964. /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
  7965. }
  7966. }
  7967. // When the format argument is an argument of this function, and this
  7968. // function also has the format attribute, there are several interactions
  7969. // for which there shouldn't be a warning. For instance, when calling
  7970. // v*printf from a function that has the printf format attribute, we
  7971. // should not emit a warning about using `fmt`, even though it's not
  7972. // constant, because the arguments have already been checked for the
  7973. // caller of `logmessage`:
  7974. //
  7975. // __attribute__((format(printf, 1, 2)))
  7976. // void logmessage(char const *fmt, ...) {
  7977. // va_list ap;
  7978. // va_start(ap, fmt);
  7979. // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
  7980. // ...
  7981. // }
  7982. //
  7983. // Another interaction that we need to support is calling a variadic
  7984. // format function from a format function that has fixed arguments. For
  7985. // instance:
  7986. //
  7987. // __attribute__((format(printf, 1, 2)))
  7988. // void logstring(char const *fmt, char const *str) {
  7989. // printf(fmt, str); /* do not emit a warning about "fmt" */
  7990. // }
  7991. //
  7992. // Same (and perhaps more relatably) for the variadic template case:
  7993. //
  7994. // template<typename... Args>
  7995. // __attribute__((format(printf, 1, 2)))
  7996. // void log(const char *fmt, Args&&... args) {
  7997. // printf(fmt, forward<Args>(args)...);
  7998. // /* do not emit a warning about "fmt" */
  7999. // }
  8000. //
  8001. // Due to implementation difficulty, we only check the format, not the
  8002. // format arguments, in all cases.
  8003. //
  8004. if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
  8005. if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
  8006. for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
  8007. bool IsCXXMember = false;
  8008. if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
  8009. IsCXXMember = MD->isInstance();
  8010. bool IsVariadic = false;
  8011. if (const FunctionType *FnTy = D->getFunctionType())
  8012. IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
  8013. else if (const auto *BD = dyn_cast<BlockDecl>(D))
  8014. IsVariadic = BD->isVariadic();
  8015. else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
  8016. IsVariadic = OMD->isVariadic();
  8017. Sema::FormatStringInfo CallerFSI;
  8018. if (Sema::getFormatStringInfo(PVFormat, IsCXXMember, IsVariadic,
  8019. &CallerFSI)) {
  8020. // We also check if the formats are compatible.
  8021. // We can't pass a 'scanf' string to a 'printf' function.
  8022. if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx &&
  8023. Type == S.GetFormatStringType(PVFormat)) {
  8024. // Lastly, check that argument passing kinds transition in a
  8025. // way that makes sense:
  8026. // from a caller with FAPK_VAList, allow FAPK_VAList
  8027. // from a caller with FAPK_Fixed, allow FAPK_Fixed
  8028. // from a caller with FAPK_Fixed, allow FAPK_Variadic
  8029. // from a caller with FAPK_Variadic, allow FAPK_VAList
  8030. switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
  8031. case combineFAPK(Sema::FAPK_VAList, Sema::FAPK_VAList):
  8032. case combineFAPK(Sema::FAPK_Fixed, Sema::FAPK_Fixed):
  8033. case combineFAPK(Sema::FAPK_Fixed, Sema::FAPK_Variadic):
  8034. case combineFAPK(Sema::FAPK_Variadic, Sema::FAPK_VAList):
  8035. return SLCT_UncheckedLiteral;
  8036. }
  8037. }
  8038. }
  8039. }
  8040. }
  8041. }
  8042. }
  8043. return SLCT_NotALiteral;
  8044. }
  8045. case Stmt::CallExprClass:
  8046. case Stmt::CXXMemberCallExprClass: {
  8047. const CallExpr *CE = cast<CallExpr>(E);
  8048. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  8049. bool IsFirst = true;
  8050. StringLiteralCheckType CommonResult;
  8051. for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
  8052. const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
  8053. StringLiteralCheckType Result = checkFormatStringExpr(
  8054. S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
  8055. InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  8056. IgnoreStringsWithoutSpecifiers);
  8057. if (IsFirst) {
  8058. CommonResult = Result;
  8059. IsFirst = false;
  8060. }
  8061. }
  8062. if (!IsFirst)
  8063. return CommonResult;
  8064. if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
  8065. unsigned BuiltinID = FD->getBuiltinID();
  8066. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  8067. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  8068. const Expr *Arg = CE->getArg(0);
  8069. return checkFormatStringExpr(
  8070. S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
  8071. InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  8072. IgnoreStringsWithoutSpecifiers);
  8073. }
  8074. }
  8075. }
  8076. if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
  8077. return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
  8078. Type, CallType, /*InFunctionCall*/ false,
  8079. CheckedVarArgs, UncoveredArg, Offset,
  8080. IgnoreStringsWithoutSpecifiers);
  8081. return SLCT_NotALiteral;
  8082. }
  8083. case Stmt::ObjCMessageExprClass: {
  8084. const auto *ME = cast<ObjCMessageExpr>(E);
  8085. if (const auto *MD = ME->getMethodDecl()) {
  8086. if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
  8087. // As a special case heuristic, if we're using the method -[NSBundle
  8088. // localizedStringForKey:value:table:], ignore any key strings that lack
  8089. // format specifiers. The idea is that if the key doesn't have any
  8090. // format specifiers then its probably just a key to map to the
  8091. // localized strings. If it does have format specifiers though, then its
  8092. // likely that the text of the key is the format string in the
  8093. // programmer's language, and should be checked.
  8094. const ObjCInterfaceDecl *IFace;
  8095. if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
  8096. IFace->getIdentifier()->isStr("NSBundle") &&
  8097. MD->getSelector().isKeywordSelector(
  8098. {"localizedStringForKey", "value", "table"})) {
  8099. IgnoreStringsWithoutSpecifiers = true;
  8100. }
  8101. const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
  8102. return checkFormatStringExpr(
  8103. S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
  8104. InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  8105. IgnoreStringsWithoutSpecifiers);
  8106. }
  8107. }
  8108. return SLCT_NotALiteral;
  8109. }
  8110. case Stmt::ObjCStringLiteralClass:
  8111. case Stmt::StringLiteralClass: {
  8112. const StringLiteral *StrE = nullptr;
  8113. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  8114. StrE = ObjCFExpr->getString();
  8115. else
  8116. StrE = cast<StringLiteral>(E);
  8117. if (StrE) {
  8118. if (Offset.isNegative() || Offset > StrE->getLength()) {
  8119. // TODO: It would be better to have an explicit warning for out of
  8120. // bounds literals.
  8121. return SLCT_NotALiteral;
  8122. }
  8123. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  8124. CheckFormatString(S, &FStr, E, Args, APK, format_idx, firstDataArg, Type,
  8125. InFunctionCall, CallType, CheckedVarArgs, UncoveredArg,
  8126. IgnoreStringsWithoutSpecifiers);
  8127. return SLCT_CheckedLiteral;
  8128. }
  8129. return SLCT_NotALiteral;
  8130. }
  8131. case Stmt::BinaryOperatorClass: {
  8132. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  8133. // A string literal + an int offset is still a string literal.
  8134. if (BinOp->isAdditiveOp()) {
  8135. Expr::EvalResult LResult, RResult;
  8136. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
  8137. LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  8138. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
  8139. RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  8140. if (LIsInt != RIsInt) {
  8141. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  8142. if (LIsInt) {
  8143. if (BinOpKind == BO_Add) {
  8144. sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
  8145. E = BinOp->getRHS();
  8146. goto tryAgain;
  8147. }
  8148. } else {
  8149. sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
  8150. E = BinOp->getLHS();
  8151. goto tryAgain;
  8152. }
  8153. }
  8154. }
  8155. return SLCT_NotALiteral;
  8156. }
  8157. case Stmt::UnaryOperatorClass: {
  8158. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  8159. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  8160. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  8161. Expr::EvalResult IndexResult;
  8162. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
  8163. Expr::SE_NoSideEffects,
  8164. S.isConstantEvaluated())) {
  8165. sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
  8166. /*RHS is int*/ true);
  8167. E = ASE->getBase();
  8168. goto tryAgain;
  8169. }
  8170. }
  8171. return SLCT_NotALiteral;
  8172. }
  8173. default:
  8174. return SLCT_NotALiteral;
  8175. }
  8176. }
  8177. // If this expression can be evaluated at compile-time,
  8178. // check if the result is a StringLiteral and return it
  8179. // otherwise return nullptr
  8180. static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
  8181. const Expr *E) {
  8182. Expr::EvalResult Result;
  8183. if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
  8184. const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
  8185. if (isa_and_nonnull<StringLiteral>(LVE))
  8186. return LVE;
  8187. }
  8188. return nullptr;
  8189. }
  8190. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  8191. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  8192. .Case("scanf", FST_Scanf)
  8193. .Cases("printf", "printf0", FST_Printf)
  8194. .Cases("NSString", "CFString", FST_NSString)
  8195. .Case("strftime", FST_Strftime)
  8196. .Case("strfmon", FST_Strfmon)
  8197. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  8198. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  8199. .Case("os_trace", FST_OSLog)
  8200. .Case("os_log", FST_OSLog)
  8201. .Default(FST_Unknown);
  8202. }
  8203. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  8204. /// functions) for correct use of format strings.
  8205. /// Returns true if a format string has been fully checked.
  8206. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  8207. ArrayRef<const Expr *> Args, bool IsCXXMember,
  8208. VariadicCallType CallType, SourceLocation Loc,
  8209. SourceRange Range,
  8210. llvm::SmallBitVector &CheckedVarArgs) {
  8211. FormatStringInfo FSI;
  8212. if (getFormatStringInfo(Format, IsCXXMember, CallType != VariadicDoesNotApply,
  8213. &FSI))
  8214. return CheckFormatArguments(Args, FSI.ArgPassingKind, FSI.FormatIdx,
  8215. FSI.FirstDataArg, GetFormatStringType(Format),
  8216. CallType, Loc, Range, CheckedVarArgs);
  8217. return false;
  8218. }
  8219. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  8220. Sema::FormatArgumentPassingKind APK,
  8221. unsigned format_idx, unsigned firstDataArg,
  8222. FormatStringType Type,
  8223. VariadicCallType CallType, SourceLocation Loc,
  8224. SourceRange Range,
  8225. llvm::SmallBitVector &CheckedVarArgs) {
  8226. // CHECK: printf/scanf-like function is called with no format string.
  8227. if (format_idx >= Args.size()) {
  8228. Diag(Loc, diag::warn_missing_format_string) << Range;
  8229. return false;
  8230. }
  8231. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  8232. // CHECK: format string is not a string literal.
  8233. //
  8234. // Dynamically generated format strings are difficult to
  8235. // automatically vet at compile time. Requiring that format strings
  8236. // are string literals: (1) permits the checking of format strings by
  8237. // the compiler and thereby (2) can practically remove the source of
  8238. // many format string exploits.
  8239. // Format string can be either ObjC string (e.g. @"%d") or
  8240. // C string (e.g. "%d")
  8241. // ObjC string uses the same format specifiers as C string, so we can use
  8242. // the same format string checking logic for both ObjC and C strings.
  8243. UncoveredArgHandler UncoveredArg;
  8244. StringLiteralCheckType CT = checkFormatStringExpr(
  8245. *this, OrigFormatExpr, Args, APK, format_idx, firstDataArg, Type,
  8246. CallType,
  8247. /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
  8248. /*no string offset*/ llvm::APSInt(64, false) = 0);
  8249. // Generate a diagnostic where an uncovered argument is detected.
  8250. if (UncoveredArg.hasUncoveredArg()) {
  8251. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  8252. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  8253. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  8254. }
  8255. if (CT != SLCT_NotALiteral)
  8256. // Literal format string found, check done!
  8257. return CT == SLCT_CheckedLiteral;
  8258. // Strftime is particular as it always uses a single 'time' argument,
  8259. // so it is safe to pass a non-literal string.
  8260. if (Type == FST_Strftime)
  8261. return false;
  8262. // Do not emit diag when the string param is a macro expansion and the
  8263. // format is either NSString or CFString. This is a hack to prevent
  8264. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  8265. // which are usually used in place of NS and CF string literals.
  8266. SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
  8267. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  8268. return false;
  8269. // If there are no arguments specified, warn with -Wformat-security, otherwise
  8270. // warn only with -Wformat-nonliteral.
  8271. if (Args.size() == firstDataArg) {
  8272. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  8273. << OrigFormatExpr->getSourceRange();
  8274. switch (Type) {
  8275. default:
  8276. break;
  8277. case FST_Kprintf:
  8278. case FST_FreeBSDKPrintf:
  8279. case FST_Printf:
  8280. Diag(FormatLoc, diag::note_format_security_fixit)
  8281. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  8282. break;
  8283. case FST_NSString:
  8284. Diag(FormatLoc, diag::note_format_security_fixit)
  8285. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  8286. break;
  8287. }
  8288. } else {
  8289. Diag(FormatLoc, diag::warn_format_nonliteral)
  8290. << OrigFormatExpr->getSourceRange();
  8291. }
  8292. return false;
  8293. }
  8294. namespace {
  8295. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  8296. protected:
  8297. Sema &S;
  8298. const FormatStringLiteral *FExpr;
  8299. const Expr *OrigFormatExpr;
  8300. const Sema::FormatStringType FSType;
  8301. const unsigned FirstDataArg;
  8302. const unsigned NumDataArgs;
  8303. const char *Beg; // Start of format string.
  8304. const Sema::FormatArgumentPassingKind ArgPassingKind;
  8305. ArrayRef<const Expr *> Args;
  8306. unsigned FormatIdx;
  8307. llvm::SmallBitVector CoveredArgs;
  8308. bool usesPositionalArgs = false;
  8309. bool atFirstArg = true;
  8310. bool inFunctionCall;
  8311. Sema::VariadicCallType CallType;
  8312. llvm::SmallBitVector &CheckedVarArgs;
  8313. UncoveredArgHandler &UncoveredArg;
  8314. public:
  8315. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  8316. const Expr *origFormatExpr,
  8317. const Sema::FormatStringType type, unsigned firstDataArg,
  8318. unsigned numDataArgs, const char *beg,
  8319. Sema::FormatArgumentPassingKind APK,
  8320. ArrayRef<const Expr *> Args, unsigned formatIdx,
  8321. bool inFunctionCall, Sema::VariadicCallType callType,
  8322. llvm::SmallBitVector &CheckedVarArgs,
  8323. UncoveredArgHandler &UncoveredArg)
  8324. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  8325. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  8326. ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
  8327. inFunctionCall(inFunctionCall), CallType(callType),
  8328. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  8329. CoveredArgs.resize(numDataArgs);
  8330. CoveredArgs.reset();
  8331. }
  8332. void DoneProcessing();
  8333. void HandleIncompleteSpecifier(const char *startSpecifier,
  8334. unsigned specifierLen) override;
  8335. void HandleInvalidLengthModifier(
  8336. const analyze_format_string::FormatSpecifier &FS,
  8337. const analyze_format_string::ConversionSpecifier &CS,
  8338. const char *startSpecifier, unsigned specifierLen,
  8339. unsigned DiagID);
  8340. void HandleNonStandardLengthModifier(
  8341. const analyze_format_string::FormatSpecifier &FS,
  8342. const char *startSpecifier, unsigned specifierLen);
  8343. void HandleNonStandardConversionSpecifier(
  8344. const analyze_format_string::ConversionSpecifier &CS,
  8345. const char *startSpecifier, unsigned specifierLen);
  8346. void HandlePosition(const char *startPos, unsigned posLen) override;
  8347. void HandleInvalidPosition(const char *startSpecifier,
  8348. unsigned specifierLen,
  8349. analyze_format_string::PositionContext p) override;
  8350. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  8351. void HandleNullChar(const char *nullCharacter) override;
  8352. template <typename Range>
  8353. static void
  8354. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  8355. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  8356. bool IsStringLocation, Range StringRange,
  8357. ArrayRef<FixItHint> Fixit = std::nullopt);
  8358. protected:
  8359. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  8360. const char *startSpec,
  8361. unsigned specifierLen,
  8362. const char *csStart, unsigned csLen);
  8363. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  8364. const char *startSpec,
  8365. unsigned specifierLen);
  8366. SourceRange getFormatStringRange();
  8367. CharSourceRange getSpecifierRange(const char *startSpecifier,
  8368. unsigned specifierLen);
  8369. SourceLocation getLocationOfByte(const char *x);
  8370. const Expr *getDataArg(unsigned i) const;
  8371. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  8372. const analyze_format_string::ConversionSpecifier &CS,
  8373. const char *startSpecifier, unsigned specifierLen,
  8374. unsigned argIndex);
  8375. template <typename Range>
  8376. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  8377. bool IsStringLocation, Range StringRange,
  8378. ArrayRef<FixItHint> Fixit = std::nullopt);
  8379. };
  8380. } // namespace
  8381. SourceRange CheckFormatHandler::getFormatStringRange() {
  8382. return OrigFormatExpr->getSourceRange();
  8383. }
  8384. CharSourceRange CheckFormatHandler::
  8385. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  8386. SourceLocation Start = getLocationOfByte(startSpecifier);
  8387. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  8388. // Advance the end SourceLocation by one due to half-open ranges.
  8389. End = End.getLocWithOffset(1);
  8390. return CharSourceRange::getCharRange(Start, End);
  8391. }
  8392. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  8393. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  8394. S.getLangOpts(), S.Context.getTargetInfo());
  8395. }
  8396. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  8397. unsigned specifierLen){
  8398. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  8399. getLocationOfByte(startSpecifier),
  8400. /*IsStringLocation*/true,
  8401. getSpecifierRange(startSpecifier, specifierLen));
  8402. }
  8403. void CheckFormatHandler::HandleInvalidLengthModifier(
  8404. const analyze_format_string::FormatSpecifier &FS,
  8405. const analyze_format_string::ConversionSpecifier &CS,
  8406. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  8407. using namespace analyze_format_string;
  8408. const LengthModifier &LM = FS.getLengthModifier();
  8409. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  8410. // See if we know how to fix this length modifier.
  8411. std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  8412. if (FixedLM) {
  8413. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  8414. getLocationOfByte(LM.getStart()),
  8415. /*IsStringLocation*/true,
  8416. getSpecifierRange(startSpecifier, specifierLen));
  8417. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  8418. << FixedLM->toString()
  8419. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  8420. } else {
  8421. FixItHint Hint;
  8422. if (DiagID == diag::warn_format_nonsensical_length)
  8423. Hint = FixItHint::CreateRemoval(LMRange);
  8424. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  8425. getLocationOfByte(LM.getStart()),
  8426. /*IsStringLocation*/true,
  8427. getSpecifierRange(startSpecifier, specifierLen),
  8428. Hint);
  8429. }
  8430. }
  8431. void CheckFormatHandler::HandleNonStandardLengthModifier(
  8432. const analyze_format_string::FormatSpecifier &FS,
  8433. const char *startSpecifier, unsigned specifierLen) {
  8434. using namespace analyze_format_string;
  8435. const LengthModifier &LM = FS.getLengthModifier();
  8436. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  8437. // See if we know how to fix this length modifier.
  8438. std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  8439. if (FixedLM) {
  8440. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  8441. << LM.toString() << 0,
  8442. getLocationOfByte(LM.getStart()),
  8443. /*IsStringLocation*/true,
  8444. getSpecifierRange(startSpecifier, specifierLen));
  8445. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  8446. << FixedLM->toString()
  8447. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  8448. } else {
  8449. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  8450. << LM.toString() << 0,
  8451. getLocationOfByte(LM.getStart()),
  8452. /*IsStringLocation*/true,
  8453. getSpecifierRange(startSpecifier, specifierLen));
  8454. }
  8455. }
  8456. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  8457. const analyze_format_string::ConversionSpecifier &CS,
  8458. const char *startSpecifier, unsigned specifierLen) {
  8459. using namespace analyze_format_string;
  8460. // See if we know how to fix this conversion specifier.
  8461. std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  8462. if (FixedCS) {
  8463. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  8464. << CS.toString() << /*conversion specifier*/1,
  8465. getLocationOfByte(CS.getStart()),
  8466. /*IsStringLocation*/true,
  8467. getSpecifierRange(startSpecifier, specifierLen));
  8468. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  8469. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  8470. << FixedCS->toString()
  8471. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  8472. } else {
  8473. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  8474. << CS.toString() << /*conversion specifier*/1,
  8475. getLocationOfByte(CS.getStart()),
  8476. /*IsStringLocation*/true,
  8477. getSpecifierRange(startSpecifier, specifierLen));
  8478. }
  8479. }
  8480. void CheckFormatHandler::HandlePosition(const char *startPos,
  8481. unsigned posLen) {
  8482. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  8483. getLocationOfByte(startPos),
  8484. /*IsStringLocation*/true,
  8485. getSpecifierRange(startPos, posLen));
  8486. }
  8487. void
  8488. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  8489. analyze_format_string::PositionContext p) {
  8490. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  8491. << (unsigned) p,
  8492. getLocationOfByte(startPos), /*IsStringLocation*/true,
  8493. getSpecifierRange(startPos, posLen));
  8494. }
  8495. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  8496. unsigned posLen) {
  8497. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  8498. getLocationOfByte(startPos),
  8499. /*IsStringLocation*/true,
  8500. getSpecifierRange(startPos, posLen));
  8501. }
  8502. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  8503. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  8504. // The presence of a null character is likely an error.
  8505. EmitFormatDiagnostic(
  8506. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  8507. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  8508. getFormatStringRange());
  8509. }
  8510. }
  8511. // Note that this may return NULL if there was an error parsing or building
  8512. // one of the argument expressions.
  8513. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  8514. return Args[FirstDataArg + i];
  8515. }
  8516. void CheckFormatHandler::DoneProcessing() {
  8517. // Does the number of data arguments exceed the number of
  8518. // format conversions in the format string?
  8519. if (ArgPassingKind != Sema::FAPK_VAList) {
  8520. // Find any arguments that weren't covered.
  8521. CoveredArgs.flip();
  8522. signed notCoveredArg = CoveredArgs.find_first();
  8523. if (notCoveredArg >= 0) {
  8524. assert((unsigned)notCoveredArg < NumDataArgs);
  8525. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  8526. } else {
  8527. UncoveredArg.setAllCovered();
  8528. }
  8529. }
  8530. }
  8531. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  8532. const Expr *ArgExpr) {
  8533. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  8534. "Invalid state");
  8535. if (!ArgExpr)
  8536. return;
  8537. SourceLocation Loc = ArgExpr->getBeginLoc();
  8538. if (S.getSourceManager().isInSystemMacro(Loc))
  8539. return;
  8540. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  8541. for (auto E : DiagnosticExprs)
  8542. PDiag << E->getSourceRange();
  8543. CheckFormatHandler::EmitFormatDiagnostic(
  8544. S, IsFunctionCall, DiagnosticExprs[0],
  8545. PDiag, Loc, /*IsStringLocation*/false,
  8546. DiagnosticExprs[0]->getSourceRange());
  8547. }
  8548. bool
  8549. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  8550. SourceLocation Loc,
  8551. const char *startSpec,
  8552. unsigned specifierLen,
  8553. const char *csStart,
  8554. unsigned csLen) {
  8555. bool keepGoing = true;
  8556. if (argIndex < NumDataArgs) {
  8557. // Consider the argument coverered, even though the specifier doesn't
  8558. // make sense.
  8559. CoveredArgs.set(argIndex);
  8560. }
  8561. else {
  8562. // If argIndex exceeds the number of data arguments we
  8563. // don't issue a warning because that is just a cascade of warnings (and
  8564. // they may have intended '%%' anyway). We don't want to continue processing
  8565. // the format string after this point, however, as we will like just get
  8566. // gibberish when trying to match arguments.
  8567. keepGoing = false;
  8568. }
  8569. StringRef Specifier(csStart, csLen);
  8570. // If the specifier in non-printable, it could be the first byte of a UTF-8
  8571. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  8572. // hex value.
  8573. std::string CodePointStr;
  8574. if (!llvm::sys::locale::isPrint(*csStart)) {
  8575. llvm::UTF32 CodePoint;
  8576. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  8577. const llvm::UTF8 *E =
  8578. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  8579. llvm::ConversionResult Result =
  8580. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  8581. if (Result != llvm::conversionOK) {
  8582. unsigned char FirstChar = *csStart;
  8583. CodePoint = (llvm::UTF32)FirstChar;
  8584. }
  8585. llvm::raw_string_ostream OS(CodePointStr);
  8586. if (CodePoint < 256)
  8587. OS << "\\x" << llvm::format("%02x", CodePoint);
  8588. else if (CodePoint <= 0xFFFF)
  8589. OS << "\\u" << llvm::format("%04x", CodePoint);
  8590. else
  8591. OS << "\\U" << llvm::format("%08x", CodePoint);
  8592. OS.flush();
  8593. Specifier = CodePointStr;
  8594. }
  8595. EmitFormatDiagnostic(
  8596. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  8597. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  8598. return keepGoing;
  8599. }
  8600. void
  8601. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  8602. const char *startSpec,
  8603. unsigned specifierLen) {
  8604. EmitFormatDiagnostic(
  8605. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  8606. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  8607. }
  8608. bool
  8609. CheckFormatHandler::CheckNumArgs(
  8610. const analyze_format_string::FormatSpecifier &FS,
  8611. const analyze_format_string::ConversionSpecifier &CS,
  8612. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  8613. if (argIndex >= NumDataArgs) {
  8614. PartialDiagnostic PDiag = FS.usesPositionalArg()
  8615. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  8616. << (argIndex+1) << NumDataArgs)
  8617. : S.PDiag(diag::warn_printf_insufficient_data_args);
  8618. EmitFormatDiagnostic(
  8619. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  8620. getSpecifierRange(startSpecifier, specifierLen));
  8621. // Since more arguments than conversion tokens are given, by extension
  8622. // all arguments are covered, so mark this as so.
  8623. UncoveredArg.setAllCovered();
  8624. return false;
  8625. }
  8626. return true;
  8627. }
  8628. template<typename Range>
  8629. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  8630. SourceLocation Loc,
  8631. bool IsStringLocation,
  8632. Range StringRange,
  8633. ArrayRef<FixItHint> FixIt) {
  8634. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  8635. Loc, IsStringLocation, StringRange, FixIt);
  8636. }
  8637. /// If the format string is not within the function call, emit a note
  8638. /// so that the function call and string are in diagnostic messages.
  8639. ///
  8640. /// \param InFunctionCall if true, the format string is within the function
  8641. /// call and only one diagnostic message will be produced. Otherwise, an
  8642. /// extra note will be emitted pointing to location of the format string.
  8643. ///
  8644. /// \param ArgumentExpr the expression that is passed as the format string
  8645. /// argument in the function call. Used for getting locations when two
  8646. /// diagnostics are emitted.
  8647. ///
  8648. /// \param PDiag the callee should already have provided any strings for the
  8649. /// diagnostic message. This function only adds locations and fixits
  8650. /// to diagnostics.
  8651. ///
  8652. /// \param Loc primary location for diagnostic. If two diagnostics are
  8653. /// required, one will be at Loc and a new SourceLocation will be created for
  8654. /// the other one.
  8655. ///
  8656. /// \param IsStringLocation if true, Loc points to the format string should be
  8657. /// used for the note. Otherwise, Loc points to the argument list and will
  8658. /// be used with PDiag.
  8659. ///
  8660. /// \param StringRange some or all of the string to highlight. This is
  8661. /// templated so it can accept either a CharSourceRange or a SourceRange.
  8662. ///
  8663. /// \param FixIt optional fix it hint for the format string.
  8664. template <typename Range>
  8665. void CheckFormatHandler::EmitFormatDiagnostic(
  8666. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  8667. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  8668. Range StringRange, ArrayRef<FixItHint> FixIt) {
  8669. if (InFunctionCall) {
  8670. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  8671. D << StringRange;
  8672. D << FixIt;
  8673. } else {
  8674. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  8675. << ArgumentExpr->getSourceRange();
  8676. const Sema::SemaDiagnosticBuilder &Note =
  8677. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  8678. diag::note_format_string_defined);
  8679. Note << StringRange;
  8680. Note << FixIt;
  8681. }
  8682. }
  8683. //===--- CHECK: Printf format string checking ------------------------------===//
  8684. namespace {
  8685. class CheckPrintfHandler : public CheckFormatHandler {
  8686. public:
  8687. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  8688. const Expr *origFormatExpr,
  8689. const Sema::FormatStringType type, unsigned firstDataArg,
  8690. unsigned numDataArgs, bool isObjC, const char *beg,
  8691. Sema::FormatArgumentPassingKind APK,
  8692. ArrayRef<const Expr *> Args, unsigned formatIdx,
  8693. bool inFunctionCall, Sema::VariadicCallType CallType,
  8694. llvm::SmallBitVector &CheckedVarArgs,
  8695. UncoveredArgHandler &UncoveredArg)
  8696. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  8697. numDataArgs, beg, APK, Args, formatIdx,
  8698. inFunctionCall, CallType, CheckedVarArgs,
  8699. UncoveredArg) {}
  8700. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  8701. /// Returns true if '%@' specifiers are allowed in the format string.
  8702. bool allowsObjCArg() const {
  8703. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  8704. FSType == Sema::FST_OSTrace;
  8705. }
  8706. bool HandleInvalidPrintfConversionSpecifier(
  8707. const analyze_printf::PrintfSpecifier &FS,
  8708. const char *startSpecifier,
  8709. unsigned specifierLen) override;
  8710. void handleInvalidMaskType(StringRef MaskType) override;
  8711. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  8712. const char *startSpecifier, unsigned specifierLen,
  8713. const TargetInfo &Target) override;
  8714. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  8715. const char *StartSpecifier,
  8716. unsigned SpecifierLen,
  8717. const Expr *E);
  8718. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  8719. const char *startSpecifier, unsigned specifierLen);
  8720. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  8721. const analyze_printf::OptionalAmount &Amt,
  8722. unsigned type,
  8723. const char *startSpecifier, unsigned specifierLen);
  8724. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  8725. const analyze_printf::OptionalFlag &flag,
  8726. const char *startSpecifier, unsigned specifierLen);
  8727. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  8728. const analyze_printf::OptionalFlag &ignoredFlag,
  8729. const analyze_printf::OptionalFlag &flag,
  8730. const char *startSpecifier, unsigned specifierLen);
  8731. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  8732. const Expr *E);
  8733. void HandleEmptyObjCModifierFlag(const char *startFlag,
  8734. unsigned flagLen) override;
  8735. void HandleInvalidObjCModifierFlag(const char *startFlag,
  8736. unsigned flagLen) override;
  8737. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  8738. const char *flagsEnd,
  8739. const char *conversionPosition)
  8740. override;
  8741. };
  8742. } // namespace
  8743. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  8744. const analyze_printf::PrintfSpecifier &FS,
  8745. const char *startSpecifier,
  8746. unsigned specifierLen) {
  8747. const analyze_printf::PrintfConversionSpecifier &CS =
  8748. FS.getConversionSpecifier();
  8749. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  8750. getLocationOfByte(CS.getStart()),
  8751. startSpecifier, specifierLen,
  8752. CS.getStart(), CS.getLength());
  8753. }
  8754. void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
  8755. S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
  8756. }
  8757. bool CheckPrintfHandler::HandleAmount(
  8758. const analyze_format_string::OptionalAmount &Amt, unsigned k,
  8759. const char *startSpecifier, unsigned specifierLen) {
  8760. if (Amt.hasDataArgument()) {
  8761. if (ArgPassingKind != Sema::FAPK_VAList) {
  8762. unsigned argIndex = Amt.getArgIndex();
  8763. if (argIndex >= NumDataArgs) {
  8764. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  8765. << k,
  8766. getLocationOfByte(Amt.getStart()),
  8767. /*IsStringLocation*/ true,
  8768. getSpecifierRange(startSpecifier, specifierLen));
  8769. // Don't do any more checking. We will just emit
  8770. // spurious errors.
  8771. return false;
  8772. }
  8773. // Type check the data argument. It should be an 'int'.
  8774. // Although not in conformance with C99, we also allow the argument to be
  8775. // an 'unsigned int' as that is a reasonably safe case. GCC also
  8776. // doesn't emit a warning for that case.
  8777. CoveredArgs.set(argIndex);
  8778. const Expr *Arg = getDataArg(argIndex);
  8779. if (!Arg)
  8780. return false;
  8781. QualType T = Arg->getType();
  8782. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  8783. assert(AT.isValid());
  8784. if (!AT.matchesType(S.Context, T)) {
  8785. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  8786. << k << AT.getRepresentativeTypeName(S.Context)
  8787. << T << Arg->getSourceRange(),
  8788. getLocationOfByte(Amt.getStart()),
  8789. /*IsStringLocation*/true,
  8790. getSpecifierRange(startSpecifier, specifierLen));
  8791. // Don't do any more checking. We will just emit
  8792. // spurious errors.
  8793. return false;
  8794. }
  8795. }
  8796. }
  8797. return true;
  8798. }
  8799. void CheckPrintfHandler::HandleInvalidAmount(
  8800. const analyze_printf::PrintfSpecifier &FS,
  8801. const analyze_printf::OptionalAmount &Amt,
  8802. unsigned type,
  8803. const char *startSpecifier,
  8804. unsigned specifierLen) {
  8805. const analyze_printf::PrintfConversionSpecifier &CS =
  8806. FS.getConversionSpecifier();
  8807. FixItHint fixit =
  8808. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  8809. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  8810. Amt.getConstantLength()))
  8811. : FixItHint();
  8812. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  8813. << type << CS.toString(),
  8814. getLocationOfByte(Amt.getStart()),
  8815. /*IsStringLocation*/true,
  8816. getSpecifierRange(startSpecifier, specifierLen),
  8817. fixit);
  8818. }
  8819. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  8820. const analyze_printf::OptionalFlag &flag,
  8821. const char *startSpecifier,
  8822. unsigned specifierLen) {
  8823. // Warn about pointless flag with a fixit removal.
  8824. const analyze_printf::PrintfConversionSpecifier &CS =
  8825. FS.getConversionSpecifier();
  8826. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  8827. << flag.toString() << CS.toString(),
  8828. getLocationOfByte(flag.getPosition()),
  8829. /*IsStringLocation*/true,
  8830. getSpecifierRange(startSpecifier, specifierLen),
  8831. FixItHint::CreateRemoval(
  8832. getSpecifierRange(flag.getPosition(), 1)));
  8833. }
  8834. void CheckPrintfHandler::HandleIgnoredFlag(
  8835. const analyze_printf::PrintfSpecifier &FS,
  8836. const analyze_printf::OptionalFlag &ignoredFlag,
  8837. const analyze_printf::OptionalFlag &flag,
  8838. const char *startSpecifier,
  8839. unsigned specifierLen) {
  8840. // Warn about ignored flag with a fixit removal.
  8841. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  8842. << ignoredFlag.toString() << flag.toString(),
  8843. getLocationOfByte(ignoredFlag.getPosition()),
  8844. /*IsStringLocation*/true,
  8845. getSpecifierRange(startSpecifier, specifierLen),
  8846. FixItHint::CreateRemoval(
  8847. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  8848. }
  8849. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  8850. unsigned flagLen) {
  8851. // Warn about an empty flag.
  8852. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  8853. getLocationOfByte(startFlag),
  8854. /*IsStringLocation*/true,
  8855. getSpecifierRange(startFlag, flagLen));
  8856. }
  8857. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  8858. unsigned flagLen) {
  8859. // Warn about an invalid flag.
  8860. auto Range = getSpecifierRange(startFlag, flagLen);
  8861. StringRef flag(startFlag, flagLen);
  8862. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  8863. getLocationOfByte(startFlag),
  8864. /*IsStringLocation*/true,
  8865. Range, FixItHint::CreateRemoval(Range));
  8866. }
  8867. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  8868. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  8869. // Warn about using '[...]' without a '@' conversion.
  8870. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  8871. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  8872. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  8873. getLocationOfByte(conversionPosition),
  8874. /*IsStringLocation*/true,
  8875. Range, FixItHint::CreateRemoval(Range));
  8876. }
  8877. // Determines if the specified is a C++ class or struct containing
  8878. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  8879. // "c_str()").
  8880. template<typename MemberKind>
  8881. static llvm::SmallPtrSet<MemberKind*, 1>
  8882. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  8883. const RecordType *RT = Ty->getAs<RecordType>();
  8884. llvm::SmallPtrSet<MemberKind*, 1> Results;
  8885. if (!RT)
  8886. return Results;
  8887. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  8888. if (!RD || !RD->getDefinition())
  8889. return Results;
  8890. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  8891. Sema::LookupMemberName);
  8892. R.suppressDiagnostics();
  8893. // We just need to include all members of the right kind turned up by the
  8894. // filter, at this point.
  8895. if (S.LookupQualifiedName(R, RT->getDecl()))
  8896. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  8897. NamedDecl *decl = (*I)->getUnderlyingDecl();
  8898. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  8899. Results.insert(FK);
  8900. }
  8901. return Results;
  8902. }
  8903. /// Check if we could call '.c_str()' on an object.
  8904. ///
  8905. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  8906. /// allow the call, or if it would be ambiguous).
  8907. bool Sema::hasCStrMethod(const Expr *E) {
  8908. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  8909. MethodSet Results =
  8910. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  8911. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  8912. MI != ME; ++MI)
  8913. if ((*MI)->getMinRequiredArguments() == 0)
  8914. return true;
  8915. return false;
  8916. }
  8917. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  8918. // better diagnostic if so. AT is assumed to be valid.
  8919. // Returns true when a c_str() conversion method is found.
  8920. bool CheckPrintfHandler::checkForCStrMembers(
  8921. const analyze_printf::ArgType &AT, const Expr *E) {
  8922. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  8923. MethodSet Results =
  8924. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  8925. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  8926. MI != ME; ++MI) {
  8927. const CXXMethodDecl *Method = *MI;
  8928. if (Method->getMinRequiredArguments() == 0 &&
  8929. AT.matchesType(S.Context, Method->getReturnType())) {
  8930. // FIXME: Suggest parens if the expression needs them.
  8931. SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
  8932. S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
  8933. << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  8934. return true;
  8935. }
  8936. }
  8937. return false;
  8938. }
  8939. bool CheckPrintfHandler::HandlePrintfSpecifier(
  8940. const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
  8941. unsigned specifierLen, const TargetInfo &Target) {
  8942. using namespace analyze_format_string;
  8943. using namespace analyze_printf;
  8944. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  8945. if (FS.consumesDataArgument()) {
  8946. if (atFirstArg) {
  8947. atFirstArg = false;
  8948. usesPositionalArgs = FS.usesPositionalArg();
  8949. }
  8950. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  8951. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  8952. startSpecifier, specifierLen);
  8953. return false;
  8954. }
  8955. }
  8956. // First check if the field width, precision, and conversion specifier
  8957. // have matching data arguments.
  8958. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  8959. startSpecifier, specifierLen)) {
  8960. return false;
  8961. }
  8962. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  8963. startSpecifier, specifierLen)) {
  8964. return false;
  8965. }
  8966. if (!CS.consumesDataArgument()) {
  8967. // FIXME: Technically specifying a precision or field width here
  8968. // makes no sense. Worth issuing a warning at some point.
  8969. return true;
  8970. }
  8971. // Consume the argument.
  8972. unsigned argIndex = FS.getArgIndex();
  8973. if (argIndex < NumDataArgs) {
  8974. // The check to see if the argIndex is valid will come later.
  8975. // We set the bit here because we may exit early from this
  8976. // function if we encounter some other error.
  8977. CoveredArgs.set(argIndex);
  8978. }
  8979. // FreeBSD kernel extensions.
  8980. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  8981. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  8982. // We need at least two arguments.
  8983. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  8984. return false;
  8985. // Claim the second argument.
  8986. CoveredArgs.set(argIndex + 1);
  8987. // Type check the first argument (int for %b, pointer for %D)
  8988. const Expr *Ex = getDataArg(argIndex);
  8989. const analyze_printf::ArgType &AT =
  8990. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  8991. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  8992. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  8993. EmitFormatDiagnostic(
  8994. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  8995. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  8996. << false << Ex->getSourceRange(),
  8997. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  8998. getSpecifierRange(startSpecifier, specifierLen));
  8999. // Type check the second argument (char * for both %b and %D)
  9000. Ex = getDataArg(argIndex + 1);
  9001. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  9002. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  9003. EmitFormatDiagnostic(
  9004. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  9005. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  9006. << false << Ex->getSourceRange(),
  9007. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  9008. getSpecifierRange(startSpecifier, specifierLen));
  9009. return true;
  9010. }
  9011. // Check for using an Objective-C specific conversion specifier
  9012. // in a non-ObjC literal.
  9013. if (!allowsObjCArg() && CS.isObjCArg()) {
  9014. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  9015. specifierLen);
  9016. }
  9017. // %P can only be used with os_log.
  9018. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  9019. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  9020. specifierLen);
  9021. }
  9022. // %n is not allowed with os_log.
  9023. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  9024. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  9025. getLocationOfByte(CS.getStart()),
  9026. /*IsStringLocation*/ false,
  9027. getSpecifierRange(startSpecifier, specifierLen));
  9028. return true;
  9029. }
  9030. // Only scalars are allowed for os_trace.
  9031. if (FSType == Sema::FST_OSTrace &&
  9032. (CS.getKind() == ConversionSpecifier::PArg ||
  9033. CS.getKind() == ConversionSpecifier::sArg ||
  9034. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  9035. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  9036. specifierLen);
  9037. }
  9038. // Check for use of public/private annotation outside of os_log().
  9039. if (FSType != Sema::FST_OSLog) {
  9040. if (FS.isPublic().isSet()) {
  9041. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  9042. << "public",
  9043. getLocationOfByte(FS.isPublic().getPosition()),
  9044. /*IsStringLocation*/ false,
  9045. getSpecifierRange(startSpecifier, specifierLen));
  9046. }
  9047. if (FS.isPrivate().isSet()) {
  9048. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  9049. << "private",
  9050. getLocationOfByte(FS.isPrivate().getPosition()),
  9051. /*IsStringLocation*/ false,
  9052. getSpecifierRange(startSpecifier, specifierLen));
  9053. }
  9054. }
  9055. const llvm::Triple &Triple = Target.getTriple();
  9056. if (CS.getKind() == ConversionSpecifier::nArg &&
  9057. (Triple.isAndroid() || Triple.isOSFuchsia())) {
  9058. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
  9059. getLocationOfByte(CS.getStart()),
  9060. /*IsStringLocation*/ false,
  9061. getSpecifierRange(startSpecifier, specifierLen));
  9062. }
  9063. // Check for invalid use of field width
  9064. if (!FS.hasValidFieldWidth()) {
  9065. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  9066. startSpecifier, specifierLen);
  9067. }
  9068. // Check for invalid use of precision
  9069. if (!FS.hasValidPrecision()) {
  9070. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  9071. startSpecifier, specifierLen);
  9072. }
  9073. // Precision is mandatory for %P specifier.
  9074. if (CS.getKind() == ConversionSpecifier::PArg &&
  9075. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  9076. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  9077. getLocationOfByte(startSpecifier),
  9078. /*IsStringLocation*/ false,
  9079. getSpecifierRange(startSpecifier, specifierLen));
  9080. }
  9081. // Check each flag does not conflict with any other component.
  9082. if (!FS.hasValidThousandsGroupingPrefix())
  9083. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  9084. if (!FS.hasValidLeadingZeros())
  9085. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  9086. if (!FS.hasValidPlusPrefix())
  9087. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  9088. if (!FS.hasValidSpacePrefix())
  9089. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  9090. if (!FS.hasValidAlternativeForm())
  9091. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  9092. if (!FS.hasValidLeftJustified())
  9093. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  9094. // Check that flags are not ignored by another flag
  9095. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  9096. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  9097. startSpecifier, specifierLen);
  9098. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  9099. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  9100. startSpecifier, specifierLen);
  9101. // Check the length modifier is valid with the given conversion specifier.
  9102. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  9103. S.getLangOpts()))
  9104. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  9105. diag::warn_format_nonsensical_length);
  9106. else if (!FS.hasStandardLengthModifier())
  9107. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  9108. else if (!FS.hasStandardLengthConversionCombination())
  9109. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  9110. diag::warn_format_non_standard_conversion_spec);
  9111. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  9112. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  9113. // The remaining checks depend on the data arguments.
  9114. if (ArgPassingKind == Sema::FAPK_VAList)
  9115. return true;
  9116. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  9117. return false;
  9118. const Expr *Arg = getDataArg(argIndex);
  9119. if (!Arg)
  9120. return true;
  9121. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  9122. }
  9123. static bool requiresParensToAddCast(const Expr *E) {
  9124. // FIXME: We should have a general way to reason about operator
  9125. // precedence and whether parens are actually needed here.
  9126. // Take care of a few common cases where they aren't.
  9127. const Expr *Inside = E->IgnoreImpCasts();
  9128. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  9129. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  9130. switch (Inside->getStmtClass()) {
  9131. case Stmt::ArraySubscriptExprClass:
  9132. case Stmt::CallExprClass:
  9133. case Stmt::CharacterLiteralClass:
  9134. case Stmt::CXXBoolLiteralExprClass:
  9135. case Stmt::DeclRefExprClass:
  9136. case Stmt::FloatingLiteralClass:
  9137. case Stmt::IntegerLiteralClass:
  9138. case Stmt::MemberExprClass:
  9139. case Stmt::ObjCArrayLiteralClass:
  9140. case Stmt::ObjCBoolLiteralExprClass:
  9141. case Stmt::ObjCBoxedExprClass:
  9142. case Stmt::ObjCDictionaryLiteralClass:
  9143. case Stmt::ObjCEncodeExprClass:
  9144. case Stmt::ObjCIvarRefExprClass:
  9145. case Stmt::ObjCMessageExprClass:
  9146. case Stmt::ObjCPropertyRefExprClass:
  9147. case Stmt::ObjCStringLiteralClass:
  9148. case Stmt::ObjCSubscriptRefExprClass:
  9149. case Stmt::ParenExprClass:
  9150. case Stmt::StringLiteralClass:
  9151. case Stmt::UnaryOperatorClass:
  9152. return false;
  9153. default:
  9154. return true;
  9155. }
  9156. }
  9157. static std::pair<QualType, StringRef>
  9158. shouldNotPrintDirectly(const ASTContext &Context,
  9159. QualType IntendedTy,
  9160. const Expr *E) {
  9161. // Use a 'while' to peel off layers of typedefs.
  9162. QualType TyTy = IntendedTy;
  9163. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  9164. StringRef Name = UserTy->getDecl()->getName();
  9165. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  9166. .Case("CFIndex", Context.getNSIntegerType())
  9167. .Case("NSInteger", Context.getNSIntegerType())
  9168. .Case("NSUInteger", Context.getNSUIntegerType())
  9169. .Case("SInt32", Context.IntTy)
  9170. .Case("UInt32", Context.UnsignedIntTy)
  9171. .Default(QualType());
  9172. if (!CastTy.isNull())
  9173. return std::make_pair(CastTy, Name);
  9174. TyTy = UserTy->desugar();
  9175. }
  9176. // Strip parens if necessary.
  9177. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  9178. return shouldNotPrintDirectly(Context,
  9179. PE->getSubExpr()->getType(),
  9180. PE->getSubExpr());
  9181. // If this is a conditional expression, then its result type is constructed
  9182. // via usual arithmetic conversions and thus there might be no necessary
  9183. // typedef sugar there. Recurse to operands to check for NSInteger &
  9184. // Co. usage condition.
  9185. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  9186. QualType TrueTy, FalseTy;
  9187. StringRef TrueName, FalseName;
  9188. std::tie(TrueTy, TrueName) =
  9189. shouldNotPrintDirectly(Context,
  9190. CO->getTrueExpr()->getType(),
  9191. CO->getTrueExpr());
  9192. std::tie(FalseTy, FalseName) =
  9193. shouldNotPrintDirectly(Context,
  9194. CO->getFalseExpr()->getType(),
  9195. CO->getFalseExpr());
  9196. if (TrueTy == FalseTy)
  9197. return std::make_pair(TrueTy, TrueName);
  9198. else if (TrueTy.isNull())
  9199. return std::make_pair(FalseTy, FalseName);
  9200. else if (FalseTy.isNull())
  9201. return std::make_pair(TrueTy, TrueName);
  9202. }
  9203. return std::make_pair(QualType(), StringRef());
  9204. }
  9205. /// Return true if \p ICE is an implicit argument promotion of an arithmetic
  9206. /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
  9207. /// type do not count.
  9208. static bool
  9209. isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
  9210. QualType From = ICE->getSubExpr()->getType();
  9211. QualType To = ICE->getType();
  9212. // It's an integer promotion if the destination type is the promoted
  9213. // source type.
  9214. if (ICE->getCastKind() == CK_IntegralCast &&
  9215. S.Context.isPromotableIntegerType(From) &&
  9216. S.Context.getPromotedIntegerType(From) == To)
  9217. return true;
  9218. // Look through vector types, since we do default argument promotion for
  9219. // those in OpenCL.
  9220. if (const auto *VecTy = From->getAs<ExtVectorType>())
  9221. From = VecTy->getElementType();
  9222. if (const auto *VecTy = To->getAs<ExtVectorType>())
  9223. To = VecTy->getElementType();
  9224. // It's a floating promotion if the source type is a lower rank.
  9225. return ICE->getCastKind() == CK_FloatingCast &&
  9226. S.Context.getFloatingTypeOrder(From, To) < 0;
  9227. }
  9228. bool
  9229. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  9230. const char *StartSpecifier,
  9231. unsigned SpecifierLen,
  9232. const Expr *E) {
  9233. using namespace analyze_format_string;
  9234. using namespace analyze_printf;
  9235. // Now type check the data expression that matches the
  9236. // format specifier.
  9237. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  9238. if (!AT.isValid())
  9239. return true;
  9240. QualType ExprTy = E->getType();
  9241. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  9242. ExprTy = TET->getUnderlyingExpr()->getType();
  9243. }
  9244. // When using the format attribute in C++, you can receive a function or an
  9245. // array that will necessarily decay to a pointer when passed to the final
  9246. // format consumer. Apply decay before type comparison.
  9247. if (ExprTy->canDecayToPointerType())
  9248. ExprTy = S.Context.getDecayedType(ExprTy);
  9249. // Diagnose attempts to print a boolean value as a character. Unlike other
  9250. // -Wformat diagnostics, this is fine from a type perspective, but it still
  9251. // doesn't make sense.
  9252. if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
  9253. E->isKnownToHaveBooleanValue()) {
  9254. const CharSourceRange &CSR =
  9255. getSpecifierRange(StartSpecifier, SpecifierLen);
  9256. SmallString<4> FSString;
  9257. llvm::raw_svector_ostream os(FSString);
  9258. FS.toString(os);
  9259. EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
  9260. << FSString,
  9261. E->getExprLoc(), false, CSR);
  9262. return true;
  9263. }
  9264. ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
  9265. ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
  9266. if (Match == ArgType::Match)
  9267. return true;
  9268. // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
  9269. assert(Match != ArgType::NoMatchPromotionTypeConfusion);
  9270. // Look through argument promotions for our error message's reported type.
  9271. // This includes the integral and floating promotions, but excludes array
  9272. // and function pointer decay (seeing that an argument intended to be a
  9273. // string has type 'char [6]' is probably more confusing than 'char *') and
  9274. // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
  9275. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  9276. if (isArithmeticArgumentPromotion(S, ICE)) {
  9277. E = ICE->getSubExpr();
  9278. ExprTy = E->getType();
  9279. // Check if we didn't match because of an implicit cast from a 'char'
  9280. // or 'short' to an 'int'. This is done because printf is a varargs
  9281. // function.
  9282. if (ICE->getType() == S.Context.IntTy ||
  9283. ICE->getType() == S.Context.UnsignedIntTy) {
  9284. // All further checking is done on the subexpression
  9285. ImplicitMatch = AT.matchesType(S.Context, ExprTy);
  9286. if (ImplicitMatch == ArgType::Match)
  9287. return true;
  9288. }
  9289. }
  9290. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  9291. // Special case for 'a', which has type 'int' in C.
  9292. // Note, however, that we do /not/ want to treat multibyte constants like
  9293. // 'MooV' as characters! This form is deprecated but still exists. In
  9294. // addition, don't treat expressions as of type 'char' if one byte length
  9295. // modifier is provided.
  9296. if (ExprTy == S.Context.IntTy &&
  9297. FS.getLengthModifier().getKind() != LengthModifier::AsChar)
  9298. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
  9299. ExprTy = S.Context.CharTy;
  9300. // To improve check results, we consider a character literal in C
  9301. // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
  9302. // more likely a type confusion situation, so we will suggest to
  9303. // use '%hhd' instead by discarding the MatchPromotion.
  9304. if (Match == ArgType::MatchPromotion)
  9305. Match = ArgType::NoMatch;
  9306. }
  9307. }
  9308. if (Match == ArgType::MatchPromotion) {
  9309. // WG14 N2562 only clarified promotions in *printf
  9310. // For NSLog in ObjC, just preserve -Wformat behavior
  9311. if (!S.getLangOpts().ObjC &&
  9312. ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
  9313. ImplicitMatch != ArgType::NoMatchTypeConfusion)
  9314. return true;
  9315. Match = ArgType::NoMatch;
  9316. }
  9317. if (ImplicitMatch == ArgType::NoMatchPedantic ||
  9318. ImplicitMatch == ArgType::NoMatchTypeConfusion)
  9319. Match = ImplicitMatch;
  9320. assert(Match != ArgType::MatchPromotion);
  9321. // Look through enums to their underlying type.
  9322. bool IsEnum = false;
  9323. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  9324. ExprTy = EnumTy->getDecl()->getIntegerType();
  9325. IsEnum = true;
  9326. }
  9327. // %C in an Objective-C context prints a unichar, not a wchar_t.
  9328. // If the argument is an integer of some kind, believe the %C and suggest
  9329. // a cast instead of changing the conversion specifier.
  9330. QualType IntendedTy = ExprTy;
  9331. if (isObjCContext() &&
  9332. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  9333. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  9334. !ExprTy->isCharType()) {
  9335. // 'unichar' is defined as a typedef of unsigned short, but we should
  9336. // prefer using the typedef if it is visible.
  9337. IntendedTy = S.Context.UnsignedShortTy;
  9338. // While we are here, check if the value is an IntegerLiteral that happens
  9339. // to be within the valid range.
  9340. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  9341. const llvm::APInt &V = IL->getValue();
  9342. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  9343. return true;
  9344. }
  9345. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
  9346. Sema::LookupOrdinaryName);
  9347. if (S.LookupName(Result, S.getCurScope())) {
  9348. NamedDecl *ND = Result.getFoundDecl();
  9349. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  9350. if (TD->getUnderlyingType() == IntendedTy)
  9351. IntendedTy = S.Context.getTypedefType(TD);
  9352. }
  9353. }
  9354. }
  9355. // Special-case some of Darwin's platform-independence types by suggesting
  9356. // casts to primitive types that are known to be large enough.
  9357. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  9358. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  9359. QualType CastTy;
  9360. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  9361. if (!CastTy.isNull()) {
  9362. // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
  9363. // (long in ASTContext). Only complain to pedants.
  9364. if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
  9365. (AT.isSizeT() || AT.isPtrdiffT()) &&
  9366. AT.matchesType(S.Context, CastTy))
  9367. Match = ArgType::NoMatchPedantic;
  9368. IntendedTy = CastTy;
  9369. ShouldNotPrintDirectly = true;
  9370. }
  9371. }
  9372. // We may be able to offer a FixItHint if it is a supported type.
  9373. PrintfSpecifier fixedFS = FS;
  9374. bool Success =
  9375. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  9376. if (Success) {
  9377. // Get the fix string from the fixed format specifier
  9378. SmallString<16> buf;
  9379. llvm::raw_svector_ostream os(buf);
  9380. fixedFS.toString(os);
  9381. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  9382. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  9383. unsigned Diag;
  9384. switch (Match) {
  9385. case ArgType::Match:
  9386. case ArgType::MatchPromotion:
  9387. case ArgType::NoMatchPromotionTypeConfusion:
  9388. llvm_unreachable("expected non-matching");
  9389. case ArgType::NoMatchPedantic:
  9390. Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  9391. break;
  9392. case ArgType::NoMatchTypeConfusion:
  9393. Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
  9394. break;
  9395. case ArgType::NoMatch:
  9396. Diag = diag::warn_format_conversion_argument_type_mismatch;
  9397. break;
  9398. }
  9399. // In this case, the specifier is wrong and should be changed to match
  9400. // the argument.
  9401. EmitFormatDiagnostic(S.PDiag(Diag)
  9402. << AT.getRepresentativeTypeName(S.Context)
  9403. << IntendedTy << IsEnum << E->getSourceRange(),
  9404. E->getBeginLoc(),
  9405. /*IsStringLocation*/ false, SpecRange,
  9406. FixItHint::CreateReplacement(SpecRange, os.str()));
  9407. } else {
  9408. // The canonical type for formatting this value is different from the
  9409. // actual type of the expression. (This occurs, for example, with Darwin's
  9410. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  9411. // should be printed as 'long' for 64-bit compatibility.)
  9412. // Rather than emitting a normal format/argument mismatch, we want to
  9413. // add a cast to the recommended type (and correct the format string
  9414. // if necessary).
  9415. SmallString<16> CastBuf;
  9416. llvm::raw_svector_ostream CastFix(CastBuf);
  9417. CastFix << "(";
  9418. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  9419. CastFix << ")";
  9420. SmallVector<FixItHint,4> Hints;
  9421. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  9422. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  9423. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  9424. // If there's already a cast present, just replace it.
  9425. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  9426. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  9427. } else if (!requiresParensToAddCast(E)) {
  9428. // If the expression has high enough precedence,
  9429. // just write the C-style cast.
  9430. Hints.push_back(
  9431. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  9432. } else {
  9433. // Otherwise, add parens around the expression as well as the cast.
  9434. CastFix << "(";
  9435. Hints.push_back(
  9436. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  9437. SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
  9438. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  9439. }
  9440. if (ShouldNotPrintDirectly) {
  9441. // The expression has a type that should not be printed directly.
  9442. // We extract the name from the typedef because we don't want to show
  9443. // the underlying type in the diagnostic.
  9444. StringRef Name;
  9445. if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
  9446. Name = TypedefTy->getDecl()->getName();
  9447. else
  9448. Name = CastTyName;
  9449. unsigned Diag = Match == ArgType::NoMatchPedantic
  9450. ? diag::warn_format_argument_needs_cast_pedantic
  9451. : diag::warn_format_argument_needs_cast;
  9452. EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
  9453. << E->getSourceRange(),
  9454. E->getBeginLoc(), /*IsStringLocation=*/false,
  9455. SpecRange, Hints);
  9456. } else {
  9457. // In this case, the expression could be printed using a different
  9458. // specifier, but we've decided that the specifier is probably correct
  9459. // and we should cast instead. Just use the normal warning message.
  9460. EmitFormatDiagnostic(
  9461. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  9462. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  9463. << E->getSourceRange(),
  9464. E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
  9465. }
  9466. }
  9467. } else {
  9468. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  9469. SpecifierLen);
  9470. // Since the warning for passing non-POD types to variadic functions
  9471. // was deferred until now, we emit a warning for non-POD
  9472. // arguments here.
  9473. bool EmitTypeMismatch = false;
  9474. switch (S.isValidVarArgType(ExprTy)) {
  9475. case Sema::VAK_Valid:
  9476. case Sema::VAK_ValidInCXX11: {
  9477. unsigned Diag;
  9478. switch (Match) {
  9479. case ArgType::Match:
  9480. case ArgType::MatchPromotion:
  9481. case ArgType::NoMatchPromotionTypeConfusion:
  9482. llvm_unreachable("expected non-matching");
  9483. case ArgType::NoMatchPedantic:
  9484. Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  9485. break;
  9486. case ArgType::NoMatchTypeConfusion:
  9487. Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
  9488. break;
  9489. case ArgType::NoMatch:
  9490. Diag = diag::warn_format_conversion_argument_type_mismatch;
  9491. break;
  9492. }
  9493. EmitFormatDiagnostic(
  9494. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  9495. << IsEnum << CSR << E->getSourceRange(),
  9496. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  9497. break;
  9498. }
  9499. case Sema::VAK_Undefined:
  9500. case Sema::VAK_MSVCUndefined:
  9501. if (CallType == Sema::VariadicDoesNotApply) {
  9502. EmitTypeMismatch = true;
  9503. } else {
  9504. EmitFormatDiagnostic(
  9505. S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  9506. << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
  9507. << AT.getRepresentativeTypeName(S.Context) << CSR
  9508. << E->getSourceRange(),
  9509. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  9510. checkForCStrMembers(AT, E);
  9511. }
  9512. break;
  9513. case Sema::VAK_Invalid:
  9514. if (CallType == Sema::VariadicDoesNotApply)
  9515. EmitTypeMismatch = true;
  9516. else if (ExprTy->isObjCObjectType())
  9517. EmitFormatDiagnostic(
  9518. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  9519. << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
  9520. << AT.getRepresentativeTypeName(S.Context) << CSR
  9521. << E->getSourceRange(),
  9522. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  9523. else
  9524. // FIXME: If this is an initializer list, suggest removing the braces
  9525. // or inserting a cast to the target type.
  9526. S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
  9527. << isa<InitListExpr>(E) << ExprTy << CallType
  9528. << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
  9529. break;
  9530. }
  9531. if (EmitTypeMismatch) {
  9532. // The function is not variadic, so we do not generate warnings about
  9533. // being allowed to pass that object as a variadic argument. Instead,
  9534. // since there are inherently no printf specifiers for types which cannot
  9535. // be passed as variadic arguments, emit a plain old specifier mismatch
  9536. // argument.
  9537. EmitFormatDiagnostic(
  9538. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  9539. << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
  9540. << E->getSourceRange(),
  9541. E->getBeginLoc(), false, CSR);
  9542. }
  9543. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  9544. "format string specifier index out of range");
  9545. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  9546. }
  9547. return true;
  9548. }
  9549. //===--- CHECK: Scanf format string checking ------------------------------===//
  9550. namespace {
  9551. class CheckScanfHandler : public CheckFormatHandler {
  9552. public:
  9553. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  9554. const Expr *origFormatExpr, Sema::FormatStringType type,
  9555. unsigned firstDataArg, unsigned numDataArgs,
  9556. const char *beg, Sema::FormatArgumentPassingKind APK,
  9557. ArrayRef<const Expr *> Args, unsigned formatIdx,
  9558. bool inFunctionCall, Sema::VariadicCallType CallType,
  9559. llvm::SmallBitVector &CheckedVarArgs,
  9560. UncoveredArgHandler &UncoveredArg)
  9561. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  9562. numDataArgs, beg, APK, Args, formatIdx,
  9563. inFunctionCall, CallType, CheckedVarArgs,
  9564. UncoveredArg) {}
  9565. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  9566. const char *startSpecifier,
  9567. unsigned specifierLen) override;
  9568. bool HandleInvalidScanfConversionSpecifier(
  9569. const analyze_scanf::ScanfSpecifier &FS,
  9570. const char *startSpecifier,
  9571. unsigned specifierLen) override;
  9572. void HandleIncompleteScanList(const char *start, const char *end) override;
  9573. };
  9574. } // namespace
  9575. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  9576. const char *end) {
  9577. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  9578. getLocationOfByte(end), /*IsStringLocation*/true,
  9579. getSpecifierRange(start, end - start));
  9580. }
  9581. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  9582. const analyze_scanf::ScanfSpecifier &FS,
  9583. const char *startSpecifier,
  9584. unsigned specifierLen) {
  9585. const analyze_scanf::ScanfConversionSpecifier &CS =
  9586. FS.getConversionSpecifier();
  9587. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  9588. getLocationOfByte(CS.getStart()),
  9589. startSpecifier, specifierLen,
  9590. CS.getStart(), CS.getLength());
  9591. }
  9592. bool CheckScanfHandler::HandleScanfSpecifier(
  9593. const analyze_scanf::ScanfSpecifier &FS,
  9594. const char *startSpecifier,
  9595. unsigned specifierLen) {
  9596. using namespace analyze_scanf;
  9597. using namespace analyze_format_string;
  9598. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  9599. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  9600. // be used to decide if we are using positional arguments consistently.
  9601. if (FS.consumesDataArgument()) {
  9602. if (atFirstArg) {
  9603. atFirstArg = false;
  9604. usesPositionalArgs = FS.usesPositionalArg();
  9605. }
  9606. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  9607. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  9608. startSpecifier, specifierLen);
  9609. return false;
  9610. }
  9611. }
  9612. // Check if the field with is non-zero.
  9613. const OptionalAmount &Amt = FS.getFieldWidth();
  9614. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  9615. if (Amt.getConstantAmount() == 0) {
  9616. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  9617. Amt.getConstantLength());
  9618. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  9619. getLocationOfByte(Amt.getStart()),
  9620. /*IsStringLocation*/true, R,
  9621. FixItHint::CreateRemoval(R));
  9622. }
  9623. }
  9624. if (!FS.consumesDataArgument()) {
  9625. // FIXME: Technically specifying a precision or field width here
  9626. // makes no sense. Worth issuing a warning at some point.
  9627. return true;
  9628. }
  9629. // Consume the argument.
  9630. unsigned argIndex = FS.getArgIndex();
  9631. if (argIndex < NumDataArgs) {
  9632. // The check to see if the argIndex is valid will come later.
  9633. // We set the bit here because we may exit early from this
  9634. // function if we encounter some other error.
  9635. CoveredArgs.set(argIndex);
  9636. }
  9637. // Check the length modifier is valid with the given conversion specifier.
  9638. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  9639. S.getLangOpts()))
  9640. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  9641. diag::warn_format_nonsensical_length);
  9642. else if (!FS.hasStandardLengthModifier())
  9643. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  9644. else if (!FS.hasStandardLengthConversionCombination())
  9645. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  9646. diag::warn_format_non_standard_conversion_spec);
  9647. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  9648. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  9649. // The remaining checks depend on the data arguments.
  9650. if (ArgPassingKind == Sema::FAPK_VAList)
  9651. return true;
  9652. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  9653. return false;
  9654. // Check that the argument type matches the format specifier.
  9655. const Expr *Ex = getDataArg(argIndex);
  9656. if (!Ex)
  9657. return true;
  9658. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  9659. if (!AT.isValid()) {
  9660. return true;
  9661. }
  9662. analyze_format_string::ArgType::MatchKind Match =
  9663. AT.matchesType(S.Context, Ex->getType());
  9664. bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
  9665. if (Match == analyze_format_string::ArgType::Match)
  9666. return true;
  9667. ScanfSpecifier fixedFS = FS;
  9668. bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  9669. S.getLangOpts(), S.Context);
  9670. unsigned Diag =
  9671. Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  9672. : diag::warn_format_conversion_argument_type_mismatch;
  9673. if (Success) {
  9674. // Get the fix string from the fixed format specifier.
  9675. SmallString<128> buf;
  9676. llvm::raw_svector_ostream os(buf);
  9677. fixedFS.toString(os);
  9678. EmitFormatDiagnostic(
  9679. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
  9680. << Ex->getType() << false << Ex->getSourceRange(),
  9681. Ex->getBeginLoc(),
  9682. /*IsStringLocation*/ false,
  9683. getSpecifierRange(startSpecifier, specifierLen),
  9684. FixItHint::CreateReplacement(
  9685. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  9686. } else {
  9687. EmitFormatDiagnostic(S.PDiag(Diag)
  9688. << AT.getRepresentativeTypeName(S.Context)
  9689. << Ex->getType() << false << Ex->getSourceRange(),
  9690. Ex->getBeginLoc(),
  9691. /*IsStringLocation*/ false,
  9692. getSpecifierRange(startSpecifier, specifierLen));
  9693. }
  9694. return true;
  9695. }
  9696. static void CheckFormatString(
  9697. Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
  9698. ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
  9699. unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
  9700. bool inFunctionCall, Sema::VariadicCallType CallType,
  9701. llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
  9702. bool IgnoreStringsWithoutSpecifiers) {
  9703. // CHECK: is the format string a wide literal?
  9704. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  9705. CheckFormatHandler::EmitFormatDiagnostic(
  9706. S, inFunctionCall, Args[format_idx],
  9707. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
  9708. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  9709. return;
  9710. }
  9711. // Str - The format string. NOTE: this is NOT null-terminated!
  9712. StringRef StrRef = FExpr->getString();
  9713. const char *Str = StrRef.data();
  9714. // Account for cases where the string literal is truncated in a declaration.
  9715. const ConstantArrayType *T =
  9716. S.Context.getAsConstantArrayType(FExpr->getType());
  9717. assert(T && "String literal not of constant array type!");
  9718. size_t TypeSize = T->getSize().getZExtValue();
  9719. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  9720. const unsigned numDataArgs = Args.size() - firstDataArg;
  9721. if (IgnoreStringsWithoutSpecifiers &&
  9722. !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
  9723. Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
  9724. return;
  9725. // Emit a warning if the string literal is truncated and does not contain an
  9726. // embedded null character.
  9727. if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
  9728. CheckFormatHandler::EmitFormatDiagnostic(
  9729. S, inFunctionCall, Args[format_idx],
  9730. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  9731. FExpr->getBeginLoc(),
  9732. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  9733. return;
  9734. }
  9735. // CHECK: empty format string?
  9736. if (StrLen == 0 && numDataArgs > 0) {
  9737. CheckFormatHandler::EmitFormatDiagnostic(
  9738. S, inFunctionCall, Args[format_idx],
  9739. S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
  9740. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  9741. return;
  9742. }
  9743. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  9744. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  9745. Type == Sema::FST_OSTrace) {
  9746. CheckPrintfHandler H(
  9747. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  9748. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, APK,
  9749. Args, format_idx, inFunctionCall, CallType, CheckedVarArgs,
  9750. UncoveredArg);
  9751. if (!analyze_format_string::ParsePrintfString(
  9752. H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
  9753. Type == Sema::FST_FreeBSDKPrintf))
  9754. H.DoneProcessing();
  9755. } else if (Type == Sema::FST_Scanf) {
  9756. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  9757. numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
  9758. CallType, CheckedVarArgs, UncoveredArg);
  9759. if (!analyze_format_string::ParseScanfString(
  9760. H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
  9761. H.DoneProcessing();
  9762. } // TODO: handle other formats
  9763. }
  9764. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  9765. // Str - The format string. NOTE: this is NOT null-terminated!
  9766. StringRef StrRef = FExpr->getString();
  9767. const char *Str = StrRef.data();
  9768. // Account for cases where the string literal is truncated in a declaration.
  9769. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  9770. assert(T && "String literal not of constant array type!");
  9771. size_t TypeSize = T->getSize().getZExtValue();
  9772. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  9773. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  9774. getLangOpts(),
  9775. Context.getTargetInfo());
  9776. }
  9777. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  9778. // Returns the related absolute value function that is larger, of 0 if one
  9779. // does not exist.
  9780. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  9781. switch (AbsFunction) {
  9782. default:
  9783. return 0;
  9784. case Builtin::BI__builtin_abs:
  9785. return Builtin::BI__builtin_labs;
  9786. case Builtin::BI__builtin_labs:
  9787. return Builtin::BI__builtin_llabs;
  9788. case Builtin::BI__builtin_llabs:
  9789. return 0;
  9790. case Builtin::BI__builtin_fabsf:
  9791. return Builtin::BI__builtin_fabs;
  9792. case Builtin::BI__builtin_fabs:
  9793. return Builtin::BI__builtin_fabsl;
  9794. case Builtin::BI__builtin_fabsl:
  9795. return 0;
  9796. case Builtin::BI__builtin_cabsf:
  9797. return Builtin::BI__builtin_cabs;
  9798. case Builtin::BI__builtin_cabs:
  9799. return Builtin::BI__builtin_cabsl;
  9800. case Builtin::BI__builtin_cabsl:
  9801. return 0;
  9802. case Builtin::BIabs:
  9803. return Builtin::BIlabs;
  9804. case Builtin::BIlabs:
  9805. return Builtin::BIllabs;
  9806. case Builtin::BIllabs:
  9807. return 0;
  9808. case Builtin::BIfabsf:
  9809. return Builtin::BIfabs;
  9810. case Builtin::BIfabs:
  9811. return Builtin::BIfabsl;
  9812. case Builtin::BIfabsl:
  9813. return 0;
  9814. case Builtin::BIcabsf:
  9815. return Builtin::BIcabs;
  9816. case Builtin::BIcabs:
  9817. return Builtin::BIcabsl;
  9818. case Builtin::BIcabsl:
  9819. return 0;
  9820. }
  9821. }
  9822. // Returns the argument type of the absolute value function.
  9823. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  9824. unsigned AbsType) {
  9825. if (AbsType == 0)
  9826. return QualType();
  9827. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  9828. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  9829. if (Error != ASTContext::GE_None)
  9830. return QualType();
  9831. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  9832. if (!FT)
  9833. return QualType();
  9834. if (FT->getNumParams() != 1)
  9835. return QualType();
  9836. return FT->getParamType(0);
  9837. }
  9838. // Returns the best absolute value function, or zero, based on type and
  9839. // current absolute value function.
  9840. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  9841. unsigned AbsFunctionKind) {
  9842. unsigned BestKind = 0;
  9843. uint64_t ArgSize = Context.getTypeSize(ArgType);
  9844. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  9845. Kind = getLargerAbsoluteValueFunction(Kind)) {
  9846. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  9847. if (Context.getTypeSize(ParamType) >= ArgSize) {
  9848. if (BestKind == 0)
  9849. BestKind = Kind;
  9850. else if (Context.hasSameType(ParamType, ArgType)) {
  9851. BestKind = Kind;
  9852. break;
  9853. }
  9854. }
  9855. }
  9856. return BestKind;
  9857. }
  9858. enum AbsoluteValueKind {
  9859. AVK_Integer,
  9860. AVK_Floating,
  9861. AVK_Complex
  9862. };
  9863. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  9864. if (T->isIntegralOrEnumerationType())
  9865. return AVK_Integer;
  9866. if (T->isRealFloatingType())
  9867. return AVK_Floating;
  9868. if (T->isAnyComplexType())
  9869. return AVK_Complex;
  9870. llvm_unreachable("Type not integer, floating, or complex");
  9871. }
  9872. // Changes the absolute value function to a different type. Preserves whether
  9873. // the function is a builtin.
  9874. static unsigned changeAbsFunction(unsigned AbsKind,
  9875. AbsoluteValueKind ValueKind) {
  9876. switch (ValueKind) {
  9877. case AVK_Integer:
  9878. switch (AbsKind) {
  9879. default:
  9880. return 0;
  9881. case Builtin::BI__builtin_fabsf:
  9882. case Builtin::BI__builtin_fabs:
  9883. case Builtin::BI__builtin_fabsl:
  9884. case Builtin::BI__builtin_cabsf:
  9885. case Builtin::BI__builtin_cabs:
  9886. case Builtin::BI__builtin_cabsl:
  9887. return Builtin::BI__builtin_abs;
  9888. case Builtin::BIfabsf:
  9889. case Builtin::BIfabs:
  9890. case Builtin::BIfabsl:
  9891. case Builtin::BIcabsf:
  9892. case Builtin::BIcabs:
  9893. case Builtin::BIcabsl:
  9894. return Builtin::BIabs;
  9895. }
  9896. case AVK_Floating:
  9897. switch (AbsKind) {
  9898. default:
  9899. return 0;
  9900. case Builtin::BI__builtin_abs:
  9901. case Builtin::BI__builtin_labs:
  9902. case Builtin::BI__builtin_llabs:
  9903. case Builtin::BI__builtin_cabsf:
  9904. case Builtin::BI__builtin_cabs:
  9905. case Builtin::BI__builtin_cabsl:
  9906. return Builtin::BI__builtin_fabsf;
  9907. case Builtin::BIabs:
  9908. case Builtin::BIlabs:
  9909. case Builtin::BIllabs:
  9910. case Builtin::BIcabsf:
  9911. case Builtin::BIcabs:
  9912. case Builtin::BIcabsl:
  9913. return Builtin::BIfabsf;
  9914. }
  9915. case AVK_Complex:
  9916. switch (AbsKind) {
  9917. default:
  9918. return 0;
  9919. case Builtin::BI__builtin_abs:
  9920. case Builtin::BI__builtin_labs:
  9921. case Builtin::BI__builtin_llabs:
  9922. case Builtin::BI__builtin_fabsf:
  9923. case Builtin::BI__builtin_fabs:
  9924. case Builtin::BI__builtin_fabsl:
  9925. return Builtin::BI__builtin_cabsf;
  9926. case Builtin::BIabs:
  9927. case Builtin::BIlabs:
  9928. case Builtin::BIllabs:
  9929. case Builtin::BIfabsf:
  9930. case Builtin::BIfabs:
  9931. case Builtin::BIfabsl:
  9932. return Builtin::BIcabsf;
  9933. }
  9934. }
  9935. llvm_unreachable("Unable to convert function");
  9936. }
  9937. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  9938. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  9939. if (!FnInfo)
  9940. return 0;
  9941. switch (FDecl->getBuiltinID()) {
  9942. default:
  9943. return 0;
  9944. case Builtin::BI__builtin_abs:
  9945. case Builtin::BI__builtin_fabs:
  9946. case Builtin::BI__builtin_fabsf:
  9947. case Builtin::BI__builtin_fabsl:
  9948. case Builtin::BI__builtin_labs:
  9949. case Builtin::BI__builtin_llabs:
  9950. case Builtin::BI__builtin_cabs:
  9951. case Builtin::BI__builtin_cabsf:
  9952. case Builtin::BI__builtin_cabsl:
  9953. case Builtin::BIabs:
  9954. case Builtin::BIlabs:
  9955. case Builtin::BIllabs:
  9956. case Builtin::BIfabs:
  9957. case Builtin::BIfabsf:
  9958. case Builtin::BIfabsl:
  9959. case Builtin::BIcabs:
  9960. case Builtin::BIcabsf:
  9961. case Builtin::BIcabsl:
  9962. return FDecl->getBuiltinID();
  9963. }
  9964. llvm_unreachable("Unknown Builtin type");
  9965. }
  9966. // If the replacement is valid, emit a note with replacement function.
  9967. // Additionally, suggest including the proper header if not already included.
  9968. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  9969. unsigned AbsKind, QualType ArgType) {
  9970. bool EmitHeaderHint = true;
  9971. const char *HeaderName = nullptr;
  9972. StringRef FunctionName;
  9973. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  9974. FunctionName = "std::abs";
  9975. if (ArgType->isIntegralOrEnumerationType()) {
  9976. HeaderName = "cstdlib";
  9977. } else if (ArgType->isRealFloatingType()) {
  9978. HeaderName = "cmath";
  9979. } else {
  9980. llvm_unreachable("Invalid Type");
  9981. }
  9982. // Lookup all std::abs
  9983. if (NamespaceDecl *Std = S.getStdNamespace()) {
  9984. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  9985. R.suppressDiagnostics();
  9986. S.LookupQualifiedName(R, Std);
  9987. for (const auto *I : R) {
  9988. const FunctionDecl *FDecl = nullptr;
  9989. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  9990. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  9991. } else {
  9992. FDecl = dyn_cast<FunctionDecl>(I);
  9993. }
  9994. if (!FDecl)
  9995. continue;
  9996. // Found std::abs(), check that they are the right ones.
  9997. if (FDecl->getNumParams() != 1)
  9998. continue;
  9999. // Check that the parameter type can handle the argument.
  10000. QualType ParamType = FDecl->getParamDecl(0)->getType();
  10001. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  10002. S.Context.getTypeSize(ArgType) <=
  10003. S.Context.getTypeSize(ParamType)) {
  10004. // Found a function, don't need the header hint.
  10005. EmitHeaderHint = false;
  10006. break;
  10007. }
  10008. }
  10009. }
  10010. } else {
  10011. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  10012. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  10013. if (HeaderName) {
  10014. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  10015. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  10016. R.suppressDiagnostics();
  10017. S.LookupName(R, S.getCurScope());
  10018. if (R.isSingleResult()) {
  10019. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  10020. if (FD && FD->getBuiltinID() == AbsKind) {
  10021. EmitHeaderHint = false;
  10022. } else {
  10023. return;
  10024. }
  10025. } else if (!R.empty()) {
  10026. return;
  10027. }
  10028. }
  10029. }
  10030. S.Diag(Loc, diag::note_replace_abs_function)
  10031. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  10032. if (!HeaderName)
  10033. return;
  10034. if (!EmitHeaderHint)
  10035. return;
  10036. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  10037. << FunctionName;
  10038. }
  10039. template <std::size_t StrLen>
  10040. static bool IsStdFunction(const FunctionDecl *FDecl,
  10041. const char (&Str)[StrLen]) {
  10042. if (!FDecl)
  10043. return false;
  10044. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  10045. return false;
  10046. if (!FDecl->isInStdNamespace())
  10047. return false;
  10048. return true;
  10049. }
  10050. // Warn when using the wrong abs() function.
  10051. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  10052. const FunctionDecl *FDecl) {
  10053. if (Call->getNumArgs() != 1)
  10054. return;
  10055. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  10056. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  10057. if (AbsKind == 0 && !IsStdAbs)
  10058. return;
  10059. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  10060. QualType ParamType = Call->getArg(0)->getType();
  10061. // Unsigned types cannot be negative. Suggest removing the absolute value
  10062. // function call.
  10063. if (ArgType->isUnsignedIntegerType()) {
  10064. StringRef FunctionName =
  10065. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  10066. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  10067. Diag(Call->getExprLoc(), diag::note_remove_abs)
  10068. << FunctionName
  10069. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  10070. return;
  10071. }
  10072. // Taking the absolute value of a pointer is very suspicious, they probably
  10073. // wanted to index into an array, dereference a pointer, call a function, etc.
  10074. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  10075. unsigned DiagType = 0;
  10076. if (ArgType->isFunctionType())
  10077. DiagType = 1;
  10078. else if (ArgType->isArrayType())
  10079. DiagType = 2;
  10080. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  10081. return;
  10082. }
  10083. // std::abs has overloads which prevent most of the absolute value problems
  10084. // from occurring.
  10085. if (IsStdAbs)
  10086. return;
  10087. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  10088. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  10089. // The argument and parameter are the same kind. Check if they are the right
  10090. // size.
  10091. if (ArgValueKind == ParamValueKind) {
  10092. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  10093. return;
  10094. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  10095. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  10096. << FDecl << ArgType << ParamType;
  10097. if (NewAbsKind == 0)
  10098. return;
  10099. emitReplacement(*this, Call->getExprLoc(),
  10100. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  10101. return;
  10102. }
  10103. // ArgValueKind != ParamValueKind
  10104. // The wrong type of absolute value function was used. Attempt to find the
  10105. // proper one.
  10106. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  10107. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  10108. if (NewAbsKind == 0)
  10109. return;
  10110. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  10111. << FDecl << ParamValueKind << ArgValueKind;
  10112. emitReplacement(*this, Call->getExprLoc(),
  10113. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  10114. }
  10115. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  10116. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  10117. const FunctionDecl *FDecl) {
  10118. if (!Call || !FDecl) return;
  10119. // Ignore template specializations and macros.
  10120. if (inTemplateInstantiation()) return;
  10121. if (Call->getExprLoc().isMacroID()) return;
  10122. // Only care about the one template argument, two function parameter std::max
  10123. if (Call->getNumArgs() != 2) return;
  10124. if (!IsStdFunction(FDecl, "max")) return;
  10125. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  10126. if (!ArgList) return;
  10127. if (ArgList->size() != 1) return;
  10128. // Check that template type argument is unsigned integer.
  10129. const auto& TA = ArgList->get(0);
  10130. if (TA.getKind() != TemplateArgument::Type) return;
  10131. QualType ArgType = TA.getAsType();
  10132. if (!ArgType->isUnsignedIntegerType()) return;
  10133. // See if either argument is a literal zero.
  10134. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  10135. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  10136. if (!MTE) return false;
  10137. const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
  10138. if (!Num) return false;
  10139. if (Num->getValue() != 0) return false;
  10140. return true;
  10141. };
  10142. const Expr *FirstArg = Call->getArg(0);
  10143. const Expr *SecondArg = Call->getArg(1);
  10144. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  10145. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  10146. // Only warn when exactly one argument is zero.
  10147. if (IsFirstArgZero == IsSecondArgZero) return;
  10148. SourceRange FirstRange = FirstArg->getSourceRange();
  10149. SourceRange SecondRange = SecondArg->getSourceRange();
  10150. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  10151. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  10152. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  10153. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  10154. SourceRange RemovalRange;
  10155. if (IsFirstArgZero) {
  10156. RemovalRange = SourceRange(FirstRange.getBegin(),
  10157. SecondRange.getBegin().getLocWithOffset(-1));
  10158. } else {
  10159. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  10160. SecondRange.getEnd());
  10161. }
  10162. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  10163. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  10164. << FixItHint::CreateRemoval(RemovalRange);
  10165. }
  10166. //===--- CHECK: Standard memory functions ---------------------------------===//
  10167. /// Takes the expression passed to the size_t parameter of functions
  10168. /// such as memcmp, strncat, etc and warns if it's a comparison.
  10169. ///
  10170. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  10171. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  10172. IdentifierInfo *FnName,
  10173. SourceLocation FnLoc,
  10174. SourceLocation RParenLoc) {
  10175. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  10176. if (!Size)
  10177. return false;
  10178. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  10179. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  10180. return false;
  10181. SourceRange SizeRange = Size->getSourceRange();
  10182. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  10183. << SizeRange << FnName;
  10184. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  10185. << FnName
  10186. << FixItHint::CreateInsertion(
  10187. S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
  10188. << FixItHint::CreateRemoval(RParenLoc);
  10189. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  10190. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  10191. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  10192. ")");
  10193. return true;
  10194. }
  10195. /// Determine whether the given type is or contains a dynamic class type
  10196. /// (e.g., whether it has a vtable).
  10197. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  10198. bool &IsContained) {
  10199. // Look through array types while ignoring qualifiers.
  10200. const Type *Ty = T->getBaseElementTypeUnsafe();
  10201. IsContained = false;
  10202. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  10203. RD = RD ? RD->getDefinition() : nullptr;
  10204. if (!RD || RD->isInvalidDecl())
  10205. return nullptr;
  10206. if (RD->isDynamicClass())
  10207. return RD;
  10208. // Check all the fields. If any bases were dynamic, the class is dynamic.
  10209. // It's impossible for a class to transitively contain itself by value, so
  10210. // infinite recursion is impossible.
  10211. for (auto *FD : RD->fields()) {
  10212. bool SubContained;
  10213. if (const CXXRecordDecl *ContainedRD =
  10214. getContainedDynamicClass(FD->getType(), SubContained)) {
  10215. IsContained = true;
  10216. return ContainedRD;
  10217. }
  10218. }
  10219. return nullptr;
  10220. }
  10221. static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
  10222. if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  10223. if (Unary->getKind() == UETT_SizeOf)
  10224. return Unary;
  10225. return nullptr;
  10226. }
  10227. /// If E is a sizeof expression, returns its argument expression,
  10228. /// otherwise returns NULL.
  10229. static const Expr *getSizeOfExprArg(const Expr *E) {
  10230. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  10231. if (!SizeOf->isArgumentType())
  10232. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  10233. return nullptr;
  10234. }
  10235. /// If E is a sizeof expression, returns its argument type.
  10236. static QualType getSizeOfArgType(const Expr *E) {
  10237. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  10238. return SizeOf->getTypeOfArgument();
  10239. return QualType();
  10240. }
  10241. namespace {
  10242. struct SearchNonTrivialToInitializeField
  10243. : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
  10244. using Super =
  10245. DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
  10246. SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
  10247. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
  10248. SourceLocation SL) {
  10249. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  10250. asDerived().visitArray(PDIK, AT, SL);
  10251. return;
  10252. }
  10253. Super::visitWithKind(PDIK, FT, SL);
  10254. }
  10255. void visitARCStrong(QualType FT, SourceLocation SL) {
  10256. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  10257. }
  10258. void visitARCWeak(QualType FT, SourceLocation SL) {
  10259. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  10260. }
  10261. void visitStruct(QualType FT, SourceLocation SL) {
  10262. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  10263. visit(FD->getType(), FD->getLocation());
  10264. }
  10265. void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
  10266. const ArrayType *AT, SourceLocation SL) {
  10267. visit(getContext().getBaseElementType(AT), SL);
  10268. }
  10269. void visitTrivial(QualType FT, SourceLocation SL) {}
  10270. static void diag(QualType RT, const Expr *E, Sema &S) {
  10271. SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
  10272. }
  10273. ASTContext &getContext() { return S.getASTContext(); }
  10274. const Expr *E;
  10275. Sema &S;
  10276. };
  10277. struct SearchNonTrivialToCopyField
  10278. : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
  10279. using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
  10280. SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
  10281. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
  10282. SourceLocation SL) {
  10283. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  10284. asDerived().visitArray(PCK, AT, SL);
  10285. return;
  10286. }
  10287. Super::visitWithKind(PCK, FT, SL);
  10288. }
  10289. void visitARCStrong(QualType FT, SourceLocation SL) {
  10290. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  10291. }
  10292. void visitARCWeak(QualType FT, SourceLocation SL) {
  10293. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  10294. }
  10295. void visitStruct(QualType FT, SourceLocation SL) {
  10296. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  10297. visit(FD->getType(), FD->getLocation());
  10298. }
  10299. void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
  10300. SourceLocation SL) {
  10301. visit(getContext().getBaseElementType(AT), SL);
  10302. }
  10303. void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
  10304. SourceLocation SL) {}
  10305. void visitTrivial(QualType FT, SourceLocation SL) {}
  10306. void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
  10307. static void diag(QualType RT, const Expr *E, Sema &S) {
  10308. SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
  10309. }
  10310. ASTContext &getContext() { return S.getASTContext(); }
  10311. const Expr *E;
  10312. Sema &S;
  10313. };
  10314. }
  10315. /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
  10316. static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
  10317. SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
  10318. if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
  10319. if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
  10320. return false;
  10321. return doesExprLikelyComputeSize(BO->getLHS()) ||
  10322. doesExprLikelyComputeSize(BO->getRHS());
  10323. }
  10324. return getAsSizeOfExpr(SizeofExpr) != nullptr;
  10325. }
  10326. /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
  10327. ///
  10328. /// \code
  10329. /// #define MACRO 0
  10330. /// foo(MACRO);
  10331. /// foo(0);
  10332. /// \endcode
  10333. ///
  10334. /// This should return true for the first call to foo, but not for the second
  10335. /// (regardless of whether foo is a macro or function).
  10336. static bool isArgumentExpandedFromMacro(SourceManager &SM,
  10337. SourceLocation CallLoc,
  10338. SourceLocation ArgLoc) {
  10339. if (!CallLoc.isMacroID())
  10340. return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
  10341. return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
  10342. SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
  10343. }
  10344. /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
  10345. /// last two arguments transposed.
  10346. static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
  10347. if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
  10348. return;
  10349. const Expr *SizeArg =
  10350. Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
  10351. auto isLiteralZero = [](const Expr *E) {
  10352. return (isa<IntegerLiteral>(E) &&
  10353. cast<IntegerLiteral>(E)->getValue() == 0) ||
  10354. (isa<CharacterLiteral>(E) &&
  10355. cast<CharacterLiteral>(E)->getValue() == 0);
  10356. };
  10357. // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
  10358. SourceLocation CallLoc = Call->getRParenLoc();
  10359. SourceManager &SM = S.getSourceManager();
  10360. if (isLiteralZero(SizeArg) &&
  10361. !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
  10362. SourceLocation DiagLoc = SizeArg->getExprLoc();
  10363. // Some platforms #define bzero to __builtin_memset. See if this is the
  10364. // case, and if so, emit a better diagnostic.
  10365. if (BId == Builtin::BIbzero ||
  10366. (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
  10367. CallLoc, SM, S.getLangOpts()) == "bzero")) {
  10368. S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
  10369. S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
  10370. } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
  10371. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
  10372. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
  10373. }
  10374. return;
  10375. }
  10376. // If the second argument to a memset is a sizeof expression and the third
  10377. // isn't, this is also likely an error. This should catch
  10378. // 'memset(buf, sizeof(buf), 0xff)'.
  10379. if (BId == Builtin::BImemset &&
  10380. doesExprLikelyComputeSize(Call->getArg(1)) &&
  10381. !doesExprLikelyComputeSize(Call->getArg(2))) {
  10382. SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
  10383. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
  10384. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
  10385. return;
  10386. }
  10387. }
  10388. /// Check for dangerous or invalid arguments to memset().
  10389. ///
  10390. /// This issues warnings on known problematic, dangerous or unspecified
  10391. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  10392. /// function calls.
  10393. ///
  10394. /// \param Call The call expression to diagnose.
  10395. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  10396. unsigned BId,
  10397. IdentifierInfo *FnName) {
  10398. assert(BId != 0);
  10399. // It is possible to have a non-standard definition of memset. Validate
  10400. // we have enough arguments, and if not, abort further checking.
  10401. unsigned ExpectedNumArgs =
  10402. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  10403. if (Call->getNumArgs() < ExpectedNumArgs)
  10404. return;
  10405. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  10406. BId == Builtin::BIstrndup ? 1 : 2);
  10407. unsigned LenArg =
  10408. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  10409. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  10410. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  10411. Call->getBeginLoc(), Call->getRParenLoc()))
  10412. return;
  10413. // Catch cases like 'memset(buf, sizeof(buf), 0)'.
  10414. CheckMemaccessSize(*this, BId, Call);
  10415. // We have special checking when the length is a sizeof expression.
  10416. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  10417. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  10418. llvm::FoldingSetNodeID SizeOfArgID;
  10419. // Although widely used, 'bzero' is not a standard function. Be more strict
  10420. // with the argument types before allowing diagnostics and only allow the
  10421. // form bzero(ptr, sizeof(...)).
  10422. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  10423. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  10424. return;
  10425. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  10426. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  10427. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  10428. QualType DestTy = Dest->getType();
  10429. QualType PointeeTy;
  10430. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  10431. PointeeTy = DestPtrTy->getPointeeType();
  10432. // Never warn about void type pointers. This can be used to suppress
  10433. // false positives.
  10434. if (PointeeTy->isVoidType())
  10435. continue;
  10436. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  10437. // actually comparing the expressions for equality. Because computing the
  10438. // expression IDs can be expensive, we only do this if the diagnostic is
  10439. // enabled.
  10440. if (SizeOfArg &&
  10441. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  10442. SizeOfArg->getExprLoc())) {
  10443. // We only compute IDs for expressions if the warning is enabled, and
  10444. // cache the sizeof arg's ID.
  10445. if (SizeOfArgID == llvm::FoldingSetNodeID())
  10446. SizeOfArg->Profile(SizeOfArgID, Context, true);
  10447. llvm::FoldingSetNodeID DestID;
  10448. Dest->Profile(DestID, Context, true);
  10449. if (DestID == SizeOfArgID) {
  10450. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  10451. // over sizeof(src) as well.
  10452. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  10453. StringRef ReadableName = FnName->getName();
  10454. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  10455. if (UnaryOp->getOpcode() == UO_AddrOf)
  10456. ActionIdx = 1; // If its an address-of operator, just remove it.
  10457. if (!PointeeTy->isIncompleteType() &&
  10458. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  10459. ActionIdx = 2; // If the pointee's size is sizeof(char),
  10460. // suggest an explicit length.
  10461. // If the function is defined as a builtin macro, do not show macro
  10462. // expansion.
  10463. SourceLocation SL = SizeOfArg->getExprLoc();
  10464. SourceRange DSR = Dest->getSourceRange();
  10465. SourceRange SSR = SizeOfArg->getSourceRange();
  10466. SourceManager &SM = getSourceManager();
  10467. if (SM.isMacroArgExpansion(SL)) {
  10468. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  10469. SL = SM.getSpellingLoc(SL);
  10470. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  10471. SM.getSpellingLoc(DSR.getEnd()));
  10472. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  10473. SM.getSpellingLoc(SSR.getEnd()));
  10474. }
  10475. DiagRuntimeBehavior(SL, SizeOfArg,
  10476. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  10477. << ReadableName
  10478. << PointeeTy
  10479. << DestTy
  10480. << DSR
  10481. << SSR);
  10482. DiagRuntimeBehavior(SL, SizeOfArg,
  10483. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  10484. << ActionIdx
  10485. << SSR);
  10486. break;
  10487. }
  10488. }
  10489. // Also check for cases where the sizeof argument is the exact same
  10490. // type as the memory argument, and where it points to a user-defined
  10491. // record type.
  10492. if (SizeOfArgTy != QualType()) {
  10493. if (PointeeTy->isRecordType() &&
  10494. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  10495. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  10496. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  10497. << FnName << SizeOfArgTy << ArgIdx
  10498. << PointeeTy << Dest->getSourceRange()
  10499. << LenExpr->getSourceRange());
  10500. break;
  10501. }
  10502. }
  10503. } else if (DestTy->isArrayType()) {
  10504. PointeeTy = DestTy;
  10505. }
  10506. if (PointeeTy == QualType())
  10507. continue;
  10508. // Always complain about dynamic classes.
  10509. bool IsContained;
  10510. if (const CXXRecordDecl *ContainedRD =
  10511. getContainedDynamicClass(PointeeTy, IsContained)) {
  10512. unsigned OperationType = 0;
  10513. const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
  10514. // "overwritten" if we're warning about the destination for any call
  10515. // but memcmp; otherwise a verb appropriate to the call.
  10516. if (ArgIdx != 0 || IsCmp) {
  10517. if (BId == Builtin::BImemcpy)
  10518. OperationType = 1;
  10519. else if(BId == Builtin::BImemmove)
  10520. OperationType = 2;
  10521. else if (IsCmp)
  10522. OperationType = 3;
  10523. }
  10524. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  10525. PDiag(diag::warn_dyn_class_memaccess)
  10526. << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
  10527. << IsContained << ContainedRD << OperationType
  10528. << Call->getCallee()->getSourceRange());
  10529. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  10530. BId != Builtin::BImemset)
  10531. DiagRuntimeBehavior(
  10532. Dest->getExprLoc(), Dest,
  10533. PDiag(diag::warn_arc_object_memaccess)
  10534. << ArgIdx << FnName << PointeeTy
  10535. << Call->getCallee()->getSourceRange());
  10536. else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
  10537. if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
  10538. RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
  10539. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  10540. PDiag(diag::warn_cstruct_memaccess)
  10541. << ArgIdx << FnName << PointeeTy << 0);
  10542. SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
  10543. } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  10544. RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
  10545. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  10546. PDiag(diag::warn_cstruct_memaccess)
  10547. << ArgIdx << FnName << PointeeTy << 1);
  10548. SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
  10549. } else {
  10550. continue;
  10551. }
  10552. } else
  10553. continue;
  10554. DiagRuntimeBehavior(
  10555. Dest->getExprLoc(), Dest,
  10556. PDiag(diag::note_bad_memaccess_silence)
  10557. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  10558. break;
  10559. }
  10560. }
  10561. // A little helper routine: ignore addition and subtraction of integer literals.
  10562. // This intentionally does not ignore all integer constant expressions because
  10563. // we don't want to remove sizeof().
  10564. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  10565. Ex = Ex->IgnoreParenCasts();
  10566. while (true) {
  10567. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  10568. if (!BO || !BO->isAdditiveOp())
  10569. break;
  10570. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  10571. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  10572. if (isa<IntegerLiteral>(RHS))
  10573. Ex = LHS;
  10574. else if (isa<IntegerLiteral>(LHS))
  10575. Ex = RHS;
  10576. else
  10577. break;
  10578. }
  10579. return Ex;
  10580. }
  10581. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  10582. ASTContext &Context) {
  10583. // Only handle constant-sized or VLAs, but not flexible members.
  10584. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  10585. // Only issue the FIXIT for arrays of size > 1.
  10586. if (CAT->getSize().getSExtValue() <= 1)
  10587. return false;
  10588. } else if (!Ty->isVariableArrayType()) {
  10589. return false;
  10590. }
  10591. return true;
  10592. }
  10593. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  10594. // be the size of the source, instead of the destination.
  10595. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  10596. IdentifierInfo *FnName) {
  10597. // Don't crash if the user has the wrong number of arguments
  10598. unsigned NumArgs = Call->getNumArgs();
  10599. if ((NumArgs != 3) && (NumArgs != 4))
  10600. return;
  10601. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  10602. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  10603. const Expr *CompareWithSrc = nullptr;
  10604. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  10605. Call->getBeginLoc(), Call->getRParenLoc()))
  10606. return;
  10607. // Look for 'strlcpy(dst, x, sizeof(x))'
  10608. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  10609. CompareWithSrc = Ex;
  10610. else {
  10611. // Look for 'strlcpy(dst, x, strlen(x))'
  10612. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  10613. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  10614. SizeCall->getNumArgs() == 1)
  10615. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  10616. }
  10617. }
  10618. if (!CompareWithSrc)
  10619. return;
  10620. // Determine if the argument to sizeof/strlen is equal to the source
  10621. // argument. In principle there's all kinds of things you could do
  10622. // here, for instance creating an == expression and evaluating it with
  10623. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  10624. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  10625. if (!SrcArgDRE)
  10626. return;
  10627. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  10628. if (!CompareWithSrcDRE ||
  10629. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  10630. return;
  10631. const Expr *OriginalSizeArg = Call->getArg(2);
  10632. Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
  10633. << OriginalSizeArg->getSourceRange() << FnName;
  10634. // Output a FIXIT hint if the destination is an array (rather than a
  10635. // pointer to an array). This could be enhanced to handle some
  10636. // pointers if we know the actual size, like if DstArg is 'array+2'
  10637. // we could say 'sizeof(array)-2'.
  10638. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  10639. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  10640. return;
  10641. SmallString<128> sizeString;
  10642. llvm::raw_svector_ostream OS(sizeString);
  10643. OS << "sizeof(";
  10644. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  10645. OS << ")";
  10646. Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
  10647. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  10648. OS.str());
  10649. }
  10650. /// Check if two expressions refer to the same declaration.
  10651. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  10652. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  10653. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  10654. return D1->getDecl() == D2->getDecl();
  10655. return false;
  10656. }
  10657. static const Expr *getStrlenExprArg(const Expr *E) {
  10658. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  10659. const FunctionDecl *FD = CE->getDirectCallee();
  10660. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  10661. return nullptr;
  10662. return CE->getArg(0)->IgnoreParenCasts();
  10663. }
  10664. return nullptr;
  10665. }
  10666. // Warn on anti-patterns as the 'size' argument to strncat.
  10667. // The correct size argument should look like following:
  10668. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  10669. void Sema::CheckStrncatArguments(const CallExpr *CE,
  10670. IdentifierInfo *FnName) {
  10671. // Don't crash if the user has the wrong number of arguments.
  10672. if (CE->getNumArgs() < 3)
  10673. return;
  10674. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  10675. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  10676. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  10677. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
  10678. CE->getRParenLoc()))
  10679. return;
  10680. // Identify common expressions, which are wrongly used as the size argument
  10681. // to strncat and may lead to buffer overflows.
  10682. unsigned PatternType = 0;
  10683. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  10684. // - sizeof(dst)
  10685. if (referToTheSameDecl(SizeOfArg, DstArg))
  10686. PatternType = 1;
  10687. // - sizeof(src)
  10688. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  10689. PatternType = 2;
  10690. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  10691. if (BE->getOpcode() == BO_Sub) {
  10692. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  10693. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  10694. // - sizeof(dst) - strlen(dst)
  10695. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  10696. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  10697. PatternType = 1;
  10698. // - sizeof(src) - (anything)
  10699. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  10700. PatternType = 2;
  10701. }
  10702. }
  10703. if (PatternType == 0)
  10704. return;
  10705. // Generate the diagnostic.
  10706. SourceLocation SL = LenArg->getBeginLoc();
  10707. SourceRange SR = LenArg->getSourceRange();
  10708. SourceManager &SM = getSourceManager();
  10709. // If the function is defined as a builtin macro, do not show macro expansion.
  10710. if (SM.isMacroArgExpansion(SL)) {
  10711. SL = SM.getSpellingLoc(SL);
  10712. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  10713. SM.getSpellingLoc(SR.getEnd()));
  10714. }
  10715. // Check if the destination is an array (rather than a pointer to an array).
  10716. QualType DstTy = DstArg->getType();
  10717. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  10718. Context);
  10719. if (!isKnownSizeArray) {
  10720. if (PatternType == 1)
  10721. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  10722. else
  10723. Diag(SL, diag::warn_strncat_src_size) << SR;
  10724. return;
  10725. }
  10726. if (PatternType == 1)
  10727. Diag(SL, diag::warn_strncat_large_size) << SR;
  10728. else
  10729. Diag(SL, diag::warn_strncat_src_size) << SR;
  10730. SmallString<128> sizeString;
  10731. llvm::raw_svector_ostream OS(sizeString);
  10732. OS << "sizeof(";
  10733. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  10734. OS << ") - ";
  10735. OS << "strlen(";
  10736. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  10737. OS << ") - 1";
  10738. Diag(SL, diag::note_strncat_wrong_size)
  10739. << FixItHint::CreateReplacement(SR, OS.str());
  10740. }
  10741. namespace {
  10742. void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
  10743. const UnaryOperator *UnaryExpr, const Decl *D) {
  10744. if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
  10745. S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
  10746. << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
  10747. return;
  10748. }
  10749. }
  10750. void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
  10751. const UnaryOperator *UnaryExpr) {
  10752. if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
  10753. const Decl *D = Lvalue->getDecl();
  10754. if (isa<DeclaratorDecl>(D))
  10755. if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
  10756. return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
  10757. }
  10758. if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
  10759. return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
  10760. Lvalue->getMemberDecl());
  10761. }
  10762. void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
  10763. const UnaryOperator *UnaryExpr) {
  10764. const auto *Lambda = dyn_cast<LambdaExpr>(
  10765. UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
  10766. if (!Lambda)
  10767. return;
  10768. S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
  10769. << CalleeName << 2 /*object: lambda expression*/;
  10770. }
  10771. void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
  10772. const DeclRefExpr *Lvalue) {
  10773. const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
  10774. if (Var == nullptr)
  10775. return;
  10776. S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
  10777. << CalleeName << 0 /*object: */ << Var;
  10778. }
  10779. void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
  10780. const CastExpr *Cast) {
  10781. SmallString<128> SizeString;
  10782. llvm::raw_svector_ostream OS(SizeString);
  10783. clang::CastKind Kind = Cast->getCastKind();
  10784. if (Kind == clang::CK_BitCast &&
  10785. !Cast->getSubExpr()->getType()->isFunctionPointerType())
  10786. return;
  10787. if (Kind == clang::CK_IntegralToPointer &&
  10788. !isa<IntegerLiteral>(
  10789. Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
  10790. return;
  10791. switch (Cast->getCastKind()) {
  10792. case clang::CK_BitCast:
  10793. case clang::CK_IntegralToPointer:
  10794. case clang::CK_FunctionToPointerDecay:
  10795. OS << '\'';
  10796. Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
  10797. OS << '\'';
  10798. break;
  10799. default:
  10800. return;
  10801. }
  10802. S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
  10803. << CalleeName << 0 /*object: */ << OS.str();
  10804. }
  10805. } // namespace
  10806. /// Alerts the user that they are attempting to free a non-malloc'd object.
  10807. void Sema::CheckFreeArguments(const CallExpr *E) {
  10808. const std::string CalleeName =
  10809. cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
  10810. { // Prefer something that doesn't involve a cast to make things simpler.
  10811. const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
  10812. if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
  10813. switch (UnaryExpr->getOpcode()) {
  10814. case UnaryOperator::Opcode::UO_AddrOf:
  10815. return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
  10816. case UnaryOperator::Opcode::UO_Plus:
  10817. return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
  10818. default:
  10819. break;
  10820. }
  10821. if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
  10822. if (Lvalue->getType()->isArrayType())
  10823. return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
  10824. if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
  10825. Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
  10826. << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
  10827. return;
  10828. }
  10829. if (isa<BlockExpr>(Arg)) {
  10830. Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
  10831. << CalleeName << 1 /*object: block*/;
  10832. return;
  10833. }
  10834. }
  10835. // Maybe the cast was important, check after the other cases.
  10836. if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
  10837. return CheckFreeArgumentsCast(*this, CalleeName, Cast);
  10838. }
  10839. void
  10840. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  10841. SourceLocation ReturnLoc,
  10842. bool isObjCMethod,
  10843. const AttrVec *Attrs,
  10844. const FunctionDecl *FD) {
  10845. // Check if the return value is null but should not be.
  10846. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  10847. (!isObjCMethod && isNonNullType(lhsType))) &&
  10848. CheckNonNullExpr(*this, RetValExp))
  10849. Diag(ReturnLoc, diag::warn_null_ret)
  10850. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  10851. // C++11 [basic.stc.dynamic.allocation]p4:
  10852. // If an allocation function declared with a non-throwing
  10853. // exception-specification fails to allocate storage, it shall return
  10854. // a null pointer. Any other allocation function that fails to allocate
  10855. // storage shall indicate failure only by throwing an exception [...]
  10856. if (FD) {
  10857. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  10858. if (Op == OO_New || Op == OO_Array_New) {
  10859. const FunctionProtoType *Proto
  10860. = FD->getType()->castAs<FunctionProtoType>();
  10861. if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
  10862. CheckNonNullExpr(*this, RetValExp))
  10863. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  10864. << FD << getLangOpts().CPlusPlus11;
  10865. }
  10866. }
  10867. // PPC MMA non-pointer types are not allowed as return type. Checking the type
  10868. // here prevent the user from using a PPC MMA type as trailing return type.
  10869. if (Context.getTargetInfo().getTriple().isPPC64())
  10870. CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
  10871. }
  10872. /// Check for comparisons of floating-point values using == and !=. Issue a
  10873. /// warning if the comparison is not likely to do what the programmer intended.
  10874. void Sema::CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
  10875. BinaryOperatorKind Opcode) {
  10876. if (!BinaryOperator::isEqualityOp(Opcode))
  10877. return;
  10878. // Match and capture subexpressions such as "(float) X == 0.1".
  10879. FloatingLiteral *FPLiteral;
  10880. CastExpr *FPCast;
  10881. auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {
  10882. FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
  10883. FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
  10884. return FPLiteral && FPCast;
  10885. };
  10886. if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
  10887. auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
  10888. auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
  10889. if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
  10890. TargetTy->isFloatingPoint()) {
  10891. bool Lossy;
  10892. llvm::APFloat TargetC = FPLiteral->getValue();
  10893. TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
  10894. llvm::APFloat::rmNearestTiesToEven, &Lossy);
  10895. if (Lossy) {
  10896. // If the literal cannot be represented in the source type, then a
  10897. // check for == is always false and check for != is always true.
  10898. Diag(Loc, diag::warn_float_compare_literal)
  10899. << (Opcode == BO_EQ) << QualType(SourceTy, 0)
  10900. << LHS->getSourceRange() << RHS->getSourceRange();
  10901. return;
  10902. }
  10903. }
  10904. }
  10905. // Match a more general floating-point equality comparison (-Wfloat-equal).
  10906. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  10907. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  10908. // Special case: check for x == x (which is OK).
  10909. // Do not emit warnings for such cases.
  10910. if (auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  10911. if (auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  10912. if (DRL->getDecl() == DRR->getDecl())
  10913. return;
  10914. // Special case: check for comparisons against literals that can be exactly
  10915. // represented by APFloat. In such cases, do not emit a warning. This
  10916. // is a heuristic: often comparison against such literals are used to
  10917. // detect if a value in a variable has not changed. This clearly can
  10918. // lead to false negatives.
  10919. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  10920. if (FLL->isExact())
  10921. return;
  10922. } else
  10923. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  10924. if (FLR->isExact())
  10925. return;
  10926. // Check for comparisons with builtin types.
  10927. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  10928. if (CL->getBuiltinCallee())
  10929. return;
  10930. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  10931. if (CR->getBuiltinCallee())
  10932. return;
  10933. // Emit the diagnostic.
  10934. Diag(Loc, diag::warn_floatingpoint_eq)
  10935. << LHS->getSourceRange() << RHS->getSourceRange();
  10936. }
  10937. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  10938. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  10939. namespace {
  10940. /// Structure recording the 'active' range of an integer-valued
  10941. /// expression.
  10942. struct IntRange {
  10943. /// The number of bits active in the int. Note that this includes exactly one
  10944. /// sign bit if !NonNegative.
  10945. unsigned Width;
  10946. /// True if the int is known not to have negative values. If so, all leading
  10947. /// bits before Width are known zero, otherwise they are known to be the
  10948. /// same as the MSB within Width.
  10949. bool NonNegative;
  10950. IntRange(unsigned Width, bool NonNegative)
  10951. : Width(Width), NonNegative(NonNegative) {}
  10952. /// Number of bits excluding the sign bit.
  10953. unsigned valueBits() const {
  10954. return NonNegative ? Width : Width - 1;
  10955. }
  10956. /// Returns the range of the bool type.
  10957. static IntRange forBoolType() {
  10958. return IntRange(1, true);
  10959. }
  10960. /// Returns the range of an opaque value of the given integral type.
  10961. static IntRange forValueOfType(ASTContext &C, QualType T) {
  10962. return forValueOfCanonicalType(C,
  10963. T->getCanonicalTypeInternal().getTypePtr());
  10964. }
  10965. /// Returns the range of an opaque value of a canonical integral type.
  10966. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  10967. assert(T->isCanonicalUnqualified());
  10968. if (const VectorType *VT = dyn_cast<VectorType>(T))
  10969. T = VT->getElementType().getTypePtr();
  10970. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  10971. T = CT->getElementType().getTypePtr();
  10972. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  10973. T = AT->getValueType().getTypePtr();
  10974. if (!C.getLangOpts().CPlusPlus) {
  10975. // For enum types in C code, use the underlying datatype.
  10976. if (const EnumType *ET = dyn_cast<EnumType>(T))
  10977. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  10978. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  10979. // For enum types in C++, use the known bit width of the enumerators.
  10980. EnumDecl *Enum = ET->getDecl();
  10981. // In C++11, enums can have a fixed underlying type. Use this type to
  10982. // compute the range.
  10983. if (Enum->isFixed()) {
  10984. return IntRange(C.getIntWidth(QualType(T, 0)),
  10985. !ET->isSignedIntegerOrEnumerationType());
  10986. }
  10987. unsigned NumPositive = Enum->getNumPositiveBits();
  10988. unsigned NumNegative = Enum->getNumNegativeBits();
  10989. if (NumNegative == 0)
  10990. return IntRange(NumPositive, true/*NonNegative*/);
  10991. else
  10992. return IntRange(std::max(NumPositive + 1, NumNegative),
  10993. false/*NonNegative*/);
  10994. }
  10995. if (const auto *EIT = dyn_cast<BitIntType>(T))
  10996. return IntRange(EIT->getNumBits(), EIT->isUnsigned());
  10997. const BuiltinType *BT = cast<BuiltinType>(T);
  10998. assert(BT->isInteger());
  10999. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  11000. }
  11001. /// Returns the "target" range of a canonical integral type, i.e.
  11002. /// the range of values expressible in the type.
  11003. ///
  11004. /// This matches forValueOfCanonicalType except that enums have the
  11005. /// full range of their type, not the range of their enumerators.
  11006. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  11007. assert(T->isCanonicalUnqualified());
  11008. if (const VectorType *VT = dyn_cast<VectorType>(T))
  11009. T = VT->getElementType().getTypePtr();
  11010. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  11011. T = CT->getElementType().getTypePtr();
  11012. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  11013. T = AT->getValueType().getTypePtr();
  11014. if (const EnumType *ET = dyn_cast<EnumType>(T))
  11015. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  11016. if (const auto *EIT = dyn_cast<BitIntType>(T))
  11017. return IntRange(EIT->getNumBits(), EIT->isUnsigned());
  11018. const BuiltinType *BT = cast<BuiltinType>(T);
  11019. assert(BT->isInteger());
  11020. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  11021. }
  11022. /// Returns the supremum of two ranges: i.e. their conservative merge.
  11023. static IntRange join(IntRange L, IntRange R) {
  11024. bool Unsigned = L.NonNegative && R.NonNegative;
  11025. return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
  11026. L.NonNegative && R.NonNegative);
  11027. }
  11028. /// Return the range of a bitwise-AND of the two ranges.
  11029. static IntRange bit_and(IntRange L, IntRange R) {
  11030. unsigned Bits = std::max(L.Width, R.Width);
  11031. bool NonNegative = false;
  11032. if (L.NonNegative) {
  11033. Bits = std::min(Bits, L.Width);
  11034. NonNegative = true;
  11035. }
  11036. if (R.NonNegative) {
  11037. Bits = std::min(Bits, R.Width);
  11038. NonNegative = true;
  11039. }
  11040. return IntRange(Bits, NonNegative);
  11041. }
  11042. /// Return the range of a sum of the two ranges.
  11043. static IntRange sum(IntRange L, IntRange R) {
  11044. bool Unsigned = L.NonNegative && R.NonNegative;
  11045. return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
  11046. Unsigned);
  11047. }
  11048. /// Return the range of a difference of the two ranges.
  11049. static IntRange difference(IntRange L, IntRange R) {
  11050. // We need a 1-bit-wider range if:
  11051. // 1) LHS can be negative: least value can be reduced.
  11052. // 2) RHS can be negative: greatest value can be increased.
  11053. bool CanWiden = !L.NonNegative || !R.NonNegative;
  11054. bool Unsigned = L.NonNegative && R.Width == 0;
  11055. return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
  11056. !Unsigned,
  11057. Unsigned);
  11058. }
  11059. /// Return the range of a product of the two ranges.
  11060. static IntRange product(IntRange L, IntRange R) {
  11061. // If both LHS and RHS can be negative, we can form
  11062. // -2^L * -2^R = 2^(L + R)
  11063. // which requires L + R + 1 value bits to represent.
  11064. bool CanWiden = !L.NonNegative && !R.NonNegative;
  11065. bool Unsigned = L.NonNegative && R.NonNegative;
  11066. return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
  11067. Unsigned);
  11068. }
  11069. /// Return the range of a remainder operation between the two ranges.
  11070. static IntRange rem(IntRange L, IntRange R) {
  11071. // The result of a remainder can't be larger than the result of
  11072. // either side. The sign of the result is the sign of the LHS.
  11073. bool Unsigned = L.NonNegative;
  11074. return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
  11075. Unsigned);
  11076. }
  11077. };
  11078. } // namespace
  11079. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  11080. unsigned MaxWidth) {
  11081. if (value.isSigned() && value.isNegative())
  11082. return IntRange(value.getMinSignedBits(), false);
  11083. if (value.getBitWidth() > MaxWidth)
  11084. value = value.trunc(MaxWidth);
  11085. // isNonNegative() just checks the sign bit without considering
  11086. // signedness.
  11087. return IntRange(value.getActiveBits(), true);
  11088. }
  11089. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  11090. unsigned MaxWidth) {
  11091. if (result.isInt())
  11092. return GetValueRange(C, result.getInt(), MaxWidth);
  11093. if (result.isVector()) {
  11094. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  11095. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  11096. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  11097. R = IntRange::join(R, El);
  11098. }
  11099. return R;
  11100. }
  11101. if (result.isComplexInt()) {
  11102. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  11103. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  11104. return IntRange::join(R, I);
  11105. }
  11106. // This can happen with lossless casts to intptr_t of "based" lvalues.
  11107. // Assume it might use arbitrary bits.
  11108. // FIXME: The only reason we need to pass the type in here is to get
  11109. // the sign right on this one case. It would be nice if APValue
  11110. // preserved this.
  11111. assert(result.isLValue() || result.isAddrLabelDiff());
  11112. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  11113. }
  11114. static QualType GetExprType(const Expr *E) {
  11115. QualType Ty = E->getType();
  11116. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  11117. Ty = AtomicRHS->getValueType();
  11118. return Ty;
  11119. }
  11120. /// Pseudo-evaluate the given integer expression, estimating the
  11121. /// range of values it might take.
  11122. ///
  11123. /// \param MaxWidth The width to which the value will be truncated.
  11124. /// \param Approximate If \c true, return a likely range for the result: in
  11125. /// particular, assume that arithmetic on narrower types doesn't leave
  11126. /// those types. If \c false, return a range including all possible
  11127. /// result values.
  11128. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
  11129. bool InConstantContext, bool Approximate) {
  11130. E = E->IgnoreParens();
  11131. // Try a full evaluation first.
  11132. Expr::EvalResult result;
  11133. if (E->EvaluateAsRValue(result, C, InConstantContext))
  11134. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  11135. // I think we only want to look through implicit casts here; if the
  11136. // user has an explicit widening cast, we should treat the value as
  11137. // being of the new, wider type.
  11138. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  11139. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  11140. return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
  11141. Approximate);
  11142. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  11143. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  11144. CE->getCastKind() == CK_BooleanToSignedIntegral;
  11145. // Assume that non-integer casts can span the full range of the type.
  11146. if (!isIntegerCast)
  11147. return OutputTypeRange;
  11148. IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
  11149. std::min(MaxWidth, OutputTypeRange.Width),
  11150. InConstantContext, Approximate);
  11151. // Bail out if the subexpr's range is as wide as the cast type.
  11152. if (SubRange.Width >= OutputTypeRange.Width)
  11153. return OutputTypeRange;
  11154. // Otherwise, we take the smaller width, and we're non-negative if
  11155. // either the output type or the subexpr is.
  11156. return IntRange(SubRange.Width,
  11157. SubRange.NonNegative || OutputTypeRange.NonNegative);
  11158. }
  11159. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  11160. // If we can fold the condition, just take that operand.
  11161. bool CondResult;
  11162. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  11163. return GetExprRange(C,
  11164. CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
  11165. MaxWidth, InConstantContext, Approximate);
  11166. // Otherwise, conservatively merge.
  11167. // GetExprRange requires an integer expression, but a throw expression
  11168. // results in a void type.
  11169. Expr *E = CO->getTrueExpr();
  11170. IntRange L = E->getType()->isVoidType()
  11171. ? IntRange{0, true}
  11172. : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
  11173. E = CO->getFalseExpr();
  11174. IntRange R = E->getType()->isVoidType()
  11175. ? IntRange{0, true}
  11176. : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
  11177. return IntRange::join(L, R);
  11178. }
  11179. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  11180. IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
  11181. switch (BO->getOpcode()) {
  11182. case BO_Cmp:
  11183. llvm_unreachable("builtin <=> should have class type");
  11184. // Boolean-valued operations are single-bit and positive.
  11185. case BO_LAnd:
  11186. case BO_LOr:
  11187. case BO_LT:
  11188. case BO_GT:
  11189. case BO_LE:
  11190. case BO_GE:
  11191. case BO_EQ:
  11192. case BO_NE:
  11193. return IntRange::forBoolType();
  11194. // The type of the assignments is the type of the LHS, so the RHS
  11195. // is not necessarily the same type.
  11196. case BO_MulAssign:
  11197. case BO_DivAssign:
  11198. case BO_RemAssign:
  11199. case BO_AddAssign:
  11200. case BO_SubAssign:
  11201. case BO_XorAssign:
  11202. case BO_OrAssign:
  11203. // TODO: bitfields?
  11204. return IntRange::forValueOfType(C, GetExprType(E));
  11205. // Simple assignments just pass through the RHS, which will have
  11206. // been coerced to the LHS type.
  11207. case BO_Assign:
  11208. // TODO: bitfields?
  11209. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
  11210. Approximate);
  11211. // Operations with opaque sources are black-listed.
  11212. case BO_PtrMemD:
  11213. case BO_PtrMemI:
  11214. return IntRange::forValueOfType(C, GetExprType(E));
  11215. // Bitwise-and uses the *infinum* of the two source ranges.
  11216. case BO_And:
  11217. case BO_AndAssign:
  11218. Combine = IntRange::bit_and;
  11219. break;
  11220. // Left shift gets black-listed based on a judgement call.
  11221. case BO_Shl:
  11222. // ...except that we want to treat '1 << (blah)' as logically
  11223. // positive. It's an important idiom.
  11224. if (IntegerLiteral *I
  11225. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  11226. if (I->getValue() == 1) {
  11227. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  11228. return IntRange(R.Width, /*NonNegative*/ true);
  11229. }
  11230. }
  11231. [[fallthrough]];
  11232. case BO_ShlAssign:
  11233. return IntRange::forValueOfType(C, GetExprType(E));
  11234. // Right shift by a constant can narrow its left argument.
  11235. case BO_Shr:
  11236. case BO_ShrAssign: {
  11237. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
  11238. Approximate);
  11239. // If the shift amount is a positive constant, drop the width by
  11240. // that much.
  11241. if (std::optional<llvm::APSInt> shift =
  11242. BO->getRHS()->getIntegerConstantExpr(C)) {
  11243. if (shift->isNonNegative()) {
  11244. unsigned zext = shift->getZExtValue();
  11245. if (zext >= L.Width)
  11246. L.Width = (L.NonNegative ? 0 : 1);
  11247. else
  11248. L.Width -= zext;
  11249. }
  11250. }
  11251. return L;
  11252. }
  11253. // Comma acts as its right operand.
  11254. case BO_Comma:
  11255. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
  11256. Approximate);
  11257. case BO_Add:
  11258. if (!Approximate)
  11259. Combine = IntRange::sum;
  11260. break;
  11261. case BO_Sub:
  11262. if (BO->getLHS()->getType()->isPointerType())
  11263. return IntRange::forValueOfType(C, GetExprType(E));
  11264. if (!Approximate)
  11265. Combine = IntRange::difference;
  11266. break;
  11267. case BO_Mul:
  11268. if (!Approximate)
  11269. Combine = IntRange::product;
  11270. break;
  11271. // The width of a division result is mostly determined by the size
  11272. // of the LHS.
  11273. case BO_Div: {
  11274. // Don't 'pre-truncate' the operands.
  11275. unsigned opWidth = C.getIntWidth(GetExprType(E));
  11276. IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
  11277. Approximate);
  11278. // If the divisor is constant, use that.
  11279. if (std::optional<llvm::APSInt> divisor =
  11280. BO->getRHS()->getIntegerConstantExpr(C)) {
  11281. unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
  11282. if (log2 >= L.Width)
  11283. L.Width = (L.NonNegative ? 0 : 1);
  11284. else
  11285. L.Width = std::min(L.Width - log2, MaxWidth);
  11286. return L;
  11287. }
  11288. // Otherwise, just use the LHS's width.
  11289. // FIXME: This is wrong if the LHS could be its minimal value and the RHS
  11290. // could be -1.
  11291. IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
  11292. Approximate);
  11293. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  11294. }
  11295. case BO_Rem:
  11296. Combine = IntRange::rem;
  11297. break;
  11298. // The default behavior is okay for these.
  11299. case BO_Xor:
  11300. case BO_Or:
  11301. break;
  11302. }
  11303. // Combine the two ranges, but limit the result to the type in which we
  11304. // performed the computation.
  11305. QualType T = GetExprType(E);
  11306. unsigned opWidth = C.getIntWidth(T);
  11307. IntRange L =
  11308. GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
  11309. IntRange R =
  11310. GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
  11311. IntRange C = Combine(L, R);
  11312. C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
  11313. C.Width = std::min(C.Width, MaxWidth);
  11314. return C;
  11315. }
  11316. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  11317. switch (UO->getOpcode()) {
  11318. // Boolean-valued operations are white-listed.
  11319. case UO_LNot:
  11320. return IntRange::forBoolType();
  11321. // Operations with opaque sources are black-listed.
  11322. case UO_Deref:
  11323. case UO_AddrOf: // should be impossible
  11324. return IntRange::forValueOfType(C, GetExprType(E));
  11325. default:
  11326. return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
  11327. Approximate);
  11328. }
  11329. }
  11330. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  11331. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
  11332. Approximate);
  11333. if (const auto *BitField = E->getSourceBitField())
  11334. return IntRange(BitField->getBitWidthValue(C),
  11335. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  11336. return IntRange::forValueOfType(C, GetExprType(E));
  11337. }
  11338. static IntRange GetExprRange(ASTContext &C, const Expr *E,
  11339. bool InConstantContext, bool Approximate) {
  11340. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
  11341. Approximate);
  11342. }
  11343. /// Checks whether the given value, which currently has the given
  11344. /// source semantics, has the same value when coerced through the
  11345. /// target semantics.
  11346. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  11347. const llvm::fltSemantics &Src,
  11348. const llvm::fltSemantics &Tgt) {
  11349. llvm::APFloat truncated = value;
  11350. bool ignored;
  11351. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  11352. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  11353. return truncated.bitwiseIsEqual(value);
  11354. }
  11355. /// Checks whether the given value, which currently has the given
  11356. /// source semantics, has the same value when coerced through the
  11357. /// target semantics.
  11358. ///
  11359. /// The value might be a vector of floats (or a complex number).
  11360. static bool IsSameFloatAfterCast(const APValue &value,
  11361. const llvm::fltSemantics &Src,
  11362. const llvm::fltSemantics &Tgt) {
  11363. if (value.isFloat())
  11364. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  11365. if (value.isVector()) {
  11366. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  11367. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  11368. return false;
  11369. return true;
  11370. }
  11371. assert(value.isComplexFloat());
  11372. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  11373. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  11374. }
  11375. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
  11376. bool IsListInit = false);
  11377. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  11378. // Suppress cases where we are comparing against an enum constant.
  11379. if (const DeclRefExpr *DR =
  11380. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  11381. if (isa<EnumConstantDecl>(DR->getDecl()))
  11382. return true;
  11383. // Suppress cases where the value is expanded from a macro, unless that macro
  11384. // is how a language represents a boolean literal. This is the case in both C
  11385. // and Objective-C.
  11386. SourceLocation BeginLoc = E->getBeginLoc();
  11387. if (BeginLoc.isMacroID()) {
  11388. StringRef MacroName = Lexer::getImmediateMacroName(
  11389. BeginLoc, S.getSourceManager(), S.getLangOpts());
  11390. return MacroName != "YES" && MacroName != "NO" &&
  11391. MacroName != "true" && MacroName != "false";
  11392. }
  11393. return false;
  11394. }
  11395. static bool isKnownToHaveUnsignedValue(Expr *E) {
  11396. return E->getType()->isIntegerType() &&
  11397. (!E->getType()->isSignedIntegerType() ||
  11398. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  11399. }
  11400. namespace {
  11401. /// The promoted range of values of a type. In general this has the
  11402. /// following structure:
  11403. ///
  11404. /// |-----------| . . . |-----------|
  11405. /// ^ ^ ^ ^
  11406. /// Min HoleMin HoleMax Max
  11407. ///
  11408. /// ... where there is only a hole if a signed type is promoted to unsigned
  11409. /// (in which case Min and Max are the smallest and largest representable
  11410. /// values).
  11411. struct PromotedRange {
  11412. // Min, or HoleMax if there is a hole.
  11413. llvm::APSInt PromotedMin;
  11414. // Max, or HoleMin if there is a hole.
  11415. llvm::APSInt PromotedMax;
  11416. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  11417. if (R.Width == 0)
  11418. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  11419. else if (R.Width >= BitWidth && !Unsigned) {
  11420. // Promotion made the type *narrower*. This happens when promoting
  11421. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  11422. // Treat all values of 'signed int' as being in range for now.
  11423. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  11424. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  11425. } else {
  11426. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  11427. .extOrTrunc(BitWidth);
  11428. PromotedMin.setIsUnsigned(Unsigned);
  11429. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  11430. .extOrTrunc(BitWidth);
  11431. PromotedMax.setIsUnsigned(Unsigned);
  11432. }
  11433. }
  11434. // Determine whether this range is contiguous (has no hole).
  11435. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  11436. // Where a constant value is within the range.
  11437. enum ComparisonResult {
  11438. LT = 0x1,
  11439. LE = 0x2,
  11440. GT = 0x4,
  11441. GE = 0x8,
  11442. EQ = 0x10,
  11443. NE = 0x20,
  11444. InRangeFlag = 0x40,
  11445. Less = LE | LT | NE,
  11446. Min = LE | InRangeFlag,
  11447. InRange = InRangeFlag,
  11448. Max = GE | InRangeFlag,
  11449. Greater = GE | GT | NE,
  11450. OnlyValue = LE | GE | EQ | InRangeFlag,
  11451. InHole = NE
  11452. };
  11453. ComparisonResult compare(const llvm::APSInt &Value) const {
  11454. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  11455. Value.isUnsigned() == PromotedMin.isUnsigned());
  11456. if (!isContiguous()) {
  11457. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  11458. if (Value.isMinValue()) return Min;
  11459. if (Value.isMaxValue()) return Max;
  11460. if (Value >= PromotedMin) return InRange;
  11461. if (Value <= PromotedMax) return InRange;
  11462. return InHole;
  11463. }
  11464. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  11465. case -1: return Less;
  11466. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  11467. case 1:
  11468. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  11469. case -1: return InRange;
  11470. case 0: return Max;
  11471. case 1: return Greater;
  11472. }
  11473. }
  11474. llvm_unreachable("impossible compare result");
  11475. }
  11476. static std::optional<StringRef>
  11477. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  11478. if (Op == BO_Cmp) {
  11479. ComparisonResult LTFlag = LT, GTFlag = GT;
  11480. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  11481. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  11482. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  11483. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  11484. return std::nullopt;
  11485. }
  11486. ComparisonResult TrueFlag, FalseFlag;
  11487. if (Op == BO_EQ) {
  11488. TrueFlag = EQ;
  11489. FalseFlag = NE;
  11490. } else if (Op == BO_NE) {
  11491. TrueFlag = NE;
  11492. FalseFlag = EQ;
  11493. } else {
  11494. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  11495. TrueFlag = LT;
  11496. FalseFlag = GE;
  11497. } else {
  11498. TrueFlag = GT;
  11499. FalseFlag = LE;
  11500. }
  11501. if (Op == BO_GE || Op == BO_LE)
  11502. std::swap(TrueFlag, FalseFlag);
  11503. }
  11504. if (R & TrueFlag)
  11505. return StringRef("true");
  11506. if (R & FalseFlag)
  11507. return StringRef("false");
  11508. return std::nullopt;
  11509. }
  11510. };
  11511. }
  11512. static bool HasEnumType(Expr *E) {
  11513. // Strip off implicit integral promotions.
  11514. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  11515. if (ICE->getCastKind() != CK_IntegralCast &&
  11516. ICE->getCastKind() != CK_NoOp)
  11517. break;
  11518. E = ICE->getSubExpr();
  11519. }
  11520. return E->getType()->isEnumeralType();
  11521. }
  11522. static int classifyConstantValue(Expr *Constant) {
  11523. // The values of this enumeration are used in the diagnostics
  11524. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  11525. enum ConstantValueKind {
  11526. Miscellaneous = 0,
  11527. LiteralTrue,
  11528. LiteralFalse
  11529. };
  11530. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  11531. return BL->getValue() ? ConstantValueKind::LiteralTrue
  11532. : ConstantValueKind::LiteralFalse;
  11533. return ConstantValueKind::Miscellaneous;
  11534. }
  11535. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  11536. Expr *Constant, Expr *Other,
  11537. const llvm::APSInt &Value,
  11538. bool RhsConstant) {
  11539. if (S.inTemplateInstantiation())
  11540. return false;
  11541. Expr *OriginalOther = Other;
  11542. Constant = Constant->IgnoreParenImpCasts();
  11543. Other = Other->IgnoreParenImpCasts();
  11544. // Suppress warnings on tautological comparisons between values of the same
  11545. // enumeration type. There are only two ways we could warn on this:
  11546. // - If the constant is outside the range of representable values of
  11547. // the enumeration. In such a case, we should warn about the cast
  11548. // to enumeration type, not about the comparison.
  11549. // - If the constant is the maximum / minimum in-range value. For an
  11550. // enumeratin type, such comparisons can be meaningful and useful.
  11551. if (Constant->getType()->isEnumeralType() &&
  11552. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  11553. return false;
  11554. IntRange OtherValueRange = GetExprRange(
  11555. S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
  11556. QualType OtherT = Other->getType();
  11557. if (const auto *AT = OtherT->getAs<AtomicType>())
  11558. OtherT = AT->getValueType();
  11559. IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
  11560. // Special case for ObjC BOOL on targets where its a typedef for a signed char
  11561. // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
  11562. bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
  11563. S.NSAPIObj->isObjCBOOLType(OtherT) &&
  11564. OtherT->isSpecificBuiltinType(BuiltinType::SChar);
  11565. // Whether we're treating Other as being a bool because of the form of
  11566. // expression despite it having another type (typically 'int' in C).
  11567. bool OtherIsBooleanDespiteType =
  11568. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  11569. if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
  11570. OtherTypeRange = OtherValueRange = IntRange::forBoolType();
  11571. // Check if all values in the range of possible values of this expression
  11572. // lead to the same comparison outcome.
  11573. PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
  11574. Value.isUnsigned());
  11575. auto Cmp = OtherPromotedValueRange.compare(Value);
  11576. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  11577. if (!Result)
  11578. return false;
  11579. // Also consider the range determined by the type alone. This allows us to
  11580. // classify the warning under the proper diagnostic group.
  11581. bool TautologicalTypeCompare = false;
  11582. {
  11583. PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
  11584. Value.isUnsigned());
  11585. auto TypeCmp = OtherPromotedTypeRange.compare(Value);
  11586. if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
  11587. RhsConstant)) {
  11588. TautologicalTypeCompare = true;
  11589. Cmp = TypeCmp;
  11590. Result = TypeResult;
  11591. }
  11592. }
  11593. // Don't warn if the non-constant operand actually always evaluates to the
  11594. // same value.
  11595. if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
  11596. return false;
  11597. // Suppress the diagnostic for an in-range comparison if the constant comes
  11598. // from a macro or enumerator. We don't want to diagnose
  11599. //
  11600. // some_long_value <= INT_MAX
  11601. //
  11602. // when sizeof(int) == sizeof(long).
  11603. bool InRange = Cmp & PromotedRange::InRangeFlag;
  11604. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  11605. return false;
  11606. // A comparison of an unsigned bit-field against 0 is really a type problem,
  11607. // even though at the type level the bit-field might promote to 'signed int'.
  11608. if (Other->refersToBitField() && InRange && Value == 0 &&
  11609. Other->getType()->isUnsignedIntegerOrEnumerationType())
  11610. TautologicalTypeCompare = true;
  11611. // If this is a comparison to an enum constant, include that
  11612. // constant in the diagnostic.
  11613. const EnumConstantDecl *ED = nullptr;
  11614. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  11615. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  11616. // Should be enough for uint128 (39 decimal digits)
  11617. SmallString<64> PrettySourceValue;
  11618. llvm::raw_svector_ostream OS(PrettySourceValue);
  11619. if (ED) {
  11620. OS << '\'' << *ED << "' (" << Value << ")";
  11621. } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
  11622. Constant->IgnoreParenImpCasts())) {
  11623. OS << (BL->getValue() ? "YES" : "NO");
  11624. } else {
  11625. OS << Value;
  11626. }
  11627. if (!TautologicalTypeCompare) {
  11628. S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
  11629. << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
  11630. << E->getOpcodeStr() << OS.str() << *Result
  11631. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  11632. return true;
  11633. }
  11634. if (IsObjCSignedCharBool) {
  11635. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  11636. S.PDiag(diag::warn_tautological_compare_objc_bool)
  11637. << OS.str() << *Result);
  11638. return true;
  11639. }
  11640. // FIXME: We use a somewhat different formatting for the in-range cases and
  11641. // cases involving boolean values for historical reasons. We should pick a
  11642. // consistent way of presenting these diagnostics.
  11643. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  11644. S.DiagRuntimeBehavior(
  11645. E->getOperatorLoc(), E,
  11646. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  11647. : diag::warn_tautological_bool_compare)
  11648. << OS.str() << classifyConstantValue(Constant) << OtherT
  11649. << OtherIsBooleanDespiteType << *Result
  11650. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  11651. } else {
  11652. bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
  11653. unsigned Diag =
  11654. (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  11655. ? (HasEnumType(OriginalOther)
  11656. ? diag::warn_unsigned_enum_always_true_comparison
  11657. : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
  11658. : diag::warn_unsigned_always_true_comparison)
  11659. : diag::warn_tautological_constant_compare;
  11660. S.Diag(E->getOperatorLoc(), Diag)
  11661. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  11662. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  11663. }
  11664. return true;
  11665. }
  11666. /// Analyze the operands of the given comparison. Implements the
  11667. /// fallback case from AnalyzeComparison.
  11668. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  11669. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  11670. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  11671. }
  11672. /// Implements -Wsign-compare.
  11673. ///
  11674. /// \param E the binary operator to check for warnings
  11675. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  11676. // The type the comparison is being performed in.
  11677. QualType T = E->getLHS()->getType();
  11678. // Only analyze comparison operators where both sides have been converted to
  11679. // the same type.
  11680. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  11681. return AnalyzeImpConvsInComparison(S, E);
  11682. // Don't analyze value-dependent comparisons directly.
  11683. if (E->isValueDependent())
  11684. return AnalyzeImpConvsInComparison(S, E);
  11685. Expr *LHS = E->getLHS();
  11686. Expr *RHS = E->getRHS();
  11687. if (T->isIntegralType(S.Context)) {
  11688. std::optional<llvm::APSInt> RHSValue =
  11689. RHS->getIntegerConstantExpr(S.Context);
  11690. std::optional<llvm::APSInt> LHSValue =
  11691. LHS->getIntegerConstantExpr(S.Context);
  11692. // We don't care about expressions whose result is a constant.
  11693. if (RHSValue && LHSValue)
  11694. return AnalyzeImpConvsInComparison(S, E);
  11695. // We only care about expressions where just one side is literal
  11696. if ((bool)RHSValue ^ (bool)LHSValue) {
  11697. // Is the constant on the RHS or LHS?
  11698. const bool RhsConstant = (bool)RHSValue;
  11699. Expr *Const = RhsConstant ? RHS : LHS;
  11700. Expr *Other = RhsConstant ? LHS : RHS;
  11701. const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
  11702. // Check whether an integer constant comparison results in a value
  11703. // of 'true' or 'false'.
  11704. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  11705. return AnalyzeImpConvsInComparison(S, E);
  11706. }
  11707. }
  11708. if (!T->hasUnsignedIntegerRepresentation()) {
  11709. // We don't do anything special if this isn't an unsigned integral
  11710. // comparison: we're only interested in integral comparisons, and
  11711. // signed comparisons only happen in cases we don't care to warn about.
  11712. return AnalyzeImpConvsInComparison(S, E);
  11713. }
  11714. LHS = LHS->IgnoreParenImpCasts();
  11715. RHS = RHS->IgnoreParenImpCasts();
  11716. if (!S.getLangOpts().CPlusPlus) {
  11717. // Avoid warning about comparison of integers with different signs when
  11718. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  11719. // the type of `E`.
  11720. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  11721. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  11722. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  11723. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  11724. }
  11725. // Check to see if one of the (unmodified) operands is of different
  11726. // signedness.
  11727. Expr *signedOperand, *unsignedOperand;
  11728. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  11729. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  11730. "unsigned comparison between two signed integer expressions?");
  11731. signedOperand = LHS;
  11732. unsignedOperand = RHS;
  11733. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  11734. signedOperand = RHS;
  11735. unsignedOperand = LHS;
  11736. } else {
  11737. return AnalyzeImpConvsInComparison(S, E);
  11738. }
  11739. // Otherwise, calculate the effective range of the signed operand.
  11740. IntRange signedRange = GetExprRange(
  11741. S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
  11742. // Go ahead and analyze implicit conversions in the operands. Note
  11743. // that we skip the implicit conversions on both sides.
  11744. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  11745. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  11746. // If the signed range is non-negative, -Wsign-compare won't fire.
  11747. if (signedRange.NonNegative)
  11748. return;
  11749. // For (in)equality comparisons, if the unsigned operand is a
  11750. // constant which cannot collide with a overflowed signed operand,
  11751. // then reinterpreting the signed operand as unsigned will not
  11752. // change the result of the comparison.
  11753. if (E->isEqualityOp()) {
  11754. unsigned comparisonWidth = S.Context.getIntWidth(T);
  11755. IntRange unsignedRange =
  11756. GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
  11757. /*Approximate*/ true);
  11758. // We should never be unable to prove that the unsigned operand is
  11759. // non-negative.
  11760. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  11761. if (unsignedRange.Width < comparisonWidth)
  11762. return;
  11763. }
  11764. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  11765. S.PDiag(diag::warn_mixed_sign_comparison)
  11766. << LHS->getType() << RHS->getType()
  11767. << LHS->getSourceRange() << RHS->getSourceRange());
  11768. }
  11769. /// Analyzes an attempt to assign the given value to a bitfield.
  11770. ///
  11771. /// Returns true if there was something fishy about the attempt.
  11772. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  11773. SourceLocation InitLoc) {
  11774. assert(Bitfield->isBitField());
  11775. if (Bitfield->isInvalidDecl())
  11776. return false;
  11777. // White-list bool bitfields.
  11778. QualType BitfieldType = Bitfield->getType();
  11779. if (BitfieldType->isBooleanType())
  11780. return false;
  11781. if (BitfieldType->isEnumeralType()) {
  11782. EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
  11783. // If the underlying enum type was not explicitly specified as an unsigned
  11784. // type and the enum contain only positive values, MSVC++ will cause an
  11785. // inconsistency by storing this as a signed type.
  11786. if (S.getLangOpts().CPlusPlus11 &&
  11787. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  11788. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  11789. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  11790. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  11791. << BitfieldEnumDecl;
  11792. }
  11793. }
  11794. // Ignore value- or type-dependent expressions.
  11795. if (Bitfield->getBitWidth()->isValueDependent() ||
  11796. Bitfield->getBitWidth()->isTypeDependent() ||
  11797. Init->isValueDependent() ||
  11798. Init->isTypeDependent())
  11799. return false;
  11800. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  11801. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  11802. Expr::EvalResult Result;
  11803. if (!OriginalInit->EvaluateAsInt(Result, S.Context,
  11804. Expr::SE_AllowSideEffects)) {
  11805. // The RHS is not constant. If the RHS has an enum type, make sure the
  11806. // bitfield is wide enough to hold all the values of the enum without
  11807. // truncation.
  11808. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  11809. EnumDecl *ED = EnumTy->getDecl();
  11810. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  11811. // Enum types are implicitly signed on Windows, so check if there are any
  11812. // negative enumerators to see if the enum was intended to be signed or
  11813. // not.
  11814. bool SignedEnum = ED->getNumNegativeBits() > 0;
  11815. // Check for surprising sign changes when assigning enum values to a
  11816. // bitfield of different signedness. If the bitfield is signed and we
  11817. // have exactly the right number of bits to store this unsigned enum,
  11818. // suggest changing the enum to an unsigned type. This typically happens
  11819. // on Windows where unfixed enums always use an underlying type of 'int'.
  11820. unsigned DiagID = 0;
  11821. if (SignedEnum && !SignedBitfield) {
  11822. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  11823. } else if (SignedBitfield && !SignedEnum &&
  11824. ED->getNumPositiveBits() == FieldWidth) {
  11825. DiagID = diag::warn_signed_bitfield_enum_conversion;
  11826. }
  11827. if (DiagID) {
  11828. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  11829. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  11830. SourceRange TypeRange =
  11831. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  11832. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  11833. << SignedEnum << TypeRange;
  11834. }
  11835. // Compute the required bitwidth. If the enum has negative values, we need
  11836. // one more bit than the normal number of positive bits to represent the
  11837. // sign bit.
  11838. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  11839. ED->getNumNegativeBits())
  11840. : ED->getNumPositiveBits();
  11841. // Check the bitwidth.
  11842. if (BitsNeeded > FieldWidth) {
  11843. Expr *WidthExpr = Bitfield->getBitWidth();
  11844. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  11845. << Bitfield << ED;
  11846. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  11847. << BitsNeeded << ED << WidthExpr->getSourceRange();
  11848. }
  11849. }
  11850. return false;
  11851. }
  11852. llvm::APSInt Value = Result.Val.getInt();
  11853. unsigned OriginalWidth = Value.getBitWidth();
  11854. // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
  11855. // false positives where the user is demonstrating they intend to use the
  11856. // bit-field as a Boolean, check to see if the value is 1 and we're assigning
  11857. // to a one-bit bit-field to see if the value came from a macro named 'true'.
  11858. bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
  11859. if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
  11860. SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
  11861. if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
  11862. S.findMacroSpelling(MaybeMacroLoc, "true"))
  11863. return false;
  11864. }
  11865. if (!Value.isSigned() || Value.isNegative())
  11866. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  11867. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  11868. OriginalWidth = Value.getMinSignedBits();
  11869. if (OriginalWidth <= FieldWidth)
  11870. return false;
  11871. // Compute the value which the bitfield will contain.
  11872. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  11873. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  11874. // Check whether the stored value is equal to the original value.
  11875. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  11876. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  11877. return false;
  11878. std::string PrettyValue = toString(Value, 10);
  11879. std::string PrettyTrunc = toString(TruncatedValue, 10);
  11880. S.Diag(InitLoc, OneAssignedToOneBitBitfield
  11881. ? diag::warn_impcast_single_bit_bitield_precision_constant
  11882. : diag::warn_impcast_bitfield_precision_constant)
  11883. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  11884. << Init->getSourceRange();
  11885. return true;
  11886. }
  11887. /// Analyze the given simple or compound assignment for warning-worthy
  11888. /// operations.
  11889. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  11890. // Just recurse on the LHS.
  11891. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  11892. // We want to recurse on the RHS as normal unless we're assigning to
  11893. // a bitfield.
  11894. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  11895. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  11896. E->getOperatorLoc())) {
  11897. // Recurse, ignoring any implicit conversions on the RHS.
  11898. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  11899. E->getOperatorLoc());
  11900. }
  11901. }
  11902. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  11903. // Diagnose implicitly sequentially-consistent atomic assignment.
  11904. if (E->getLHS()->getType()->isAtomicType())
  11905. S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  11906. }
  11907. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  11908. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  11909. SourceLocation CContext, unsigned diag,
  11910. bool pruneControlFlow = false) {
  11911. if (pruneControlFlow) {
  11912. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  11913. S.PDiag(diag)
  11914. << SourceType << T << E->getSourceRange()
  11915. << SourceRange(CContext));
  11916. return;
  11917. }
  11918. S.Diag(E->getExprLoc(), diag)
  11919. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  11920. }
  11921. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  11922. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  11923. SourceLocation CContext,
  11924. unsigned diag, bool pruneControlFlow = false) {
  11925. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  11926. }
  11927. static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
  11928. return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
  11929. S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
  11930. }
  11931. static void adornObjCBoolConversionDiagWithTernaryFixit(
  11932. Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
  11933. Expr *Ignored = SourceExpr->IgnoreImplicit();
  11934. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
  11935. Ignored = OVE->getSourceExpr();
  11936. bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
  11937. isa<BinaryOperator>(Ignored) ||
  11938. isa<CXXOperatorCallExpr>(Ignored);
  11939. SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
  11940. if (NeedsParens)
  11941. Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
  11942. << FixItHint::CreateInsertion(EndLoc, ")");
  11943. Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
  11944. }
  11945. /// Diagnose an implicit cast from a floating point value to an integer value.
  11946. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  11947. SourceLocation CContext) {
  11948. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  11949. const bool PruneWarnings = S.inTemplateInstantiation();
  11950. Expr *InnerE = E->IgnoreParenImpCasts();
  11951. // We also want to warn on, e.g., "int i = -1.234"
  11952. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  11953. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  11954. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  11955. const bool IsLiteral =
  11956. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  11957. llvm::APFloat Value(0.0);
  11958. bool IsConstant =
  11959. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  11960. if (!IsConstant) {
  11961. if (isObjCSignedCharBool(S, T)) {
  11962. return adornObjCBoolConversionDiagWithTernaryFixit(
  11963. S, E,
  11964. S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
  11965. << E->getType());
  11966. }
  11967. return DiagnoseImpCast(S, E, T, CContext,
  11968. diag::warn_impcast_float_integer, PruneWarnings);
  11969. }
  11970. bool isExact = false;
  11971. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  11972. T->hasUnsignedIntegerRepresentation());
  11973. llvm::APFloat::opStatus Result = Value.convertToInteger(
  11974. IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
  11975. // FIXME: Force the precision of the source value down so we don't print
  11976. // digits which are usually useless (we don't really care here if we
  11977. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  11978. // would automatically print the shortest representation, but it's a bit
  11979. // tricky to implement.
  11980. SmallString<16> PrettySourceValue;
  11981. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  11982. precision = (precision * 59 + 195) / 196;
  11983. Value.toString(PrettySourceValue, precision);
  11984. if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
  11985. return adornObjCBoolConversionDiagWithTernaryFixit(
  11986. S, E,
  11987. S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
  11988. << PrettySourceValue);
  11989. }
  11990. if (Result == llvm::APFloat::opOK && isExact) {
  11991. if (IsLiteral) return;
  11992. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  11993. PruneWarnings);
  11994. }
  11995. // Conversion of a floating-point value to a non-bool integer where the
  11996. // integral part cannot be represented by the integer type is undefined.
  11997. if (!IsBool && Result == llvm::APFloat::opInvalidOp)
  11998. return DiagnoseImpCast(
  11999. S, E, T, CContext,
  12000. IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
  12001. : diag::warn_impcast_float_to_integer_out_of_range,
  12002. PruneWarnings);
  12003. unsigned DiagID = 0;
  12004. if (IsLiteral) {
  12005. // Warn on floating point literal to integer.
  12006. DiagID = diag::warn_impcast_literal_float_to_integer;
  12007. } else if (IntegerValue == 0) {
  12008. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  12009. return DiagnoseImpCast(S, E, T, CContext,
  12010. diag::warn_impcast_float_integer, PruneWarnings);
  12011. }
  12012. // Warn on non-zero to zero conversion.
  12013. DiagID = diag::warn_impcast_float_to_integer_zero;
  12014. } else {
  12015. if (IntegerValue.isUnsigned()) {
  12016. if (!IntegerValue.isMaxValue()) {
  12017. return DiagnoseImpCast(S, E, T, CContext,
  12018. diag::warn_impcast_float_integer, PruneWarnings);
  12019. }
  12020. } else { // IntegerValue.isSigned()
  12021. if (!IntegerValue.isMaxSignedValue() &&
  12022. !IntegerValue.isMinSignedValue()) {
  12023. return DiagnoseImpCast(S, E, T, CContext,
  12024. diag::warn_impcast_float_integer, PruneWarnings);
  12025. }
  12026. }
  12027. // Warn on evaluatable floating point expression to integer conversion.
  12028. DiagID = diag::warn_impcast_float_to_integer;
  12029. }
  12030. SmallString<16> PrettyTargetValue;
  12031. if (IsBool)
  12032. PrettyTargetValue = Value.isZero() ? "false" : "true";
  12033. else
  12034. IntegerValue.toString(PrettyTargetValue);
  12035. if (PruneWarnings) {
  12036. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  12037. S.PDiag(DiagID)
  12038. << E->getType() << T.getUnqualifiedType()
  12039. << PrettySourceValue << PrettyTargetValue
  12040. << E->getSourceRange() << SourceRange(CContext));
  12041. } else {
  12042. S.Diag(E->getExprLoc(), DiagID)
  12043. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  12044. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  12045. }
  12046. }
  12047. /// Analyze the given compound assignment for the possible losing of
  12048. /// floating-point precision.
  12049. static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
  12050. assert(isa<CompoundAssignOperator>(E) &&
  12051. "Must be compound assignment operation");
  12052. // Recurse on the LHS and RHS in here
  12053. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  12054. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  12055. if (E->getLHS()->getType()->isAtomicType())
  12056. S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
  12057. // Now check the outermost expression
  12058. const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
  12059. const auto *RBT = cast<CompoundAssignOperator>(E)
  12060. ->getComputationResultType()
  12061. ->getAs<BuiltinType>();
  12062. // The below checks assume source is floating point.
  12063. if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
  12064. // If source is floating point but target is an integer.
  12065. if (ResultBT->isInteger())
  12066. return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
  12067. E->getExprLoc(), diag::warn_impcast_float_integer);
  12068. if (!ResultBT->isFloatingPoint())
  12069. return;
  12070. // If both source and target are floating points, warn about losing precision.
  12071. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  12072. QualType(ResultBT, 0), QualType(RBT, 0));
  12073. if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
  12074. // warn about dropping FP rank.
  12075. DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
  12076. diag::warn_impcast_float_result_precision);
  12077. }
  12078. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  12079. IntRange Range) {
  12080. if (!Range.Width) return "0";
  12081. llvm::APSInt ValueInRange = Value;
  12082. ValueInRange.setIsSigned(!Range.NonNegative);
  12083. ValueInRange = ValueInRange.trunc(Range.Width);
  12084. return toString(ValueInRange, 10);
  12085. }
  12086. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  12087. if (!isa<ImplicitCastExpr>(Ex))
  12088. return false;
  12089. Expr *InnerE = Ex->IgnoreParenImpCasts();
  12090. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  12091. const Type *Source =
  12092. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  12093. if (Target->isDependentType())
  12094. return false;
  12095. const BuiltinType *FloatCandidateBT =
  12096. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  12097. const Type *BoolCandidateType = ToBool ? Target : Source;
  12098. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  12099. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  12100. }
  12101. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  12102. SourceLocation CC) {
  12103. unsigned NumArgs = TheCall->getNumArgs();
  12104. for (unsigned i = 0; i < NumArgs; ++i) {
  12105. Expr *CurrA = TheCall->getArg(i);
  12106. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  12107. continue;
  12108. bool IsSwapped = ((i > 0) &&
  12109. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  12110. IsSwapped |= ((i < (NumArgs - 1)) &&
  12111. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  12112. if (IsSwapped) {
  12113. // Warn on this floating-point to bool conversion.
  12114. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  12115. CurrA->getType(), CC,
  12116. diag::warn_impcast_floating_point_to_bool);
  12117. }
  12118. }
  12119. }
  12120. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  12121. SourceLocation CC) {
  12122. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  12123. E->getExprLoc()))
  12124. return;
  12125. // Don't warn on functions which have return type nullptr_t.
  12126. if (isa<CallExpr>(E))
  12127. return;
  12128. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  12129. const Expr *NewE = E->IgnoreParenImpCasts();
  12130. bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
  12131. bool HasNullPtrType = NewE->getType()->isNullPtrType();
  12132. if (!IsGNUNullExpr && !HasNullPtrType)
  12133. return;
  12134. // Return if target type is a safe conversion.
  12135. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  12136. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  12137. return;
  12138. SourceLocation Loc = E->getSourceRange().getBegin();
  12139. // Venture through the macro stacks to get to the source of macro arguments.
  12140. // The new location is a better location than the complete location that was
  12141. // passed in.
  12142. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  12143. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  12144. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  12145. if (IsGNUNullExpr && Loc.isMacroID()) {
  12146. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  12147. Loc, S.SourceMgr, S.getLangOpts());
  12148. if (MacroName == "NULL")
  12149. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
  12150. }
  12151. // Only warn if the null and context location are in the same macro expansion.
  12152. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  12153. return;
  12154. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  12155. << HasNullPtrType << T << SourceRange(CC)
  12156. << FixItHint::CreateReplacement(Loc,
  12157. S.getFixItZeroLiteralForType(T, Loc));
  12158. }
  12159. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  12160. ObjCArrayLiteral *ArrayLiteral);
  12161. static void
  12162. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  12163. ObjCDictionaryLiteral *DictionaryLiteral);
  12164. /// Check a single element within a collection literal against the
  12165. /// target element type.
  12166. static void checkObjCCollectionLiteralElement(Sema &S,
  12167. QualType TargetElementType,
  12168. Expr *Element,
  12169. unsigned ElementKind) {
  12170. // Skip a bitcast to 'id' or qualified 'id'.
  12171. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  12172. if (ICE->getCastKind() == CK_BitCast &&
  12173. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  12174. Element = ICE->getSubExpr();
  12175. }
  12176. QualType ElementType = Element->getType();
  12177. ExprResult ElementResult(Element);
  12178. if (ElementType->getAs<ObjCObjectPointerType>() &&
  12179. S.CheckSingleAssignmentConstraints(TargetElementType,
  12180. ElementResult,
  12181. false, false)
  12182. != Sema::Compatible) {
  12183. S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
  12184. << ElementType << ElementKind << TargetElementType
  12185. << Element->getSourceRange();
  12186. }
  12187. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  12188. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  12189. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  12190. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  12191. }
  12192. /// Check an Objective-C array literal being converted to the given
  12193. /// target type.
  12194. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  12195. ObjCArrayLiteral *ArrayLiteral) {
  12196. if (!S.NSArrayDecl)
  12197. return;
  12198. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  12199. if (!TargetObjCPtr)
  12200. return;
  12201. if (TargetObjCPtr->isUnspecialized() ||
  12202. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  12203. != S.NSArrayDecl->getCanonicalDecl())
  12204. return;
  12205. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  12206. if (TypeArgs.size() != 1)
  12207. return;
  12208. QualType TargetElementType = TypeArgs[0];
  12209. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  12210. checkObjCCollectionLiteralElement(S, TargetElementType,
  12211. ArrayLiteral->getElement(I),
  12212. 0);
  12213. }
  12214. }
  12215. /// Check an Objective-C dictionary literal being converted to the given
  12216. /// target type.
  12217. static void
  12218. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  12219. ObjCDictionaryLiteral *DictionaryLiteral) {
  12220. if (!S.NSDictionaryDecl)
  12221. return;
  12222. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  12223. if (!TargetObjCPtr)
  12224. return;
  12225. if (TargetObjCPtr->isUnspecialized() ||
  12226. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  12227. != S.NSDictionaryDecl->getCanonicalDecl())
  12228. return;
  12229. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  12230. if (TypeArgs.size() != 2)
  12231. return;
  12232. QualType TargetKeyType = TypeArgs[0];
  12233. QualType TargetObjectType = TypeArgs[1];
  12234. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  12235. auto Element = DictionaryLiteral->getKeyValueElement(I);
  12236. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  12237. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  12238. }
  12239. }
  12240. // Helper function to filter out cases for constant width constant conversion.
  12241. // Don't warn on char array initialization or for non-decimal values.
  12242. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  12243. SourceLocation CC) {
  12244. // If initializing from a constant, and the constant starts with '0',
  12245. // then it is a binary, octal, or hexadecimal. Allow these constants
  12246. // to fill all the bits, even if there is a sign change.
  12247. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  12248. const char FirstLiteralCharacter =
  12249. S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
  12250. if (FirstLiteralCharacter == '0')
  12251. return false;
  12252. }
  12253. // If the CC location points to a '{', and the type is char, then assume
  12254. // assume it is an array initialization.
  12255. if (CC.isValid() && T->isCharType()) {
  12256. const char FirstContextCharacter =
  12257. S.getSourceManager().getCharacterData(CC)[0];
  12258. if (FirstContextCharacter == '{')
  12259. return false;
  12260. }
  12261. return true;
  12262. }
  12263. static const IntegerLiteral *getIntegerLiteral(Expr *E) {
  12264. const auto *IL = dyn_cast<IntegerLiteral>(E);
  12265. if (!IL) {
  12266. if (auto *UO = dyn_cast<UnaryOperator>(E)) {
  12267. if (UO->getOpcode() == UO_Minus)
  12268. return dyn_cast<IntegerLiteral>(UO->getSubExpr());
  12269. }
  12270. }
  12271. return IL;
  12272. }
  12273. static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
  12274. E = E->IgnoreParenImpCasts();
  12275. SourceLocation ExprLoc = E->getExprLoc();
  12276. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  12277. BinaryOperator::Opcode Opc = BO->getOpcode();
  12278. Expr::EvalResult Result;
  12279. // Do not diagnose unsigned shifts.
  12280. if (Opc == BO_Shl) {
  12281. const auto *LHS = getIntegerLiteral(BO->getLHS());
  12282. const auto *RHS = getIntegerLiteral(BO->getRHS());
  12283. if (LHS && LHS->getValue() == 0)
  12284. S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
  12285. else if (!E->isValueDependent() && LHS && RHS &&
  12286. RHS->getValue().isNonNegative() &&
  12287. E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
  12288. S.Diag(ExprLoc, diag::warn_left_shift_always)
  12289. << (Result.Val.getInt() != 0);
  12290. else if (E->getType()->isSignedIntegerType())
  12291. S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
  12292. }
  12293. }
  12294. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  12295. const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
  12296. const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
  12297. if (!LHS || !RHS)
  12298. return;
  12299. if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
  12300. (RHS->getValue() == 0 || RHS->getValue() == 1))
  12301. // Do not diagnose common idioms.
  12302. return;
  12303. if (LHS->getValue() != 0 && RHS->getValue() != 0)
  12304. S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
  12305. }
  12306. }
  12307. static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  12308. SourceLocation CC,
  12309. bool *ICContext = nullptr,
  12310. bool IsListInit = false) {
  12311. if (E->isTypeDependent() || E->isValueDependent()) return;
  12312. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  12313. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  12314. if (Source == Target) return;
  12315. if (Target->isDependentType()) return;
  12316. // If the conversion context location is invalid don't complain. We also
  12317. // don't want to emit a warning if the issue occurs from the expansion of
  12318. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  12319. // delay this check as long as possible. Once we detect we are in that
  12320. // scenario, we just return.
  12321. if (CC.isInvalid())
  12322. return;
  12323. if (Source->isAtomicType())
  12324. S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
  12325. // Diagnose implicit casts to bool.
  12326. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  12327. if (isa<StringLiteral>(E))
  12328. // Warn on string literal to bool. Checks for string literals in logical
  12329. // and expressions, for instance, assert(0 && "error here"), are
  12330. // prevented by a check in AnalyzeImplicitConversions().
  12331. return DiagnoseImpCast(S, E, T, CC,
  12332. diag::warn_impcast_string_literal_to_bool);
  12333. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  12334. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  12335. // This covers the literal expressions that evaluate to Objective-C
  12336. // objects.
  12337. return DiagnoseImpCast(S, E, T, CC,
  12338. diag::warn_impcast_objective_c_literal_to_bool);
  12339. }
  12340. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  12341. // Warn on pointer to bool conversion that is always true.
  12342. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  12343. SourceRange(CC));
  12344. }
  12345. }
  12346. // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
  12347. // is a typedef for signed char (macOS), then that constant value has to be 1
  12348. // or 0.
  12349. if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
  12350. Expr::EvalResult Result;
  12351. if (E->EvaluateAsInt(Result, S.getASTContext(),
  12352. Expr::SE_AllowSideEffects)) {
  12353. if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
  12354. adornObjCBoolConversionDiagWithTernaryFixit(
  12355. S, E,
  12356. S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
  12357. << toString(Result.Val.getInt(), 10));
  12358. }
  12359. return;
  12360. }
  12361. }
  12362. // Check implicit casts from Objective-C collection literals to specialized
  12363. // collection types, e.g., NSArray<NSString *> *.
  12364. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  12365. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  12366. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  12367. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  12368. // Strip vector types.
  12369. if (isa<VectorType>(Source)) {
  12370. if (Target->isVLSTBuiltinType() &&
  12371. (S.Context.areCompatibleSveTypes(QualType(Target, 0),
  12372. QualType(Source, 0)) ||
  12373. S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
  12374. QualType(Source, 0))))
  12375. return;
  12376. if (!isa<VectorType>(Target)) {
  12377. if (S.SourceMgr.isInSystemMacro(CC))
  12378. return;
  12379. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  12380. }
  12381. // If the vector cast is cast between two vectors of the same size, it is
  12382. // a bitcast, not a conversion.
  12383. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  12384. return;
  12385. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  12386. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  12387. }
  12388. if (auto VecTy = dyn_cast<VectorType>(Target))
  12389. Target = VecTy->getElementType().getTypePtr();
  12390. // Strip complex types.
  12391. if (isa<ComplexType>(Source)) {
  12392. if (!isa<ComplexType>(Target)) {
  12393. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  12394. return;
  12395. return DiagnoseImpCast(S, E, T, CC,
  12396. S.getLangOpts().CPlusPlus
  12397. ? diag::err_impcast_complex_scalar
  12398. : diag::warn_impcast_complex_scalar);
  12399. }
  12400. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  12401. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  12402. }
  12403. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  12404. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  12405. // Strip SVE vector types
  12406. if (SourceBT && SourceBT->isVLSTBuiltinType()) {
  12407. // Need the original target type for vector type checks
  12408. const Type *OriginalTarget = S.Context.getCanonicalType(T).getTypePtr();
  12409. // Handle conversion from scalable to fixed when msve-vector-bits is
  12410. // specified
  12411. if (S.Context.areCompatibleSveTypes(QualType(OriginalTarget, 0),
  12412. QualType(Source, 0)) ||
  12413. S.Context.areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
  12414. QualType(Source, 0)))
  12415. return;
  12416. // If the vector cast is cast between two vectors of the same size, it is
  12417. // a bitcast, not a conversion.
  12418. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  12419. return;
  12420. Source = SourceBT->getSveEltType(S.Context).getTypePtr();
  12421. }
  12422. if (TargetBT && TargetBT->isVLSTBuiltinType())
  12423. Target = TargetBT->getSveEltType(S.Context).getTypePtr();
  12424. // If the source is floating point...
  12425. if (SourceBT && SourceBT->isFloatingPoint()) {
  12426. // ...and the target is floating point...
  12427. if (TargetBT && TargetBT->isFloatingPoint()) {
  12428. // ...then warn if we're dropping FP rank.
  12429. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  12430. QualType(SourceBT, 0), QualType(TargetBT, 0));
  12431. if (Order > 0) {
  12432. // Don't warn about float constants that are precisely
  12433. // representable in the target type.
  12434. Expr::EvalResult result;
  12435. if (E->EvaluateAsRValue(result, S.Context)) {
  12436. // Value might be a float, a float vector, or a float complex.
  12437. if (IsSameFloatAfterCast(result.Val,
  12438. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  12439. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  12440. return;
  12441. }
  12442. if (S.SourceMgr.isInSystemMacro(CC))
  12443. return;
  12444. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  12445. }
  12446. // ... or possibly if we're increasing rank, too
  12447. else if (Order < 0) {
  12448. if (S.SourceMgr.isInSystemMacro(CC))
  12449. return;
  12450. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  12451. }
  12452. return;
  12453. }
  12454. // If the target is integral, always warn.
  12455. if (TargetBT && TargetBT->isInteger()) {
  12456. if (S.SourceMgr.isInSystemMacro(CC))
  12457. return;
  12458. DiagnoseFloatingImpCast(S, E, T, CC);
  12459. }
  12460. // Detect the case where a call result is converted from floating-point to
  12461. // to bool, and the final argument to the call is converted from bool, to
  12462. // discover this typo:
  12463. //
  12464. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  12465. //
  12466. // FIXME: This is an incredibly special case; is there some more general
  12467. // way to detect this class of misplaced-parentheses bug?
  12468. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  12469. // Check last argument of function call to see if it is an
  12470. // implicit cast from a type matching the type the result
  12471. // is being cast to.
  12472. CallExpr *CEx = cast<CallExpr>(E);
  12473. if (unsigned NumArgs = CEx->getNumArgs()) {
  12474. Expr *LastA = CEx->getArg(NumArgs - 1);
  12475. Expr *InnerE = LastA->IgnoreParenImpCasts();
  12476. if (isa<ImplicitCastExpr>(LastA) &&
  12477. InnerE->getType()->isBooleanType()) {
  12478. // Warn on this floating-point to bool conversion
  12479. DiagnoseImpCast(S, E, T, CC,
  12480. diag::warn_impcast_floating_point_to_bool);
  12481. }
  12482. }
  12483. }
  12484. return;
  12485. }
  12486. // Valid casts involving fixed point types should be accounted for here.
  12487. if (Source->isFixedPointType()) {
  12488. if (Target->isUnsaturatedFixedPointType()) {
  12489. Expr::EvalResult Result;
  12490. if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
  12491. S.isConstantEvaluated())) {
  12492. llvm::APFixedPoint Value = Result.Val.getFixedPoint();
  12493. llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
  12494. llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
  12495. if (Value > MaxVal || Value < MinVal) {
  12496. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  12497. S.PDiag(diag::warn_impcast_fixed_point_range)
  12498. << Value.toString() << T
  12499. << E->getSourceRange()
  12500. << clang::SourceRange(CC));
  12501. return;
  12502. }
  12503. }
  12504. } else if (Target->isIntegerType()) {
  12505. Expr::EvalResult Result;
  12506. if (!S.isConstantEvaluated() &&
  12507. E->EvaluateAsFixedPoint(Result, S.Context,
  12508. Expr::SE_AllowSideEffects)) {
  12509. llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
  12510. bool Overflowed;
  12511. llvm::APSInt IntResult = FXResult.convertToInt(
  12512. S.Context.getIntWidth(T),
  12513. Target->isSignedIntegerOrEnumerationType(), &Overflowed);
  12514. if (Overflowed) {
  12515. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  12516. S.PDiag(diag::warn_impcast_fixed_point_range)
  12517. << FXResult.toString() << T
  12518. << E->getSourceRange()
  12519. << clang::SourceRange(CC));
  12520. return;
  12521. }
  12522. }
  12523. }
  12524. } else if (Target->isUnsaturatedFixedPointType()) {
  12525. if (Source->isIntegerType()) {
  12526. Expr::EvalResult Result;
  12527. if (!S.isConstantEvaluated() &&
  12528. E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
  12529. llvm::APSInt Value = Result.Val.getInt();
  12530. bool Overflowed;
  12531. llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
  12532. Value, S.Context.getFixedPointSemantics(T), &Overflowed);
  12533. if (Overflowed) {
  12534. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  12535. S.PDiag(diag::warn_impcast_fixed_point_range)
  12536. << toString(Value, /*Radix=*/10) << T
  12537. << E->getSourceRange()
  12538. << clang::SourceRange(CC));
  12539. return;
  12540. }
  12541. }
  12542. }
  12543. }
  12544. // If we are casting an integer type to a floating point type without
  12545. // initialization-list syntax, we might lose accuracy if the floating
  12546. // point type has a narrower significand than the integer type.
  12547. if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
  12548. TargetBT->isFloatingType() && !IsListInit) {
  12549. // Determine the number of precision bits in the source integer type.
  12550. IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
  12551. /*Approximate*/ true);
  12552. unsigned int SourcePrecision = SourceRange.Width;
  12553. // Determine the number of precision bits in the
  12554. // target floating point type.
  12555. unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
  12556. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
  12557. if (SourcePrecision > 0 && TargetPrecision > 0 &&
  12558. SourcePrecision > TargetPrecision) {
  12559. if (std::optional<llvm::APSInt> SourceInt =
  12560. E->getIntegerConstantExpr(S.Context)) {
  12561. // If the source integer is a constant, convert it to the target
  12562. // floating point type. Issue a warning if the value changes
  12563. // during the whole conversion.
  12564. llvm::APFloat TargetFloatValue(
  12565. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
  12566. llvm::APFloat::opStatus ConversionStatus =
  12567. TargetFloatValue.convertFromAPInt(
  12568. *SourceInt, SourceBT->isSignedInteger(),
  12569. llvm::APFloat::rmNearestTiesToEven);
  12570. if (ConversionStatus != llvm::APFloat::opOK) {
  12571. SmallString<32> PrettySourceValue;
  12572. SourceInt->toString(PrettySourceValue, 10);
  12573. SmallString<32> PrettyTargetValue;
  12574. TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
  12575. S.DiagRuntimeBehavior(
  12576. E->getExprLoc(), E,
  12577. S.PDiag(diag::warn_impcast_integer_float_precision_constant)
  12578. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  12579. << E->getSourceRange() << clang::SourceRange(CC));
  12580. }
  12581. } else {
  12582. // Otherwise, the implicit conversion may lose precision.
  12583. DiagnoseImpCast(S, E, T, CC,
  12584. diag::warn_impcast_integer_float_precision);
  12585. }
  12586. }
  12587. }
  12588. DiagnoseNullConversion(S, E, T, CC);
  12589. S.DiscardMisalignedMemberAddress(Target, E);
  12590. if (Target->isBooleanType())
  12591. DiagnoseIntInBoolContext(S, E);
  12592. if (!Source->isIntegerType() || !Target->isIntegerType())
  12593. return;
  12594. // TODO: remove this early return once the false positives for constant->bool
  12595. // in templates, macros, etc, are reduced or removed.
  12596. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  12597. return;
  12598. if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
  12599. !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
  12600. return adornObjCBoolConversionDiagWithTernaryFixit(
  12601. S, E,
  12602. S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
  12603. << E->getType());
  12604. }
  12605. IntRange SourceTypeRange =
  12606. IntRange::forTargetOfCanonicalType(S.Context, Source);
  12607. IntRange LikelySourceRange =
  12608. GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
  12609. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  12610. if (LikelySourceRange.Width > TargetRange.Width) {
  12611. // If the source is a constant, use a default-on diagnostic.
  12612. // TODO: this should happen for bitfield stores, too.
  12613. Expr::EvalResult Result;
  12614. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
  12615. S.isConstantEvaluated())) {
  12616. llvm::APSInt Value(32);
  12617. Value = Result.Val.getInt();
  12618. if (S.SourceMgr.isInSystemMacro(CC))
  12619. return;
  12620. std::string PrettySourceValue = toString(Value, 10);
  12621. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  12622. S.DiagRuntimeBehavior(
  12623. E->getExprLoc(), E,
  12624. S.PDiag(diag::warn_impcast_integer_precision_constant)
  12625. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  12626. << E->getSourceRange() << SourceRange(CC));
  12627. return;
  12628. }
  12629. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  12630. if (S.SourceMgr.isInSystemMacro(CC))
  12631. return;
  12632. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  12633. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  12634. /* pruneControlFlow */ true);
  12635. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  12636. }
  12637. if (TargetRange.Width > SourceTypeRange.Width) {
  12638. if (auto *UO = dyn_cast<UnaryOperator>(E))
  12639. if (UO->getOpcode() == UO_Minus)
  12640. if (Source->isUnsignedIntegerType()) {
  12641. if (Target->isUnsignedIntegerType())
  12642. return DiagnoseImpCast(S, E, T, CC,
  12643. diag::warn_impcast_high_order_zero_bits);
  12644. if (Target->isSignedIntegerType())
  12645. return DiagnoseImpCast(S, E, T, CC,
  12646. diag::warn_impcast_nonnegative_result);
  12647. }
  12648. }
  12649. if (TargetRange.Width == LikelySourceRange.Width &&
  12650. !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
  12651. Source->isSignedIntegerType()) {
  12652. // Warn when doing a signed to signed conversion, warn if the positive
  12653. // source value is exactly the width of the target type, which will
  12654. // cause a negative value to be stored.
  12655. Expr::EvalResult Result;
  12656. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
  12657. !S.SourceMgr.isInSystemMacro(CC)) {
  12658. llvm::APSInt Value = Result.Val.getInt();
  12659. if (isSameWidthConstantConversion(S, E, T, CC)) {
  12660. std::string PrettySourceValue = toString(Value, 10);
  12661. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  12662. S.DiagRuntimeBehavior(
  12663. E->getExprLoc(), E,
  12664. S.PDiag(diag::warn_impcast_integer_precision_constant)
  12665. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  12666. << E->getSourceRange() << SourceRange(CC));
  12667. return;
  12668. }
  12669. }
  12670. // Fall through for non-constants to give a sign conversion warning.
  12671. }
  12672. if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
  12673. ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
  12674. (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
  12675. LikelySourceRange.Width == TargetRange.Width))) {
  12676. if (S.SourceMgr.isInSystemMacro(CC))
  12677. return;
  12678. unsigned DiagID = diag::warn_impcast_integer_sign;
  12679. // Traditionally, gcc has warned about this under -Wsign-compare.
  12680. // We also want to warn about it in -Wconversion.
  12681. // So if -Wconversion is off, use a completely identical diagnostic
  12682. // in the sign-compare group.
  12683. // The conditional-checking code will
  12684. if (ICContext) {
  12685. DiagID = diag::warn_impcast_integer_sign_conditional;
  12686. *ICContext = true;
  12687. }
  12688. return DiagnoseImpCast(S, E, T, CC, DiagID);
  12689. }
  12690. // Diagnose conversions between different enumeration types.
  12691. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  12692. // type, to give us better diagnostics.
  12693. QualType SourceType = E->getType();
  12694. if (!S.getLangOpts().CPlusPlus) {
  12695. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  12696. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  12697. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  12698. SourceType = S.Context.getTypeDeclType(Enum);
  12699. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  12700. }
  12701. }
  12702. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  12703. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  12704. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  12705. TargetEnum->getDecl()->hasNameForLinkage() &&
  12706. SourceEnum != TargetEnum) {
  12707. if (S.SourceMgr.isInSystemMacro(CC))
  12708. return;
  12709. return DiagnoseImpCast(S, E, SourceType, T, CC,
  12710. diag::warn_impcast_different_enum_types);
  12711. }
  12712. }
  12713. static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
  12714. SourceLocation CC, QualType T);
  12715. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  12716. SourceLocation CC, bool &ICContext) {
  12717. E = E->IgnoreParenImpCasts();
  12718. if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
  12719. return CheckConditionalOperator(S, CO, CC, T);
  12720. AnalyzeImplicitConversions(S, E, CC);
  12721. if (E->getType() != T)
  12722. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  12723. }
  12724. static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
  12725. SourceLocation CC, QualType T) {
  12726. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  12727. Expr *TrueExpr = E->getTrueExpr();
  12728. if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
  12729. TrueExpr = BCO->getCommon();
  12730. bool Suspicious = false;
  12731. CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
  12732. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  12733. if (T->isBooleanType())
  12734. DiagnoseIntInBoolContext(S, E);
  12735. // If -Wconversion would have warned about either of the candidates
  12736. // for a signedness conversion to the context type...
  12737. if (!Suspicious) return;
  12738. // ...but it's currently ignored...
  12739. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  12740. return;
  12741. // ...then check whether it would have warned about either of the
  12742. // candidates for a signedness conversion to the condition type.
  12743. if (E->getType() == T) return;
  12744. Suspicious = false;
  12745. CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
  12746. E->getType(), CC, &Suspicious);
  12747. if (!Suspicious)
  12748. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  12749. E->getType(), CC, &Suspicious);
  12750. }
  12751. /// Check conversion of given expression to boolean.
  12752. /// Input argument E is a logical expression.
  12753. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  12754. if (S.getLangOpts().Bool)
  12755. return;
  12756. if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
  12757. return;
  12758. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  12759. }
  12760. namespace {
  12761. struct AnalyzeImplicitConversionsWorkItem {
  12762. Expr *E;
  12763. SourceLocation CC;
  12764. bool IsListInit;
  12765. };
  12766. }
  12767. /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
  12768. /// that should be visited are added to WorkList.
  12769. static void AnalyzeImplicitConversions(
  12770. Sema &S, AnalyzeImplicitConversionsWorkItem Item,
  12771. llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
  12772. Expr *OrigE = Item.E;
  12773. SourceLocation CC = Item.CC;
  12774. QualType T = OrigE->getType();
  12775. Expr *E = OrigE->IgnoreParenImpCasts();
  12776. // Propagate whether we are in a C++ list initialization expression.
  12777. // If so, we do not issue warnings for implicit int-float conversion
  12778. // precision loss, because C++11 narrowing already handles it.
  12779. bool IsListInit = Item.IsListInit ||
  12780. (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
  12781. if (E->isTypeDependent() || E->isValueDependent())
  12782. return;
  12783. Expr *SourceExpr = E;
  12784. // Examine, but don't traverse into the source expression of an
  12785. // OpaqueValueExpr, since it may have multiple parents and we don't want to
  12786. // emit duplicate diagnostics. Its fine to examine the form or attempt to
  12787. // evaluate it in the context of checking the specific conversion to T though.
  12788. if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  12789. if (auto *Src = OVE->getSourceExpr())
  12790. SourceExpr = Src;
  12791. if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
  12792. if (UO->getOpcode() == UO_Not &&
  12793. UO->getSubExpr()->isKnownToHaveBooleanValue())
  12794. S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
  12795. << OrigE->getSourceRange() << T->isBooleanType()
  12796. << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
  12797. if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
  12798. if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
  12799. BO->getLHS()->isKnownToHaveBooleanValue() &&
  12800. BO->getRHS()->isKnownToHaveBooleanValue() &&
  12801. BO->getLHS()->HasSideEffects(S.Context) &&
  12802. BO->getRHS()->HasSideEffects(S.Context)) {
  12803. S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
  12804. << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
  12805. << FixItHint::CreateReplacement(
  12806. BO->getOperatorLoc(),
  12807. (BO->getOpcode() == BO_And ? "&&" : "||"));
  12808. S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
  12809. }
  12810. // For conditional operators, we analyze the arguments as if they
  12811. // were being fed directly into the output.
  12812. if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
  12813. CheckConditionalOperator(S, CO, CC, T);
  12814. return;
  12815. }
  12816. // Check implicit argument conversions for function calls.
  12817. if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
  12818. CheckImplicitArgumentConversions(S, Call, CC);
  12819. // Go ahead and check any implicit conversions we might have skipped.
  12820. // The non-canonical typecheck is just an optimization;
  12821. // CheckImplicitConversion will filter out dead implicit conversions.
  12822. if (SourceExpr->getType() != T)
  12823. CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
  12824. // Now continue drilling into this expression.
  12825. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  12826. // The bound subexpressions in a PseudoObjectExpr are not reachable
  12827. // as transitive children.
  12828. // FIXME: Use a more uniform representation for this.
  12829. for (auto *SE : POE->semantics())
  12830. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  12831. WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
  12832. }
  12833. // Skip past explicit casts.
  12834. if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
  12835. E = CE->getSubExpr()->IgnoreParenImpCasts();
  12836. if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
  12837. S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  12838. WorkList.push_back({E, CC, IsListInit});
  12839. return;
  12840. }
  12841. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  12842. // Do a somewhat different check with comparison operators.
  12843. if (BO->isComparisonOp())
  12844. return AnalyzeComparison(S, BO);
  12845. // And with simple assignments.
  12846. if (BO->getOpcode() == BO_Assign)
  12847. return AnalyzeAssignment(S, BO);
  12848. // And with compound assignments.
  12849. if (BO->isAssignmentOp())
  12850. return AnalyzeCompoundAssignment(S, BO);
  12851. }
  12852. // These break the otherwise-useful invariant below. Fortunately,
  12853. // we don't really need to recurse into them, because any internal
  12854. // expressions should have been analyzed already when they were
  12855. // built into statements.
  12856. if (isa<StmtExpr>(E)) return;
  12857. // Don't descend into unevaluated contexts.
  12858. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  12859. // Now just recurse over the expression's children.
  12860. CC = E->getExprLoc();
  12861. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  12862. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  12863. for (Stmt *SubStmt : E->children()) {
  12864. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  12865. if (!ChildExpr)
  12866. continue;
  12867. if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
  12868. if (ChildExpr == CSE->getOperand())
  12869. // Do not recurse over a CoroutineSuspendExpr's operand.
  12870. // The operand is also a subexpression of getCommonExpr(), and
  12871. // recursing into it directly would produce duplicate diagnostics.
  12872. continue;
  12873. if (IsLogicalAndOperator &&
  12874. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  12875. // Ignore checking string literals that are in logical and operators.
  12876. // This is a common pattern for asserts.
  12877. continue;
  12878. WorkList.push_back({ChildExpr, CC, IsListInit});
  12879. }
  12880. if (BO && BO->isLogicalOp()) {
  12881. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  12882. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  12883. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  12884. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  12885. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  12886. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  12887. }
  12888. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  12889. if (U->getOpcode() == UO_LNot) {
  12890. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  12891. } else if (U->getOpcode() != UO_AddrOf) {
  12892. if (U->getSubExpr()->getType()->isAtomicType())
  12893. S.Diag(U->getSubExpr()->getBeginLoc(),
  12894. diag::warn_atomic_implicit_seq_cst);
  12895. }
  12896. }
  12897. }
  12898. /// AnalyzeImplicitConversions - Find and report any interesting
  12899. /// implicit conversions in the given expression. There are a couple
  12900. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  12901. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
  12902. bool IsListInit/*= false*/) {
  12903. llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
  12904. WorkList.push_back({OrigE, CC, IsListInit});
  12905. while (!WorkList.empty())
  12906. AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
  12907. }
  12908. /// Diagnose integer type and any valid implicit conversion to it.
  12909. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  12910. // Taking into account implicit conversions,
  12911. // allow any integer.
  12912. if (!E->getType()->isIntegerType()) {
  12913. S.Diag(E->getBeginLoc(),
  12914. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  12915. return true;
  12916. }
  12917. // Potentially emit standard warnings for implicit conversions if enabled
  12918. // using -Wconversion.
  12919. CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
  12920. return false;
  12921. }
  12922. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  12923. // Returns true when emitting a warning about taking the address of a reference.
  12924. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  12925. const PartialDiagnostic &PD) {
  12926. E = E->IgnoreParenImpCasts();
  12927. const FunctionDecl *FD = nullptr;
  12928. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  12929. if (!DRE->getDecl()->getType()->isReferenceType())
  12930. return false;
  12931. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  12932. if (!M->getMemberDecl()->getType()->isReferenceType())
  12933. return false;
  12934. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  12935. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  12936. return false;
  12937. FD = Call->getDirectCallee();
  12938. } else {
  12939. return false;
  12940. }
  12941. SemaRef.Diag(E->getExprLoc(), PD);
  12942. // If possible, point to location of function.
  12943. if (FD) {
  12944. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  12945. }
  12946. return true;
  12947. }
  12948. // Returns true if the SourceLocation is expanded from any macro body.
  12949. // Returns false if the SourceLocation is invalid, is from not in a macro
  12950. // expansion, or is from expanded from a top-level macro argument.
  12951. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  12952. if (Loc.isInvalid())
  12953. return false;
  12954. while (Loc.isMacroID()) {
  12955. if (SM.isMacroBodyExpansion(Loc))
  12956. return true;
  12957. Loc = SM.getImmediateMacroCallerLoc(Loc);
  12958. }
  12959. return false;
  12960. }
  12961. /// Diagnose pointers that are always non-null.
  12962. /// \param E the expression containing the pointer
  12963. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  12964. /// compared to a null pointer
  12965. /// \param IsEqual True when the comparison is equal to a null pointer
  12966. /// \param Range Extra SourceRange to highlight in the diagnostic
  12967. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  12968. Expr::NullPointerConstantKind NullKind,
  12969. bool IsEqual, SourceRange Range) {
  12970. if (!E)
  12971. return;
  12972. // Don't warn inside macros.
  12973. if (E->getExprLoc().isMacroID()) {
  12974. const SourceManager &SM = getSourceManager();
  12975. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  12976. IsInAnyMacroBody(SM, Range.getBegin()))
  12977. return;
  12978. }
  12979. E = E->IgnoreImpCasts();
  12980. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  12981. if (isa<CXXThisExpr>(E)) {
  12982. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  12983. : diag::warn_this_bool_conversion;
  12984. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  12985. return;
  12986. }
  12987. bool IsAddressOf = false;
  12988. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  12989. if (UO->getOpcode() != UO_AddrOf)
  12990. return;
  12991. IsAddressOf = true;
  12992. E = UO->getSubExpr();
  12993. }
  12994. if (IsAddressOf) {
  12995. unsigned DiagID = IsCompare
  12996. ? diag::warn_address_of_reference_null_compare
  12997. : diag::warn_address_of_reference_bool_conversion;
  12998. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  12999. << IsEqual;
  13000. if (CheckForReference(*this, E, PD)) {
  13001. return;
  13002. }
  13003. }
  13004. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  13005. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  13006. std::string Str;
  13007. llvm::raw_string_ostream S(Str);
  13008. E->printPretty(S, nullptr, getPrintingPolicy());
  13009. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  13010. : diag::warn_cast_nonnull_to_bool;
  13011. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  13012. << E->getSourceRange() << Range << IsEqual;
  13013. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  13014. };
  13015. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  13016. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  13017. if (auto *Callee = Call->getDirectCallee()) {
  13018. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  13019. ComplainAboutNonnullParamOrCall(A);
  13020. return;
  13021. }
  13022. }
  13023. }
  13024. // Expect to find a single Decl. Skip anything more complicated.
  13025. ValueDecl *D = nullptr;
  13026. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  13027. D = R->getDecl();
  13028. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  13029. D = M->getMemberDecl();
  13030. }
  13031. // Weak Decls can be null.
  13032. if (!D || D->isWeak())
  13033. return;
  13034. // Check for parameter decl with nonnull attribute
  13035. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  13036. if (getCurFunction() &&
  13037. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  13038. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  13039. ComplainAboutNonnullParamOrCall(A);
  13040. return;
  13041. }
  13042. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  13043. // Skip function template not specialized yet.
  13044. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  13045. return;
  13046. auto ParamIter = llvm::find(FD->parameters(), PV);
  13047. assert(ParamIter != FD->param_end());
  13048. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  13049. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  13050. if (!NonNull->args_size()) {
  13051. ComplainAboutNonnullParamOrCall(NonNull);
  13052. return;
  13053. }
  13054. for (const ParamIdx &ArgNo : NonNull->args()) {
  13055. if (ArgNo.getASTIndex() == ParamNo) {
  13056. ComplainAboutNonnullParamOrCall(NonNull);
  13057. return;
  13058. }
  13059. }
  13060. }
  13061. }
  13062. }
  13063. }
  13064. QualType T = D->getType();
  13065. const bool IsArray = T->isArrayType();
  13066. const bool IsFunction = T->isFunctionType();
  13067. // Address of function is used to silence the function warning.
  13068. if (IsAddressOf && IsFunction) {
  13069. return;
  13070. }
  13071. // Found nothing.
  13072. if (!IsAddressOf && !IsFunction && !IsArray)
  13073. return;
  13074. // Pretty print the expression for the diagnostic.
  13075. std::string Str;
  13076. llvm::raw_string_ostream S(Str);
  13077. E->printPretty(S, nullptr, getPrintingPolicy());
  13078. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  13079. : diag::warn_impcast_pointer_to_bool;
  13080. enum {
  13081. AddressOf,
  13082. FunctionPointer,
  13083. ArrayPointer
  13084. } DiagType;
  13085. if (IsAddressOf)
  13086. DiagType = AddressOf;
  13087. else if (IsFunction)
  13088. DiagType = FunctionPointer;
  13089. else if (IsArray)
  13090. DiagType = ArrayPointer;
  13091. else
  13092. llvm_unreachable("Could not determine diagnostic.");
  13093. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  13094. << Range << IsEqual;
  13095. if (!IsFunction)
  13096. return;
  13097. // Suggest '&' to silence the function warning.
  13098. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  13099. << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
  13100. // Check to see if '()' fixit should be emitted.
  13101. QualType ReturnType;
  13102. UnresolvedSet<4> NonTemplateOverloads;
  13103. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  13104. if (ReturnType.isNull())
  13105. return;
  13106. if (IsCompare) {
  13107. // There are two cases here. If there is null constant, the only suggest
  13108. // for a pointer return type. If the null is 0, then suggest if the return
  13109. // type is a pointer or an integer type.
  13110. if (!ReturnType->isPointerType()) {
  13111. if (NullKind == Expr::NPCK_ZeroExpression ||
  13112. NullKind == Expr::NPCK_ZeroLiteral) {
  13113. if (!ReturnType->isIntegerType())
  13114. return;
  13115. } else {
  13116. return;
  13117. }
  13118. }
  13119. } else { // !IsCompare
  13120. // For function to bool, only suggest if the function pointer has bool
  13121. // return type.
  13122. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  13123. return;
  13124. }
  13125. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  13126. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
  13127. }
  13128. /// Diagnoses "dangerous" implicit conversions within the given
  13129. /// expression (which is a full expression). Implements -Wconversion
  13130. /// and -Wsign-compare.
  13131. ///
  13132. /// \param CC the "context" location of the implicit conversion, i.e.
  13133. /// the most location of the syntactic entity requiring the implicit
  13134. /// conversion
  13135. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  13136. // Don't diagnose in unevaluated contexts.
  13137. if (isUnevaluatedContext())
  13138. return;
  13139. // Don't diagnose for value- or type-dependent expressions.
  13140. if (E->isTypeDependent() || E->isValueDependent())
  13141. return;
  13142. // Check for array bounds violations in cases where the check isn't triggered
  13143. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  13144. // ArraySubscriptExpr is on the RHS of a variable initialization.
  13145. CheckArrayAccess(E);
  13146. // This is not the right CC for (e.g.) a variable initialization.
  13147. AnalyzeImplicitConversions(*this, E, CC);
  13148. }
  13149. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  13150. /// Input argument E is a logical expression.
  13151. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  13152. ::CheckBoolLikeConversion(*this, E, CC);
  13153. }
  13154. /// Diagnose when expression is an integer constant expression and its evaluation
  13155. /// results in integer overflow
  13156. void Sema::CheckForIntOverflow (Expr *E) {
  13157. // Use a work list to deal with nested struct initializers.
  13158. SmallVector<Expr *, 2> Exprs(1, E);
  13159. do {
  13160. Expr *OriginalE = Exprs.pop_back_val();
  13161. Expr *E = OriginalE->IgnoreParenCasts();
  13162. if (isa<BinaryOperator>(E)) {
  13163. E->EvaluateForOverflow(Context);
  13164. continue;
  13165. }
  13166. if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
  13167. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  13168. else if (isa<ObjCBoxedExpr>(OriginalE))
  13169. E->EvaluateForOverflow(Context);
  13170. else if (auto Call = dyn_cast<CallExpr>(E))
  13171. Exprs.append(Call->arg_begin(), Call->arg_end());
  13172. else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
  13173. Exprs.append(Message->arg_begin(), Message->arg_end());
  13174. else if (auto Construct = dyn_cast<CXXConstructExpr>(E))
  13175. Exprs.append(Construct->arg_begin(), Construct->arg_end());
  13176. else if (auto Array = dyn_cast<ArraySubscriptExpr>(E))
  13177. Exprs.push_back(Array->getIdx());
  13178. else if (auto Compound = dyn_cast<CompoundLiteralExpr>(E))
  13179. Exprs.push_back(Compound->getInitializer());
  13180. else if (auto New = dyn_cast<CXXNewExpr>(E)) {
  13181. if (New->isArray())
  13182. if (auto ArraySize = New->getArraySize())
  13183. Exprs.push_back(*ArraySize);
  13184. }
  13185. } while (!Exprs.empty());
  13186. }
  13187. namespace {
  13188. /// Visitor for expressions which looks for unsequenced operations on the
  13189. /// same object.
  13190. class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
  13191. using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
  13192. /// A tree of sequenced regions within an expression. Two regions are
  13193. /// unsequenced if one is an ancestor or a descendent of the other. When we
  13194. /// finish processing an expression with sequencing, such as a comma
  13195. /// expression, we fold its tree nodes into its parent, since they are
  13196. /// unsequenced with respect to nodes we will visit later.
  13197. class SequenceTree {
  13198. struct Value {
  13199. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  13200. unsigned Parent : 31;
  13201. unsigned Merged : 1;
  13202. };
  13203. SmallVector<Value, 8> Values;
  13204. public:
  13205. /// A region within an expression which may be sequenced with respect
  13206. /// to some other region.
  13207. class Seq {
  13208. friend class SequenceTree;
  13209. unsigned Index;
  13210. explicit Seq(unsigned N) : Index(N) {}
  13211. public:
  13212. Seq() : Index(0) {}
  13213. };
  13214. SequenceTree() { Values.push_back(Value(0)); }
  13215. Seq root() const { return Seq(0); }
  13216. /// Create a new sequence of operations, which is an unsequenced
  13217. /// subset of \p Parent. This sequence of operations is sequenced with
  13218. /// respect to other children of \p Parent.
  13219. Seq allocate(Seq Parent) {
  13220. Values.push_back(Value(Parent.Index));
  13221. return Seq(Values.size() - 1);
  13222. }
  13223. /// Merge a sequence of operations into its parent.
  13224. void merge(Seq S) {
  13225. Values[S.Index].Merged = true;
  13226. }
  13227. /// Determine whether two operations are unsequenced. This operation
  13228. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  13229. /// should have been merged into its parent as appropriate.
  13230. bool isUnsequenced(Seq Cur, Seq Old) {
  13231. unsigned C = representative(Cur.Index);
  13232. unsigned Target = representative(Old.Index);
  13233. while (C >= Target) {
  13234. if (C == Target)
  13235. return true;
  13236. C = Values[C].Parent;
  13237. }
  13238. return false;
  13239. }
  13240. private:
  13241. /// Pick a representative for a sequence.
  13242. unsigned representative(unsigned K) {
  13243. if (Values[K].Merged)
  13244. // Perform path compression as we go.
  13245. return Values[K].Parent = representative(Values[K].Parent);
  13246. return K;
  13247. }
  13248. };
  13249. /// An object for which we can track unsequenced uses.
  13250. using Object = const NamedDecl *;
  13251. /// Different flavors of object usage which we track. We only track the
  13252. /// least-sequenced usage of each kind.
  13253. enum UsageKind {
  13254. /// A read of an object. Multiple unsequenced reads are OK.
  13255. UK_Use,
  13256. /// A modification of an object which is sequenced before the value
  13257. /// computation of the expression, such as ++n in C++.
  13258. UK_ModAsValue,
  13259. /// A modification of an object which is not sequenced before the value
  13260. /// computation of the expression, such as n++.
  13261. UK_ModAsSideEffect,
  13262. UK_Count = UK_ModAsSideEffect + 1
  13263. };
  13264. /// Bundle together a sequencing region and the expression corresponding
  13265. /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
  13266. struct Usage {
  13267. const Expr *UsageExpr;
  13268. SequenceTree::Seq Seq;
  13269. Usage() : UsageExpr(nullptr) {}
  13270. };
  13271. struct UsageInfo {
  13272. Usage Uses[UK_Count];
  13273. /// Have we issued a diagnostic for this object already?
  13274. bool Diagnosed;
  13275. UsageInfo() : Diagnosed(false) {}
  13276. };
  13277. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  13278. Sema &SemaRef;
  13279. /// Sequenced regions within the expression.
  13280. SequenceTree Tree;
  13281. /// Declaration modifications and references which we have seen.
  13282. UsageInfoMap UsageMap;
  13283. /// The region we are currently within.
  13284. SequenceTree::Seq Region;
  13285. /// Filled in with declarations which were modified as a side-effect
  13286. /// (that is, post-increment operations).
  13287. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  13288. /// Expressions to check later. We defer checking these to reduce
  13289. /// stack usage.
  13290. SmallVectorImpl<const Expr *> &WorkList;
  13291. /// RAII object wrapping the visitation of a sequenced subexpression of an
  13292. /// expression. At the end of this process, the side-effects of the evaluation
  13293. /// become sequenced with respect to the value computation of the result, so
  13294. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  13295. /// UK_ModAsValue.
  13296. struct SequencedSubexpression {
  13297. SequencedSubexpression(SequenceChecker &Self)
  13298. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  13299. Self.ModAsSideEffect = &ModAsSideEffect;
  13300. }
  13301. ~SequencedSubexpression() {
  13302. for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
  13303. // Add a new usage with usage kind UK_ModAsValue, and then restore
  13304. // the previous usage with UK_ModAsSideEffect (thus clearing it if
  13305. // the previous one was empty).
  13306. UsageInfo &UI = Self.UsageMap[M.first];
  13307. auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
  13308. Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
  13309. SideEffectUsage = M.second;
  13310. }
  13311. Self.ModAsSideEffect = OldModAsSideEffect;
  13312. }
  13313. SequenceChecker &Self;
  13314. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  13315. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  13316. };
  13317. /// RAII object wrapping the visitation of a subexpression which we might
  13318. /// choose to evaluate as a constant. If any subexpression is evaluated and
  13319. /// found to be non-constant, this allows us to suppress the evaluation of
  13320. /// the outer expression.
  13321. class EvaluationTracker {
  13322. public:
  13323. EvaluationTracker(SequenceChecker &Self)
  13324. : Self(Self), Prev(Self.EvalTracker) {
  13325. Self.EvalTracker = this;
  13326. }
  13327. ~EvaluationTracker() {
  13328. Self.EvalTracker = Prev;
  13329. if (Prev)
  13330. Prev->EvalOK &= EvalOK;
  13331. }
  13332. bool evaluate(const Expr *E, bool &Result) {
  13333. if (!EvalOK || E->isValueDependent())
  13334. return false;
  13335. EvalOK = E->EvaluateAsBooleanCondition(
  13336. Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
  13337. return EvalOK;
  13338. }
  13339. private:
  13340. SequenceChecker &Self;
  13341. EvaluationTracker *Prev;
  13342. bool EvalOK = true;
  13343. } *EvalTracker = nullptr;
  13344. /// Find the object which is produced by the specified expression,
  13345. /// if any.
  13346. Object getObject(const Expr *E, bool Mod) const {
  13347. E = E->IgnoreParenCasts();
  13348. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  13349. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  13350. return getObject(UO->getSubExpr(), Mod);
  13351. } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  13352. if (BO->getOpcode() == BO_Comma)
  13353. return getObject(BO->getRHS(), Mod);
  13354. if (Mod && BO->isAssignmentOp())
  13355. return getObject(BO->getLHS(), Mod);
  13356. } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  13357. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  13358. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  13359. return ME->getMemberDecl();
  13360. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  13361. // FIXME: If this is a reference, map through to its value.
  13362. return DRE->getDecl();
  13363. return nullptr;
  13364. }
  13365. /// Note that an object \p O was modified or used by an expression
  13366. /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
  13367. /// the object \p O as obtained via the \p UsageMap.
  13368. void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
  13369. // Get the old usage for the given object and usage kind.
  13370. Usage &U = UI.Uses[UK];
  13371. if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
  13372. // If we have a modification as side effect and are in a sequenced
  13373. // subexpression, save the old Usage so that we can restore it later
  13374. // in SequencedSubexpression::~SequencedSubexpression.
  13375. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  13376. ModAsSideEffect->push_back(std::make_pair(O, U));
  13377. // Then record the new usage with the current sequencing region.
  13378. U.UsageExpr = UsageExpr;
  13379. U.Seq = Region;
  13380. }
  13381. }
  13382. /// Check whether a modification or use of an object \p O in an expression
  13383. /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
  13384. /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
  13385. /// \p IsModMod is true when we are checking for a mod-mod unsequenced
  13386. /// usage and false we are checking for a mod-use unsequenced usage.
  13387. void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
  13388. UsageKind OtherKind, bool IsModMod) {
  13389. if (UI.Diagnosed)
  13390. return;
  13391. const Usage &U = UI.Uses[OtherKind];
  13392. if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
  13393. return;
  13394. const Expr *Mod = U.UsageExpr;
  13395. const Expr *ModOrUse = UsageExpr;
  13396. if (OtherKind == UK_Use)
  13397. std::swap(Mod, ModOrUse);
  13398. SemaRef.DiagRuntimeBehavior(
  13399. Mod->getExprLoc(), {Mod, ModOrUse},
  13400. SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
  13401. : diag::warn_unsequenced_mod_use)
  13402. << O << SourceRange(ModOrUse->getExprLoc()));
  13403. UI.Diagnosed = true;
  13404. }
  13405. // A note on note{Pre, Post}{Use, Mod}:
  13406. //
  13407. // (It helps to follow the algorithm with an expression such as
  13408. // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
  13409. // operations before C++17 and both are well-defined in C++17).
  13410. //
  13411. // When visiting a node which uses/modify an object we first call notePreUse
  13412. // or notePreMod before visiting its sub-expression(s). At this point the
  13413. // children of the current node have not yet been visited and so the eventual
  13414. // uses/modifications resulting from the children of the current node have not
  13415. // been recorded yet.
  13416. //
  13417. // We then visit the children of the current node. After that notePostUse or
  13418. // notePostMod is called. These will 1) detect an unsequenced modification
  13419. // as side effect (as in "k++ + k") and 2) add a new usage with the
  13420. // appropriate usage kind.
  13421. //
  13422. // We also have to be careful that some operation sequences modification as
  13423. // side effect as well (for example: || or ,). To account for this we wrap
  13424. // the visitation of such a sub-expression (for example: the LHS of || or ,)
  13425. // with SequencedSubexpression. SequencedSubexpression is an RAII object
  13426. // which record usages which are modifications as side effect, and then
  13427. // downgrade them (or more accurately restore the previous usage which was a
  13428. // modification as side effect) when exiting the scope of the sequenced
  13429. // subexpression.
  13430. void notePreUse(Object O, const Expr *UseExpr) {
  13431. UsageInfo &UI = UsageMap[O];
  13432. // Uses conflict with other modifications.
  13433. checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
  13434. }
  13435. void notePostUse(Object O, const Expr *UseExpr) {
  13436. UsageInfo &UI = UsageMap[O];
  13437. checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
  13438. /*IsModMod=*/false);
  13439. addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
  13440. }
  13441. void notePreMod(Object O, const Expr *ModExpr) {
  13442. UsageInfo &UI = UsageMap[O];
  13443. // Modifications conflict with other modifications and with uses.
  13444. checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
  13445. checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
  13446. }
  13447. void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
  13448. UsageInfo &UI = UsageMap[O];
  13449. checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
  13450. /*IsModMod=*/true);
  13451. addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
  13452. }
  13453. public:
  13454. SequenceChecker(Sema &S, const Expr *E,
  13455. SmallVectorImpl<const Expr *> &WorkList)
  13456. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  13457. Visit(E);
  13458. // Silence a -Wunused-private-field since WorkList is now unused.
  13459. // TODO: Evaluate if it can be used, and if not remove it.
  13460. (void)this->WorkList;
  13461. }
  13462. void VisitStmt(const Stmt *S) {
  13463. // Skip all statements which aren't expressions for now.
  13464. }
  13465. void VisitExpr(const Expr *E) {
  13466. // By default, just recurse to evaluated subexpressions.
  13467. Base::VisitStmt(E);
  13468. }
  13469. void VisitCastExpr(const CastExpr *E) {
  13470. Object O = Object();
  13471. if (E->getCastKind() == CK_LValueToRValue)
  13472. O = getObject(E->getSubExpr(), false);
  13473. if (O)
  13474. notePreUse(O, E);
  13475. VisitExpr(E);
  13476. if (O)
  13477. notePostUse(O, E);
  13478. }
  13479. void VisitSequencedExpressions(const Expr *SequencedBefore,
  13480. const Expr *SequencedAfter) {
  13481. SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
  13482. SequenceTree::Seq AfterRegion = Tree.allocate(Region);
  13483. SequenceTree::Seq OldRegion = Region;
  13484. {
  13485. SequencedSubexpression SeqBefore(*this);
  13486. Region = BeforeRegion;
  13487. Visit(SequencedBefore);
  13488. }
  13489. Region = AfterRegion;
  13490. Visit(SequencedAfter);
  13491. Region = OldRegion;
  13492. Tree.merge(BeforeRegion);
  13493. Tree.merge(AfterRegion);
  13494. }
  13495. void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
  13496. // C++17 [expr.sub]p1:
  13497. // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
  13498. // expression E1 is sequenced before the expression E2.
  13499. if (SemaRef.getLangOpts().CPlusPlus17)
  13500. VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
  13501. else {
  13502. Visit(ASE->getLHS());
  13503. Visit(ASE->getRHS());
  13504. }
  13505. }
  13506. void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
  13507. void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
  13508. void VisitBinPtrMem(const BinaryOperator *BO) {
  13509. // C++17 [expr.mptr.oper]p4:
  13510. // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
  13511. // the expression E1 is sequenced before the expression E2.
  13512. if (SemaRef.getLangOpts().CPlusPlus17)
  13513. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  13514. else {
  13515. Visit(BO->getLHS());
  13516. Visit(BO->getRHS());
  13517. }
  13518. }
  13519. void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
  13520. void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
  13521. void VisitBinShlShr(const BinaryOperator *BO) {
  13522. // C++17 [expr.shift]p4:
  13523. // The expression E1 is sequenced before the expression E2.
  13524. if (SemaRef.getLangOpts().CPlusPlus17)
  13525. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  13526. else {
  13527. Visit(BO->getLHS());
  13528. Visit(BO->getRHS());
  13529. }
  13530. }
  13531. void VisitBinComma(const BinaryOperator *BO) {
  13532. // C++11 [expr.comma]p1:
  13533. // Every value computation and side effect associated with the left
  13534. // expression is sequenced before every value computation and side
  13535. // effect associated with the right expression.
  13536. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  13537. }
  13538. void VisitBinAssign(const BinaryOperator *BO) {
  13539. SequenceTree::Seq RHSRegion;
  13540. SequenceTree::Seq LHSRegion;
  13541. if (SemaRef.getLangOpts().CPlusPlus17) {
  13542. RHSRegion = Tree.allocate(Region);
  13543. LHSRegion = Tree.allocate(Region);
  13544. } else {
  13545. RHSRegion = Region;
  13546. LHSRegion = Region;
  13547. }
  13548. SequenceTree::Seq OldRegion = Region;
  13549. // C++11 [expr.ass]p1:
  13550. // [...] the assignment is sequenced after the value computation
  13551. // of the right and left operands, [...]
  13552. //
  13553. // so check it before inspecting the operands and update the
  13554. // map afterwards.
  13555. Object O = getObject(BO->getLHS(), /*Mod=*/true);
  13556. if (O)
  13557. notePreMod(O, BO);
  13558. if (SemaRef.getLangOpts().CPlusPlus17) {
  13559. // C++17 [expr.ass]p1:
  13560. // [...] The right operand is sequenced before the left operand. [...]
  13561. {
  13562. SequencedSubexpression SeqBefore(*this);
  13563. Region = RHSRegion;
  13564. Visit(BO->getRHS());
  13565. }
  13566. Region = LHSRegion;
  13567. Visit(BO->getLHS());
  13568. if (O && isa<CompoundAssignOperator>(BO))
  13569. notePostUse(O, BO);
  13570. } else {
  13571. // C++11 does not specify any sequencing between the LHS and RHS.
  13572. Region = LHSRegion;
  13573. Visit(BO->getLHS());
  13574. if (O && isa<CompoundAssignOperator>(BO))
  13575. notePostUse(O, BO);
  13576. Region = RHSRegion;
  13577. Visit(BO->getRHS());
  13578. }
  13579. // C++11 [expr.ass]p1:
  13580. // the assignment is sequenced [...] before the value computation of the
  13581. // assignment expression.
  13582. // C11 6.5.16/3 has no such rule.
  13583. Region = OldRegion;
  13584. if (O)
  13585. notePostMod(O, BO,
  13586. SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  13587. : UK_ModAsSideEffect);
  13588. if (SemaRef.getLangOpts().CPlusPlus17) {
  13589. Tree.merge(RHSRegion);
  13590. Tree.merge(LHSRegion);
  13591. }
  13592. }
  13593. void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
  13594. VisitBinAssign(CAO);
  13595. }
  13596. void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  13597. void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  13598. void VisitUnaryPreIncDec(const UnaryOperator *UO) {
  13599. Object O = getObject(UO->getSubExpr(), true);
  13600. if (!O)
  13601. return VisitExpr(UO);
  13602. notePreMod(O, UO);
  13603. Visit(UO->getSubExpr());
  13604. // C++11 [expr.pre.incr]p1:
  13605. // the expression ++x is equivalent to x+=1
  13606. notePostMod(O, UO,
  13607. SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  13608. : UK_ModAsSideEffect);
  13609. }
  13610. void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  13611. void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  13612. void VisitUnaryPostIncDec(const UnaryOperator *UO) {
  13613. Object O = getObject(UO->getSubExpr(), true);
  13614. if (!O)
  13615. return VisitExpr(UO);
  13616. notePreMod(O, UO);
  13617. Visit(UO->getSubExpr());
  13618. notePostMod(O, UO, UK_ModAsSideEffect);
  13619. }
  13620. void VisitBinLOr(const BinaryOperator *BO) {
  13621. // C++11 [expr.log.or]p2:
  13622. // If the second expression is evaluated, every value computation and
  13623. // side effect associated with the first expression is sequenced before
  13624. // every value computation and side effect associated with the
  13625. // second expression.
  13626. SequenceTree::Seq LHSRegion = Tree.allocate(Region);
  13627. SequenceTree::Seq RHSRegion = Tree.allocate(Region);
  13628. SequenceTree::Seq OldRegion = Region;
  13629. EvaluationTracker Eval(*this);
  13630. {
  13631. SequencedSubexpression Sequenced(*this);
  13632. Region = LHSRegion;
  13633. Visit(BO->getLHS());
  13634. }
  13635. // C++11 [expr.log.or]p1:
  13636. // [...] the second operand is not evaluated if the first operand
  13637. // evaluates to true.
  13638. bool EvalResult = false;
  13639. bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
  13640. bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
  13641. if (ShouldVisitRHS) {
  13642. Region = RHSRegion;
  13643. Visit(BO->getRHS());
  13644. }
  13645. Region = OldRegion;
  13646. Tree.merge(LHSRegion);
  13647. Tree.merge(RHSRegion);
  13648. }
  13649. void VisitBinLAnd(const BinaryOperator *BO) {
  13650. // C++11 [expr.log.and]p2:
  13651. // If the second expression is evaluated, every value computation and
  13652. // side effect associated with the first expression is sequenced before
  13653. // every value computation and side effect associated with the
  13654. // second expression.
  13655. SequenceTree::Seq LHSRegion = Tree.allocate(Region);
  13656. SequenceTree::Seq RHSRegion = Tree.allocate(Region);
  13657. SequenceTree::Seq OldRegion = Region;
  13658. EvaluationTracker Eval(*this);
  13659. {
  13660. SequencedSubexpression Sequenced(*this);
  13661. Region = LHSRegion;
  13662. Visit(BO->getLHS());
  13663. }
  13664. // C++11 [expr.log.and]p1:
  13665. // [...] the second operand is not evaluated if the first operand is false.
  13666. bool EvalResult = false;
  13667. bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
  13668. bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
  13669. if (ShouldVisitRHS) {
  13670. Region = RHSRegion;
  13671. Visit(BO->getRHS());
  13672. }
  13673. Region = OldRegion;
  13674. Tree.merge(LHSRegion);
  13675. Tree.merge(RHSRegion);
  13676. }
  13677. void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
  13678. // C++11 [expr.cond]p1:
  13679. // [...] Every value computation and side effect associated with the first
  13680. // expression is sequenced before every value computation and side effect
  13681. // associated with the second or third expression.
  13682. SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
  13683. // No sequencing is specified between the true and false expression.
  13684. // However since exactly one of both is going to be evaluated we can
  13685. // consider them to be sequenced. This is needed to avoid warning on
  13686. // something like "x ? y+= 1 : y += 2;" in the case where we will visit
  13687. // both the true and false expressions because we can't evaluate x.
  13688. // This will still allow us to detect an expression like (pre C++17)
  13689. // "(x ? y += 1 : y += 2) = y".
  13690. //
  13691. // We don't wrap the visitation of the true and false expression with
  13692. // SequencedSubexpression because we don't want to downgrade modifications
  13693. // as side effect in the true and false expressions after the visition
  13694. // is done. (for example in the expression "(x ? y++ : y++) + y" we should
  13695. // not warn between the two "y++", but we should warn between the "y++"
  13696. // and the "y".
  13697. SequenceTree::Seq TrueRegion = Tree.allocate(Region);
  13698. SequenceTree::Seq FalseRegion = Tree.allocate(Region);
  13699. SequenceTree::Seq OldRegion = Region;
  13700. EvaluationTracker Eval(*this);
  13701. {
  13702. SequencedSubexpression Sequenced(*this);
  13703. Region = ConditionRegion;
  13704. Visit(CO->getCond());
  13705. }
  13706. // C++11 [expr.cond]p1:
  13707. // [...] The first expression is contextually converted to bool (Clause 4).
  13708. // It is evaluated and if it is true, the result of the conditional
  13709. // expression is the value of the second expression, otherwise that of the
  13710. // third expression. Only one of the second and third expressions is
  13711. // evaluated. [...]
  13712. bool EvalResult = false;
  13713. bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
  13714. bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
  13715. bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
  13716. if (ShouldVisitTrueExpr) {
  13717. Region = TrueRegion;
  13718. Visit(CO->getTrueExpr());
  13719. }
  13720. if (ShouldVisitFalseExpr) {
  13721. Region = FalseRegion;
  13722. Visit(CO->getFalseExpr());
  13723. }
  13724. Region = OldRegion;
  13725. Tree.merge(ConditionRegion);
  13726. Tree.merge(TrueRegion);
  13727. Tree.merge(FalseRegion);
  13728. }
  13729. void VisitCallExpr(const CallExpr *CE) {
  13730. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  13731. if (CE->isUnevaluatedBuiltinCall(Context))
  13732. return;
  13733. // C++11 [intro.execution]p15:
  13734. // When calling a function [...], every value computation and side effect
  13735. // associated with any argument expression, or with the postfix expression
  13736. // designating the called function, is sequenced before execution of every
  13737. // expression or statement in the body of the function [and thus before
  13738. // the value computation of its result].
  13739. SequencedSubexpression Sequenced(*this);
  13740. SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
  13741. // C++17 [expr.call]p5
  13742. // The postfix-expression is sequenced before each expression in the
  13743. // expression-list and any default argument. [...]
  13744. SequenceTree::Seq CalleeRegion;
  13745. SequenceTree::Seq OtherRegion;
  13746. if (SemaRef.getLangOpts().CPlusPlus17) {
  13747. CalleeRegion = Tree.allocate(Region);
  13748. OtherRegion = Tree.allocate(Region);
  13749. } else {
  13750. CalleeRegion = Region;
  13751. OtherRegion = Region;
  13752. }
  13753. SequenceTree::Seq OldRegion = Region;
  13754. // Visit the callee expression first.
  13755. Region = CalleeRegion;
  13756. if (SemaRef.getLangOpts().CPlusPlus17) {
  13757. SequencedSubexpression Sequenced(*this);
  13758. Visit(CE->getCallee());
  13759. } else {
  13760. Visit(CE->getCallee());
  13761. }
  13762. // Then visit the argument expressions.
  13763. Region = OtherRegion;
  13764. for (const Expr *Argument : CE->arguments())
  13765. Visit(Argument);
  13766. Region = OldRegion;
  13767. if (SemaRef.getLangOpts().CPlusPlus17) {
  13768. Tree.merge(CalleeRegion);
  13769. Tree.merge(OtherRegion);
  13770. }
  13771. });
  13772. }
  13773. void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
  13774. // C++17 [over.match.oper]p2:
  13775. // [...] the operator notation is first transformed to the equivalent
  13776. // function-call notation as summarized in Table 12 (where @ denotes one
  13777. // of the operators covered in the specified subclause). However, the
  13778. // operands are sequenced in the order prescribed for the built-in
  13779. // operator (Clause 8).
  13780. //
  13781. // From the above only overloaded binary operators and overloaded call
  13782. // operators have sequencing rules in C++17 that we need to handle
  13783. // separately.
  13784. if (!SemaRef.getLangOpts().CPlusPlus17 ||
  13785. (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
  13786. return VisitCallExpr(CXXOCE);
  13787. enum {
  13788. NoSequencing,
  13789. LHSBeforeRHS,
  13790. RHSBeforeLHS,
  13791. LHSBeforeRest
  13792. } SequencingKind;
  13793. switch (CXXOCE->getOperator()) {
  13794. case OO_Equal:
  13795. case OO_PlusEqual:
  13796. case OO_MinusEqual:
  13797. case OO_StarEqual:
  13798. case OO_SlashEqual:
  13799. case OO_PercentEqual:
  13800. case OO_CaretEqual:
  13801. case OO_AmpEqual:
  13802. case OO_PipeEqual:
  13803. case OO_LessLessEqual:
  13804. case OO_GreaterGreaterEqual:
  13805. SequencingKind = RHSBeforeLHS;
  13806. break;
  13807. case OO_LessLess:
  13808. case OO_GreaterGreater:
  13809. case OO_AmpAmp:
  13810. case OO_PipePipe:
  13811. case OO_Comma:
  13812. case OO_ArrowStar:
  13813. case OO_Subscript:
  13814. SequencingKind = LHSBeforeRHS;
  13815. break;
  13816. case OO_Call:
  13817. SequencingKind = LHSBeforeRest;
  13818. break;
  13819. default:
  13820. SequencingKind = NoSequencing;
  13821. break;
  13822. }
  13823. if (SequencingKind == NoSequencing)
  13824. return VisitCallExpr(CXXOCE);
  13825. // This is a call, so all subexpressions are sequenced before the result.
  13826. SequencedSubexpression Sequenced(*this);
  13827. SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
  13828. assert(SemaRef.getLangOpts().CPlusPlus17 &&
  13829. "Should only get there with C++17 and above!");
  13830. assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
  13831. "Should only get there with an overloaded binary operator"
  13832. " or an overloaded call operator!");
  13833. if (SequencingKind == LHSBeforeRest) {
  13834. assert(CXXOCE->getOperator() == OO_Call &&
  13835. "We should only have an overloaded call operator here!");
  13836. // This is very similar to VisitCallExpr, except that we only have the
  13837. // C++17 case. The postfix-expression is the first argument of the
  13838. // CXXOperatorCallExpr. The expressions in the expression-list, if any,
  13839. // are in the following arguments.
  13840. //
  13841. // Note that we intentionally do not visit the callee expression since
  13842. // it is just a decayed reference to a function.
  13843. SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
  13844. SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
  13845. SequenceTree::Seq OldRegion = Region;
  13846. assert(CXXOCE->getNumArgs() >= 1 &&
  13847. "An overloaded call operator must have at least one argument"
  13848. " for the postfix-expression!");
  13849. const Expr *PostfixExpr = CXXOCE->getArgs()[0];
  13850. llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
  13851. CXXOCE->getNumArgs() - 1);
  13852. // Visit the postfix-expression first.
  13853. {
  13854. Region = PostfixExprRegion;
  13855. SequencedSubexpression Sequenced(*this);
  13856. Visit(PostfixExpr);
  13857. }
  13858. // Then visit the argument expressions.
  13859. Region = ArgsRegion;
  13860. for (const Expr *Arg : Args)
  13861. Visit(Arg);
  13862. Region = OldRegion;
  13863. Tree.merge(PostfixExprRegion);
  13864. Tree.merge(ArgsRegion);
  13865. } else {
  13866. assert(CXXOCE->getNumArgs() == 2 &&
  13867. "Should only have two arguments here!");
  13868. assert((SequencingKind == LHSBeforeRHS ||
  13869. SequencingKind == RHSBeforeLHS) &&
  13870. "Unexpected sequencing kind!");
  13871. // We do not visit the callee expression since it is just a decayed
  13872. // reference to a function.
  13873. const Expr *E1 = CXXOCE->getArg(0);
  13874. const Expr *E2 = CXXOCE->getArg(1);
  13875. if (SequencingKind == RHSBeforeLHS)
  13876. std::swap(E1, E2);
  13877. return VisitSequencedExpressions(E1, E2);
  13878. }
  13879. });
  13880. }
  13881. void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
  13882. // This is a call, so all subexpressions are sequenced before the result.
  13883. SequencedSubexpression Sequenced(*this);
  13884. if (!CCE->isListInitialization())
  13885. return VisitExpr(CCE);
  13886. // In C++11, list initializations are sequenced.
  13887. SmallVector<SequenceTree::Seq, 32> Elts;
  13888. SequenceTree::Seq Parent = Region;
  13889. for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
  13890. E = CCE->arg_end();
  13891. I != E; ++I) {
  13892. Region = Tree.allocate(Parent);
  13893. Elts.push_back(Region);
  13894. Visit(*I);
  13895. }
  13896. // Forget that the initializers are sequenced.
  13897. Region = Parent;
  13898. for (unsigned I = 0; I < Elts.size(); ++I)
  13899. Tree.merge(Elts[I]);
  13900. }
  13901. void VisitInitListExpr(const InitListExpr *ILE) {
  13902. if (!SemaRef.getLangOpts().CPlusPlus11)
  13903. return VisitExpr(ILE);
  13904. // In C++11, list initializations are sequenced.
  13905. SmallVector<SequenceTree::Seq, 32> Elts;
  13906. SequenceTree::Seq Parent = Region;
  13907. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  13908. const Expr *E = ILE->getInit(I);
  13909. if (!E)
  13910. continue;
  13911. Region = Tree.allocate(Parent);
  13912. Elts.push_back(Region);
  13913. Visit(E);
  13914. }
  13915. // Forget that the initializers are sequenced.
  13916. Region = Parent;
  13917. for (unsigned I = 0; I < Elts.size(); ++I)
  13918. Tree.merge(Elts[I]);
  13919. }
  13920. };
  13921. } // namespace
  13922. void Sema::CheckUnsequencedOperations(const Expr *E) {
  13923. SmallVector<const Expr *, 8> WorkList;
  13924. WorkList.push_back(E);
  13925. while (!WorkList.empty()) {
  13926. const Expr *Item = WorkList.pop_back_val();
  13927. SequenceChecker(*this, Item, WorkList);
  13928. }
  13929. }
  13930. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  13931. bool IsConstexpr) {
  13932. llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
  13933. IsConstexpr || isa<ConstantExpr>(E));
  13934. CheckImplicitConversions(E, CheckLoc);
  13935. if (!E->isInstantiationDependent())
  13936. CheckUnsequencedOperations(E);
  13937. if (!IsConstexpr && !E->isValueDependent())
  13938. CheckForIntOverflow(E);
  13939. DiagnoseMisalignedMembers();
  13940. }
  13941. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  13942. FieldDecl *BitField,
  13943. Expr *Init) {
  13944. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  13945. }
  13946. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  13947. SourceLocation Loc) {
  13948. if (!PType->isVariablyModifiedType())
  13949. return;
  13950. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  13951. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  13952. return;
  13953. }
  13954. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  13955. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  13956. return;
  13957. }
  13958. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  13959. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  13960. return;
  13961. }
  13962. const ArrayType *AT = S.Context.getAsArrayType(PType);
  13963. if (!AT)
  13964. return;
  13965. if (AT->getSizeModifier() != ArrayType::Star) {
  13966. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  13967. return;
  13968. }
  13969. S.Diag(Loc, diag::err_array_star_in_function_definition);
  13970. }
  13971. /// CheckParmsForFunctionDef - Check that the parameters of the given
  13972. /// function are appropriate for the definition of a function. This
  13973. /// takes care of any checks that cannot be performed on the
  13974. /// declaration itself, e.g., that the types of each of the function
  13975. /// parameters are complete.
  13976. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  13977. bool CheckParameterNames) {
  13978. bool HasInvalidParm = false;
  13979. for (ParmVarDecl *Param : Parameters) {
  13980. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  13981. // function declarator that is part of a function definition of
  13982. // that function shall not have incomplete type.
  13983. //
  13984. // This is also C++ [dcl.fct]p6.
  13985. if (!Param->isInvalidDecl() &&
  13986. RequireCompleteType(Param->getLocation(), Param->getType(),
  13987. diag::err_typecheck_decl_incomplete_type)) {
  13988. Param->setInvalidDecl();
  13989. HasInvalidParm = true;
  13990. }
  13991. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  13992. // declaration of each parameter shall include an identifier.
  13993. if (CheckParameterNames && Param->getIdentifier() == nullptr &&
  13994. !Param->isImplicit() && !getLangOpts().CPlusPlus) {
  13995. // Diagnose this as an extension in C17 and earlier.
  13996. if (!getLangOpts().C2x)
  13997. Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
  13998. }
  13999. // C99 6.7.5.3p12:
  14000. // If the function declarator is not part of a definition of that
  14001. // function, parameters may have incomplete type and may use the [*]
  14002. // notation in their sequences of declarator specifiers to specify
  14003. // variable length array types.
  14004. QualType PType = Param->getOriginalType();
  14005. // FIXME: This diagnostic should point the '[*]' if source-location
  14006. // information is added for it.
  14007. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  14008. // If the parameter is a c++ class type and it has to be destructed in the
  14009. // callee function, declare the destructor so that it can be called by the
  14010. // callee function. Do not perform any direct access check on the dtor here.
  14011. if (!Param->isInvalidDecl()) {
  14012. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  14013. if (!ClassDecl->isInvalidDecl() &&
  14014. !ClassDecl->hasIrrelevantDestructor() &&
  14015. !ClassDecl->isDependentContext() &&
  14016. ClassDecl->isParamDestroyedInCallee()) {
  14017. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  14018. MarkFunctionReferenced(Param->getLocation(), Destructor);
  14019. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  14020. }
  14021. }
  14022. }
  14023. // Parameters with the pass_object_size attribute only need to be marked
  14024. // constant at function definitions. Because we lack information about
  14025. // whether we're on a declaration or definition when we're instantiating the
  14026. // attribute, we need to check for constness here.
  14027. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  14028. if (!Param->getType().isConstQualified())
  14029. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  14030. << Attr->getSpelling() << 1;
  14031. // Check for parameter names shadowing fields from the class.
  14032. if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
  14033. // The owning context for the parameter should be the function, but we
  14034. // want to see if this function's declaration context is a record.
  14035. DeclContext *DC = Param->getDeclContext();
  14036. if (DC && DC->isFunctionOrMethod()) {
  14037. if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
  14038. CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
  14039. RD, /*DeclIsField*/ false);
  14040. }
  14041. }
  14042. }
  14043. return HasInvalidParm;
  14044. }
  14045. std::optional<std::pair<
  14046. CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
  14047. *E,
  14048. ASTContext
  14049. &Ctx);
  14050. /// Compute the alignment and offset of the base class object given the
  14051. /// derived-to-base cast expression and the alignment and offset of the derived
  14052. /// class object.
  14053. static std::pair<CharUnits, CharUnits>
  14054. getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
  14055. CharUnits BaseAlignment, CharUnits Offset,
  14056. ASTContext &Ctx) {
  14057. for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
  14058. ++PathI) {
  14059. const CXXBaseSpecifier *Base = *PathI;
  14060. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  14061. if (Base->isVirtual()) {
  14062. // The complete object may have a lower alignment than the non-virtual
  14063. // alignment of the base, in which case the base may be misaligned. Choose
  14064. // the smaller of the non-virtual alignment and BaseAlignment, which is a
  14065. // conservative lower bound of the complete object alignment.
  14066. CharUnits NonVirtualAlignment =
  14067. Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
  14068. BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
  14069. Offset = CharUnits::Zero();
  14070. } else {
  14071. const ASTRecordLayout &RL =
  14072. Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
  14073. Offset += RL.getBaseClassOffset(BaseDecl);
  14074. }
  14075. DerivedType = Base->getType();
  14076. }
  14077. return std::make_pair(BaseAlignment, Offset);
  14078. }
  14079. /// Compute the alignment and offset of a binary additive operator.
  14080. static std::optional<std::pair<CharUnits, CharUnits>>
  14081. getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
  14082. bool IsSub, ASTContext &Ctx) {
  14083. QualType PointeeType = PtrE->getType()->getPointeeType();
  14084. if (!PointeeType->isConstantSizeType())
  14085. return std::nullopt;
  14086. auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
  14087. if (!P)
  14088. return std::nullopt;
  14089. CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
  14090. if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
  14091. CharUnits Offset = EltSize * IdxRes->getExtValue();
  14092. if (IsSub)
  14093. Offset = -Offset;
  14094. return std::make_pair(P->first, P->second + Offset);
  14095. }
  14096. // If the integer expression isn't a constant expression, compute the lower
  14097. // bound of the alignment using the alignment and offset of the pointer
  14098. // expression and the element size.
  14099. return std::make_pair(
  14100. P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
  14101. CharUnits::Zero());
  14102. }
  14103. /// This helper function takes an lvalue expression and returns the alignment of
  14104. /// a VarDecl and a constant offset from the VarDecl.
  14105. std::optional<std::pair<
  14106. CharUnits,
  14107. CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E,
  14108. ASTContext &Ctx) {
  14109. E = E->IgnoreParens();
  14110. switch (E->getStmtClass()) {
  14111. default:
  14112. break;
  14113. case Stmt::CStyleCastExprClass:
  14114. case Stmt::CXXStaticCastExprClass:
  14115. case Stmt::ImplicitCastExprClass: {
  14116. auto *CE = cast<CastExpr>(E);
  14117. const Expr *From = CE->getSubExpr();
  14118. switch (CE->getCastKind()) {
  14119. default:
  14120. break;
  14121. case CK_NoOp:
  14122. return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
  14123. case CK_UncheckedDerivedToBase:
  14124. case CK_DerivedToBase: {
  14125. auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
  14126. if (!P)
  14127. break;
  14128. return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
  14129. P->second, Ctx);
  14130. }
  14131. }
  14132. break;
  14133. }
  14134. case Stmt::ArraySubscriptExprClass: {
  14135. auto *ASE = cast<ArraySubscriptExpr>(E);
  14136. return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
  14137. false, Ctx);
  14138. }
  14139. case Stmt::DeclRefExprClass: {
  14140. if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
  14141. // FIXME: If VD is captured by copy or is an escaping __block variable,
  14142. // use the alignment of VD's type.
  14143. if (!VD->getType()->isReferenceType())
  14144. return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
  14145. if (VD->hasInit())
  14146. return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
  14147. }
  14148. break;
  14149. }
  14150. case Stmt::MemberExprClass: {
  14151. auto *ME = cast<MemberExpr>(E);
  14152. auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  14153. if (!FD || FD->getType()->isReferenceType() ||
  14154. FD->getParent()->isInvalidDecl())
  14155. break;
  14156. std::optional<std::pair<CharUnits, CharUnits>> P;
  14157. if (ME->isArrow())
  14158. P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
  14159. else
  14160. P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
  14161. if (!P)
  14162. break;
  14163. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
  14164. uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
  14165. return std::make_pair(P->first,
  14166. P->second + CharUnits::fromQuantity(Offset));
  14167. }
  14168. case Stmt::UnaryOperatorClass: {
  14169. auto *UO = cast<UnaryOperator>(E);
  14170. switch (UO->getOpcode()) {
  14171. default:
  14172. break;
  14173. case UO_Deref:
  14174. return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
  14175. }
  14176. break;
  14177. }
  14178. case Stmt::BinaryOperatorClass: {
  14179. auto *BO = cast<BinaryOperator>(E);
  14180. auto Opcode = BO->getOpcode();
  14181. switch (Opcode) {
  14182. default:
  14183. break;
  14184. case BO_Comma:
  14185. return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
  14186. }
  14187. break;
  14188. }
  14189. }
  14190. return std::nullopt;
  14191. }
  14192. /// This helper function takes a pointer expression and returns the alignment of
  14193. /// a VarDecl and a constant offset from the VarDecl.
  14194. std::optional<std::pair<
  14195. CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
  14196. *E,
  14197. ASTContext
  14198. &Ctx) {
  14199. E = E->IgnoreParens();
  14200. switch (E->getStmtClass()) {
  14201. default:
  14202. break;
  14203. case Stmt::CStyleCastExprClass:
  14204. case Stmt::CXXStaticCastExprClass:
  14205. case Stmt::ImplicitCastExprClass: {
  14206. auto *CE = cast<CastExpr>(E);
  14207. const Expr *From = CE->getSubExpr();
  14208. switch (CE->getCastKind()) {
  14209. default:
  14210. break;
  14211. case CK_NoOp:
  14212. return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
  14213. case CK_ArrayToPointerDecay:
  14214. return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
  14215. case CK_UncheckedDerivedToBase:
  14216. case CK_DerivedToBase: {
  14217. auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
  14218. if (!P)
  14219. break;
  14220. return getDerivedToBaseAlignmentAndOffset(
  14221. CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
  14222. }
  14223. }
  14224. break;
  14225. }
  14226. case Stmt::CXXThisExprClass: {
  14227. auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
  14228. CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
  14229. return std::make_pair(Alignment, CharUnits::Zero());
  14230. }
  14231. case Stmt::UnaryOperatorClass: {
  14232. auto *UO = cast<UnaryOperator>(E);
  14233. if (UO->getOpcode() == UO_AddrOf)
  14234. return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
  14235. break;
  14236. }
  14237. case Stmt::BinaryOperatorClass: {
  14238. auto *BO = cast<BinaryOperator>(E);
  14239. auto Opcode = BO->getOpcode();
  14240. switch (Opcode) {
  14241. default:
  14242. break;
  14243. case BO_Add:
  14244. case BO_Sub: {
  14245. const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
  14246. if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
  14247. std::swap(LHS, RHS);
  14248. return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
  14249. Ctx);
  14250. }
  14251. case BO_Comma:
  14252. return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
  14253. }
  14254. break;
  14255. }
  14256. }
  14257. return std::nullopt;
  14258. }
  14259. static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
  14260. // See if we can compute the alignment of a VarDecl and an offset from it.
  14261. std::optional<std::pair<CharUnits, CharUnits>> P =
  14262. getBaseAlignmentAndOffsetFromPtr(E, S.Context);
  14263. if (P)
  14264. return P->first.alignmentAtOffset(P->second);
  14265. // If that failed, return the type's alignment.
  14266. return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
  14267. }
  14268. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  14269. /// pointer cast increases the alignment requirements.
  14270. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  14271. // This is actually a lot of work to potentially be doing on every
  14272. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  14273. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  14274. return;
  14275. // Ignore dependent types.
  14276. if (T->isDependentType() || Op->getType()->isDependentType())
  14277. return;
  14278. // Require that the destination be a pointer type.
  14279. const PointerType *DestPtr = T->getAs<PointerType>();
  14280. if (!DestPtr) return;
  14281. // If the destination has alignment 1, we're done.
  14282. QualType DestPointee = DestPtr->getPointeeType();
  14283. if (DestPointee->isIncompleteType()) return;
  14284. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  14285. if (DestAlign.isOne()) return;
  14286. // Require that the source be a pointer type.
  14287. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  14288. if (!SrcPtr) return;
  14289. QualType SrcPointee = SrcPtr->getPointeeType();
  14290. // Explicitly allow casts from cv void*. We already implicitly
  14291. // allowed casts to cv void*, since they have alignment 1.
  14292. // Also allow casts involving incomplete types, which implicitly
  14293. // includes 'void'.
  14294. if (SrcPointee->isIncompleteType()) return;
  14295. CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
  14296. if (SrcAlign >= DestAlign) return;
  14297. Diag(TRange.getBegin(), diag::warn_cast_align)
  14298. << Op->getType() << T
  14299. << static_cast<unsigned>(SrcAlign.getQuantity())
  14300. << static_cast<unsigned>(DestAlign.getQuantity())
  14301. << TRange << Op->getSourceRange();
  14302. }
  14303. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  14304. const ArraySubscriptExpr *ASE,
  14305. bool AllowOnePastEnd, bool IndexNegated) {
  14306. // Already diagnosed by the constant evaluator.
  14307. if (isConstantEvaluated())
  14308. return;
  14309. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  14310. if (IndexExpr->isValueDependent())
  14311. return;
  14312. const Type *EffectiveType =
  14313. BaseExpr->getType()->getPointeeOrArrayElementType();
  14314. BaseExpr = BaseExpr->IgnoreParenCasts();
  14315. const ConstantArrayType *ArrayTy =
  14316. Context.getAsConstantArrayType(BaseExpr->getType());
  14317. LangOptions::StrictFlexArraysLevelKind
  14318. StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
  14319. const Type *BaseType =
  14320. ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
  14321. bool IsUnboundedArray =
  14322. BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
  14323. Context, StrictFlexArraysLevel,
  14324. /*IgnoreTemplateOrMacroSubstitution=*/true);
  14325. if (EffectiveType->isDependentType() ||
  14326. (!IsUnboundedArray && BaseType->isDependentType()))
  14327. return;
  14328. Expr::EvalResult Result;
  14329. if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
  14330. return;
  14331. llvm::APSInt index = Result.Val.getInt();
  14332. if (IndexNegated) {
  14333. index.setIsUnsigned(false);
  14334. index = -index;
  14335. }
  14336. if (IsUnboundedArray) {
  14337. if (EffectiveType->isFunctionType())
  14338. return;
  14339. if (index.isUnsigned() || !index.isNegative()) {
  14340. const auto &ASTC = getASTContext();
  14341. unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
  14342. EffectiveType->getCanonicalTypeInternal().getAddressSpace());
  14343. if (index.getBitWidth() < AddrBits)
  14344. index = index.zext(AddrBits);
  14345. std::optional<CharUnits> ElemCharUnits =
  14346. ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
  14347. // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
  14348. // pointer) bounds-checking isn't meaningful.
  14349. if (!ElemCharUnits)
  14350. return;
  14351. llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
  14352. // If index has more active bits than address space, we already know
  14353. // we have a bounds violation to warn about. Otherwise, compute
  14354. // address of (index + 1)th element, and warn about bounds violation
  14355. // only if that address exceeds address space.
  14356. if (index.getActiveBits() <= AddrBits) {
  14357. bool Overflow;
  14358. llvm::APInt Product(index);
  14359. Product += 1;
  14360. Product = Product.umul_ov(ElemBytes, Overflow);
  14361. if (!Overflow && Product.getActiveBits() <= AddrBits)
  14362. return;
  14363. }
  14364. // Need to compute max possible elements in address space, since that
  14365. // is included in diag message.
  14366. llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
  14367. MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
  14368. MaxElems += 1;
  14369. ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
  14370. MaxElems = MaxElems.udiv(ElemBytes);
  14371. unsigned DiagID =
  14372. ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
  14373. : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
  14374. // Diag message shows element size in bits and in "bytes" (platform-
  14375. // dependent CharUnits)
  14376. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  14377. PDiag(DiagID)
  14378. << toString(index, 10, true) << AddrBits
  14379. << (unsigned)ASTC.toBits(*ElemCharUnits)
  14380. << toString(ElemBytes, 10, false)
  14381. << toString(MaxElems, 10, false)
  14382. << (unsigned)MaxElems.getLimitedValue(~0U)
  14383. << IndexExpr->getSourceRange());
  14384. const NamedDecl *ND = nullptr;
  14385. // Try harder to find a NamedDecl to point at in the note.
  14386. while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
  14387. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  14388. if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  14389. ND = DRE->getDecl();
  14390. if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
  14391. ND = ME->getMemberDecl();
  14392. if (ND)
  14393. DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
  14394. PDiag(diag::note_array_declared_here) << ND);
  14395. }
  14396. return;
  14397. }
  14398. if (index.isUnsigned() || !index.isNegative()) {
  14399. // It is possible that the type of the base expression after
  14400. // IgnoreParenCasts is incomplete, even though the type of the base
  14401. // expression before IgnoreParenCasts is complete (see PR39746 for an
  14402. // example). In this case we have no information about whether the array
  14403. // access exceeds the array bounds. However we can still diagnose an array
  14404. // access which precedes the array bounds.
  14405. if (BaseType->isIncompleteType())
  14406. return;
  14407. llvm::APInt size = ArrayTy->getSize();
  14408. if (BaseType != EffectiveType) {
  14409. // Make sure we're comparing apples to apples when comparing index to
  14410. // size.
  14411. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  14412. uint64_t array_typesize = Context.getTypeSize(BaseType);
  14413. // Handle ptrarith_typesize being zero, such as when casting to void*.
  14414. // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
  14415. if (!ptrarith_typesize)
  14416. ptrarith_typesize = Context.getCharWidth();
  14417. if (ptrarith_typesize != array_typesize) {
  14418. // There's a cast to a different size type involved.
  14419. uint64_t ratio = array_typesize / ptrarith_typesize;
  14420. // TODO: Be smarter about handling cases where array_typesize is not a
  14421. // multiple of ptrarith_typesize.
  14422. if (ptrarith_typesize * ratio == array_typesize)
  14423. size *= llvm::APInt(size.getBitWidth(), ratio);
  14424. }
  14425. }
  14426. if (size.getBitWidth() > index.getBitWidth())
  14427. index = index.zext(size.getBitWidth());
  14428. else if (size.getBitWidth() < index.getBitWidth())
  14429. size = size.zext(index.getBitWidth());
  14430. // For array subscripting the index must be less than size, but for pointer
  14431. // arithmetic also allow the index (offset) to be equal to size since
  14432. // computing the next address after the end of the array is legal and
  14433. // commonly done e.g. in C++ iterators and range-based for loops.
  14434. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  14435. return;
  14436. // Suppress the warning if the subscript expression (as identified by the
  14437. // ']' location) and the index expression are both from macro expansions
  14438. // within a system header.
  14439. if (ASE) {
  14440. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  14441. ASE->getRBracketLoc());
  14442. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  14443. SourceLocation IndexLoc =
  14444. SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
  14445. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  14446. return;
  14447. }
  14448. }
  14449. unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
  14450. : diag::warn_ptr_arith_exceeds_bounds;
  14451. unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
  14452. QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
  14453. DiagRuntimeBehavior(
  14454. BaseExpr->getBeginLoc(), BaseExpr,
  14455. PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar()
  14456. << CastMsg << CastMsgTy << IndexExpr->getSourceRange());
  14457. } else {
  14458. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  14459. if (!ASE) {
  14460. DiagID = diag::warn_ptr_arith_precedes_bounds;
  14461. if (index.isNegative()) index = -index;
  14462. }
  14463. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  14464. PDiag(DiagID) << toString(index, 10, true)
  14465. << IndexExpr->getSourceRange());
  14466. }
  14467. const NamedDecl *ND = nullptr;
  14468. // Try harder to find a NamedDecl to point at in the note.
  14469. while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
  14470. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  14471. if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  14472. ND = DRE->getDecl();
  14473. if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
  14474. ND = ME->getMemberDecl();
  14475. if (ND)
  14476. DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
  14477. PDiag(diag::note_array_declared_here) << ND);
  14478. }
  14479. void Sema::CheckArrayAccess(const Expr *expr) {
  14480. int AllowOnePastEnd = 0;
  14481. while (expr) {
  14482. expr = expr->IgnoreParenImpCasts();
  14483. switch (expr->getStmtClass()) {
  14484. case Stmt::ArraySubscriptExprClass: {
  14485. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  14486. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  14487. AllowOnePastEnd > 0);
  14488. expr = ASE->getBase();
  14489. break;
  14490. }
  14491. case Stmt::MemberExprClass: {
  14492. expr = cast<MemberExpr>(expr)->getBase();
  14493. break;
  14494. }
  14495. case Stmt::OMPArraySectionExprClass: {
  14496. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  14497. if (ASE->getLowerBound())
  14498. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  14499. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  14500. return;
  14501. }
  14502. case Stmt::UnaryOperatorClass: {
  14503. // Only unwrap the * and & unary operators
  14504. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  14505. expr = UO->getSubExpr();
  14506. switch (UO->getOpcode()) {
  14507. case UO_AddrOf:
  14508. AllowOnePastEnd++;
  14509. break;
  14510. case UO_Deref:
  14511. AllowOnePastEnd--;
  14512. break;
  14513. default:
  14514. return;
  14515. }
  14516. break;
  14517. }
  14518. case Stmt::ConditionalOperatorClass: {
  14519. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  14520. if (const Expr *lhs = cond->getLHS())
  14521. CheckArrayAccess(lhs);
  14522. if (const Expr *rhs = cond->getRHS())
  14523. CheckArrayAccess(rhs);
  14524. return;
  14525. }
  14526. case Stmt::CXXOperatorCallExprClass: {
  14527. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  14528. for (const auto *Arg : OCE->arguments())
  14529. CheckArrayAccess(Arg);
  14530. return;
  14531. }
  14532. default:
  14533. return;
  14534. }
  14535. }
  14536. }
  14537. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  14538. namespace {
  14539. struct RetainCycleOwner {
  14540. VarDecl *Variable = nullptr;
  14541. SourceRange Range;
  14542. SourceLocation Loc;
  14543. bool Indirect = false;
  14544. RetainCycleOwner() = default;
  14545. void setLocsFrom(Expr *e) {
  14546. Loc = e->getExprLoc();
  14547. Range = e->getSourceRange();
  14548. }
  14549. };
  14550. } // namespace
  14551. /// Consider whether capturing the given variable can possibly lead to
  14552. /// a retain cycle.
  14553. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  14554. // In ARC, it's captured strongly iff the variable has __strong
  14555. // lifetime. In MRR, it's captured strongly if the variable is
  14556. // __block and has an appropriate type.
  14557. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  14558. return false;
  14559. owner.Variable = var;
  14560. if (ref)
  14561. owner.setLocsFrom(ref);
  14562. return true;
  14563. }
  14564. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  14565. while (true) {
  14566. e = e->IgnoreParens();
  14567. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  14568. switch (cast->getCastKind()) {
  14569. case CK_BitCast:
  14570. case CK_LValueBitCast:
  14571. case CK_LValueToRValue:
  14572. case CK_ARCReclaimReturnedObject:
  14573. e = cast->getSubExpr();
  14574. continue;
  14575. default:
  14576. return false;
  14577. }
  14578. }
  14579. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  14580. ObjCIvarDecl *ivar = ref->getDecl();
  14581. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  14582. return false;
  14583. // Try to find a retain cycle in the base.
  14584. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  14585. return false;
  14586. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  14587. owner.Indirect = true;
  14588. return true;
  14589. }
  14590. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  14591. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  14592. if (!var) return false;
  14593. return considerVariable(var, ref, owner);
  14594. }
  14595. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  14596. if (member->isArrow()) return false;
  14597. // Don't count this as an indirect ownership.
  14598. e = member->getBase();
  14599. continue;
  14600. }
  14601. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  14602. // Only pay attention to pseudo-objects on property references.
  14603. ObjCPropertyRefExpr *pre
  14604. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  14605. ->IgnoreParens());
  14606. if (!pre) return false;
  14607. if (pre->isImplicitProperty()) return false;
  14608. ObjCPropertyDecl *property = pre->getExplicitProperty();
  14609. if (!property->isRetaining() &&
  14610. !(property->getPropertyIvarDecl() &&
  14611. property->getPropertyIvarDecl()->getType()
  14612. .getObjCLifetime() == Qualifiers::OCL_Strong))
  14613. return false;
  14614. owner.Indirect = true;
  14615. if (pre->isSuperReceiver()) {
  14616. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  14617. if (!owner.Variable)
  14618. return false;
  14619. owner.Loc = pre->getLocation();
  14620. owner.Range = pre->getSourceRange();
  14621. return true;
  14622. }
  14623. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  14624. ->getSourceExpr());
  14625. continue;
  14626. }
  14627. // Array ivars?
  14628. return false;
  14629. }
  14630. }
  14631. namespace {
  14632. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  14633. ASTContext &Context;
  14634. VarDecl *Variable;
  14635. Expr *Capturer = nullptr;
  14636. bool VarWillBeReased = false;
  14637. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  14638. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  14639. Context(Context), Variable(variable) {}
  14640. void VisitDeclRefExpr(DeclRefExpr *ref) {
  14641. if (ref->getDecl() == Variable && !Capturer)
  14642. Capturer = ref;
  14643. }
  14644. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  14645. if (Capturer) return;
  14646. Visit(ref->getBase());
  14647. if (Capturer && ref->isFreeIvar())
  14648. Capturer = ref;
  14649. }
  14650. void VisitBlockExpr(BlockExpr *block) {
  14651. // Look inside nested blocks
  14652. if (block->getBlockDecl()->capturesVariable(Variable))
  14653. Visit(block->getBlockDecl()->getBody());
  14654. }
  14655. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  14656. if (Capturer) return;
  14657. if (OVE->getSourceExpr())
  14658. Visit(OVE->getSourceExpr());
  14659. }
  14660. void VisitBinaryOperator(BinaryOperator *BinOp) {
  14661. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  14662. return;
  14663. Expr *LHS = BinOp->getLHS();
  14664. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  14665. if (DRE->getDecl() != Variable)
  14666. return;
  14667. if (Expr *RHS = BinOp->getRHS()) {
  14668. RHS = RHS->IgnoreParenCasts();
  14669. std::optional<llvm::APSInt> Value;
  14670. VarWillBeReased =
  14671. (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
  14672. *Value == 0);
  14673. }
  14674. }
  14675. }
  14676. };
  14677. } // namespace
  14678. /// Check whether the given argument is a block which captures a
  14679. /// variable.
  14680. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  14681. assert(owner.Variable && owner.Loc.isValid());
  14682. e = e->IgnoreParenCasts();
  14683. // Look through [^{...} copy] and Block_copy(^{...}).
  14684. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  14685. Selector Cmd = ME->getSelector();
  14686. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  14687. e = ME->getInstanceReceiver();
  14688. if (!e)
  14689. return nullptr;
  14690. e = e->IgnoreParenCasts();
  14691. }
  14692. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  14693. if (CE->getNumArgs() == 1) {
  14694. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  14695. if (Fn) {
  14696. const IdentifierInfo *FnI = Fn->getIdentifier();
  14697. if (FnI && FnI->isStr("_Block_copy")) {
  14698. e = CE->getArg(0)->IgnoreParenCasts();
  14699. }
  14700. }
  14701. }
  14702. }
  14703. BlockExpr *block = dyn_cast<BlockExpr>(e);
  14704. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  14705. return nullptr;
  14706. FindCaptureVisitor visitor(S.Context, owner.Variable);
  14707. visitor.Visit(block->getBlockDecl()->getBody());
  14708. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  14709. }
  14710. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  14711. RetainCycleOwner &owner) {
  14712. assert(capturer);
  14713. assert(owner.Variable && owner.Loc.isValid());
  14714. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  14715. << owner.Variable << capturer->getSourceRange();
  14716. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  14717. << owner.Indirect << owner.Range;
  14718. }
  14719. /// Check for a keyword selector that starts with the word 'add' or
  14720. /// 'set'.
  14721. static bool isSetterLikeSelector(Selector sel) {
  14722. if (sel.isUnarySelector()) return false;
  14723. StringRef str = sel.getNameForSlot(0);
  14724. while (!str.empty() && str.front() == '_') str = str.substr(1);
  14725. if (str.startswith("set"))
  14726. str = str.substr(3);
  14727. else if (str.startswith("add")) {
  14728. // Specially allow 'addOperationWithBlock:'.
  14729. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  14730. return false;
  14731. str = str.substr(3);
  14732. }
  14733. else
  14734. return false;
  14735. if (str.empty()) return true;
  14736. return !isLowercase(str.front());
  14737. }
  14738. static std::optional<int>
  14739. GetNSMutableArrayArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  14740. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  14741. Message->getReceiverInterface(),
  14742. NSAPI::ClassId_NSMutableArray);
  14743. if (!IsMutableArray) {
  14744. return std::nullopt;
  14745. }
  14746. Selector Sel = Message->getSelector();
  14747. std::optional<NSAPI::NSArrayMethodKind> MKOpt =
  14748. S.NSAPIObj->getNSArrayMethodKind(Sel);
  14749. if (!MKOpt) {
  14750. return std::nullopt;
  14751. }
  14752. NSAPI::NSArrayMethodKind MK = *MKOpt;
  14753. switch (MK) {
  14754. case NSAPI::NSMutableArr_addObject:
  14755. case NSAPI::NSMutableArr_insertObjectAtIndex:
  14756. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  14757. return 0;
  14758. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  14759. return 1;
  14760. default:
  14761. return std::nullopt;
  14762. }
  14763. return std::nullopt;
  14764. }
  14765. static std::optional<int>
  14766. GetNSMutableDictionaryArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  14767. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  14768. Message->getReceiverInterface(),
  14769. NSAPI::ClassId_NSMutableDictionary);
  14770. if (!IsMutableDictionary) {
  14771. return std::nullopt;
  14772. }
  14773. Selector Sel = Message->getSelector();
  14774. std::optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  14775. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  14776. if (!MKOpt) {
  14777. return std::nullopt;
  14778. }
  14779. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  14780. switch (MK) {
  14781. case NSAPI::NSMutableDict_setObjectForKey:
  14782. case NSAPI::NSMutableDict_setValueForKey:
  14783. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  14784. return 0;
  14785. default:
  14786. return std::nullopt;
  14787. }
  14788. return std::nullopt;
  14789. }
  14790. static std::optional<int> GetNSSetArgumentIndex(Sema &S,
  14791. ObjCMessageExpr *Message) {
  14792. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  14793. Message->getReceiverInterface(),
  14794. NSAPI::ClassId_NSMutableSet);
  14795. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  14796. Message->getReceiverInterface(),
  14797. NSAPI::ClassId_NSMutableOrderedSet);
  14798. if (!IsMutableSet && !IsMutableOrderedSet) {
  14799. return std::nullopt;
  14800. }
  14801. Selector Sel = Message->getSelector();
  14802. std::optional<NSAPI::NSSetMethodKind> MKOpt =
  14803. S.NSAPIObj->getNSSetMethodKind(Sel);
  14804. if (!MKOpt) {
  14805. return std::nullopt;
  14806. }
  14807. NSAPI::NSSetMethodKind MK = *MKOpt;
  14808. switch (MK) {
  14809. case NSAPI::NSMutableSet_addObject:
  14810. case NSAPI::NSOrderedSet_setObjectAtIndex:
  14811. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  14812. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  14813. return 0;
  14814. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  14815. return 1;
  14816. }
  14817. return std::nullopt;
  14818. }
  14819. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  14820. if (!Message->isInstanceMessage()) {
  14821. return;
  14822. }
  14823. std::optional<int> ArgOpt;
  14824. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  14825. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  14826. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  14827. return;
  14828. }
  14829. int ArgIndex = *ArgOpt;
  14830. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  14831. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  14832. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  14833. }
  14834. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  14835. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  14836. if (ArgRE->isObjCSelfExpr()) {
  14837. Diag(Message->getSourceRange().getBegin(),
  14838. diag::warn_objc_circular_container)
  14839. << ArgRE->getDecl() << StringRef("'super'");
  14840. }
  14841. }
  14842. } else {
  14843. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  14844. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  14845. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  14846. }
  14847. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  14848. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  14849. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  14850. ValueDecl *Decl = ReceiverRE->getDecl();
  14851. Diag(Message->getSourceRange().getBegin(),
  14852. diag::warn_objc_circular_container)
  14853. << Decl << Decl;
  14854. if (!ArgRE->isObjCSelfExpr()) {
  14855. Diag(Decl->getLocation(),
  14856. diag::note_objc_circular_container_declared_here)
  14857. << Decl;
  14858. }
  14859. }
  14860. }
  14861. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  14862. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  14863. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  14864. ObjCIvarDecl *Decl = IvarRE->getDecl();
  14865. Diag(Message->getSourceRange().getBegin(),
  14866. diag::warn_objc_circular_container)
  14867. << Decl << Decl;
  14868. Diag(Decl->getLocation(),
  14869. diag::note_objc_circular_container_declared_here)
  14870. << Decl;
  14871. }
  14872. }
  14873. }
  14874. }
  14875. }
  14876. /// Check a message send to see if it's likely to cause a retain cycle.
  14877. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  14878. // Only check instance methods whose selector looks like a setter.
  14879. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  14880. return;
  14881. // Try to find a variable that the receiver is strongly owned by.
  14882. RetainCycleOwner owner;
  14883. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  14884. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  14885. return;
  14886. } else {
  14887. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  14888. owner.Variable = getCurMethodDecl()->getSelfDecl();
  14889. owner.Loc = msg->getSuperLoc();
  14890. owner.Range = msg->getSuperLoc();
  14891. }
  14892. // Check whether the receiver is captured by any of the arguments.
  14893. const ObjCMethodDecl *MD = msg->getMethodDecl();
  14894. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  14895. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  14896. // noescape blocks should not be retained by the method.
  14897. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  14898. continue;
  14899. return diagnoseRetainCycle(*this, capturer, owner);
  14900. }
  14901. }
  14902. }
  14903. /// Check a property assign to see if it's likely to cause a retain cycle.
  14904. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  14905. RetainCycleOwner owner;
  14906. if (!findRetainCycleOwner(*this, receiver, owner))
  14907. return;
  14908. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  14909. diagnoseRetainCycle(*this, capturer, owner);
  14910. }
  14911. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  14912. RetainCycleOwner Owner;
  14913. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  14914. return;
  14915. // Because we don't have an expression for the variable, we have to set the
  14916. // location explicitly here.
  14917. Owner.Loc = Var->getLocation();
  14918. Owner.Range = Var->getSourceRange();
  14919. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  14920. diagnoseRetainCycle(*this, Capturer, Owner);
  14921. }
  14922. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  14923. Expr *RHS, bool isProperty) {
  14924. // Check if RHS is an Objective-C object literal, which also can get
  14925. // immediately zapped in a weak reference. Note that we explicitly
  14926. // allow ObjCStringLiterals, since those are designed to never really die.
  14927. RHS = RHS->IgnoreParenImpCasts();
  14928. // This enum needs to match with the 'select' in
  14929. // warn_objc_arc_literal_assign (off-by-1).
  14930. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  14931. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  14932. return false;
  14933. S.Diag(Loc, diag::warn_arc_literal_assign)
  14934. << (unsigned) Kind
  14935. << (isProperty ? 0 : 1)
  14936. << RHS->getSourceRange();
  14937. return true;
  14938. }
  14939. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  14940. Qualifiers::ObjCLifetime LT,
  14941. Expr *RHS, bool isProperty) {
  14942. // Strip off any implicit cast added to get to the one ARC-specific.
  14943. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  14944. if (cast->getCastKind() == CK_ARCConsumeObject) {
  14945. S.Diag(Loc, diag::warn_arc_retained_assign)
  14946. << (LT == Qualifiers::OCL_ExplicitNone)
  14947. << (isProperty ? 0 : 1)
  14948. << RHS->getSourceRange();
  14949. return true;
  14950. }
  14951. RHS = cast->getSubExpr();
  14952. }
  14953. if (LT == Qualifiers::OCL_Weak &&
  14954. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  14955. return true;
  14956. return false;
  14957. }
  14958. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  14959. QualType LHS, Expr *RHS) {
  14960. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  14961. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  14962. return false;
  14963. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  14964. return true;
  14965. return false;
  14966. }
  14967. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  14968. Expr *LHS, Expr *RHS) {
  14969. QualType LHSType;
  14970. // PropertyRef on LHS type need be directly obtained from
  14971. // its declaration as it has a PseudoType.
  14972. ObjCPropertyRefExpr *PRE
  14973. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  14974. if (PRE && !PRE->isImplicitProperty()) {
  14975. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  14976. if (PD)
  14977. LHSType = PD->getType();
  14978. }
  14979. if (LHSType.isNull())
  14980. LHSType = LHS->getType();
  14981. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  14982. if (LT == Qualifiers::OCL_Weak) {
  14983. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  14984. getCurFunction()->markSafeWeakUse(LHS);
  14985. }
  14986. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  14987. return;
  14988. // FIXME. Check for other life times.
  14989. if (LT != Qualifiers::OCL_None)
  14990. return;
  14991. if (PRE) {
  14992. if (PRE->isImplicitProperty())
  14993. return;
  14994. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  14995. if (!PD)
  14996. return;
  14997. unsigned Attributes = PD->getPropertyAttributes();
  14998. if (Attributes & ObjCPropertyAttribute::kind_assign) {
  14999. // when 'assign' attribute was not explicitly specified
  15000. // by user, ignore it and rely on property type itself
  15001. // for lifetime info.
  15002. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  15003. if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
  15004. LHSType->isObjCRetainableType())
  15005. return;
  15006. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  15007. if (cast->getCastKind() == CK_ARCConsumeObject) {
  15008. Diag(Loc, diag::warn_arc_retained_property_assign)
  15009. << RHS->getSourceRange();
  15010. return;
  15011. }
  15012. RHS = cast->getSubExpr();
  15013. }
  15014. } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
  15015. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  15016. return;
  15017. }
  15018. }
  15019. }
  15020. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  15021. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  15022. SourceLocation StmtLoc,
  15023. const NullStmt *Body) {
  15024. // Do not warn if the body is a macro that expands to nothing, e.g:
  15025. //
  15026. // #define CALL(x)
  15027. // if (condition)
  15028. // CALL(0);
  15029. if (Body->hasLeadingEmptyMacro())
  15030. return false;
  15031. // Get line numbers of statement and body.
  15032. bool StmtLineInvalid;
  15033. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  15034. &StmtLineInvalid);
  15035. if (StmtLineInvalid)
  15036. return false;
  15037. bool BodyLineInvalid;
  15038. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  15039. &BodyLineInvalid);
  15040. if (BodyLineInvalid)
  15041. return false;
  15042. // Warn if null statement and body are on the same line.
  15043. if (StmtLine != BodyLine)
  15044. return false;
  15045. return true;
  15046. }
  15047. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  15048. const Stmt *Body,
  15049. unsigned DiagID) {
  15050. // Since this is a syntactic check, don't emit diagnostic for template
  15051. // instantiations, this just adds noise.
  15052. if (CurrentInstantiationScope)
  15053. return;
  15054. // The body should be a null statement.
  15055. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  15056. if (!NBody)
  15057. return;
  15058. // Do the usual checks.
  15059. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  15060. return;
  15061. Diag(NBody->getSemiLoc(), DiagID);
  15062. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  15063. }
  15064. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  15065. const Stmt *PossibleBody) {
  15066. assert(!CurrentInstantiationScope); // Ensured by caller
  15067. SourceLocation StmtLoc;
  15068. const Stmt *Body;
  15069. unsigned DiagID;
  15070. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  15071. StmtLoc = FS->getRParenLoc();
  15072. Body = FS->getBody();
  15073. DiagID = diag::warn_empty_for_body;
  15074. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  15075. StmtLoc = WS->getRParenLoc();
  15076. Body = WS->getBody();
  15077. DiagID = diag::warn_empty_while_body;
  15078. } else
  15079. return; // Neither `for' nor `while'.
  15080. // The body should be a null statement.
  15081. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  15082. if (!NBody)
  15083. return;
  15084. // Skip expensive checks if diagnostic is disabled.
  15085. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  15086. return;
  15087. // Do the usual checks.
  15088. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  15089. return;
  15090. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  15091. // noise level low, emit diagnostics only if for/while is followed by a
  15092. // CompoundStmt, e.g.:
  15093. // for (int i = 0; i < n; i++);
  15094. // {
  15095. // a(i);
  15096. // }
  15097. // or if for/while is followed by a statement with more indentation
  15098. // than for/while itself:
  15099. // for (int i = 0; i < n; i++);
  15100. // a(i);
  15101. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  15102. if (!ProbableTypo) {
  15103. bool BodyColInvalid;
  15104. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  15105. PossibleBody->getBeginLoc(), &BodyColInvalid);
  15106. if (BodyColInvalid)
  15107. return;
  15108. bool StmtColInvalid;
  15109. unsigned StmtCol =
  15110. SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
  15111. if (StmtColInvalid)
  15112. return;
  15113. if (BodyCol > StmtCol)
  15114. ProbableTypo = true;
  15115. }
  15116. if (ProbableTypo) {
  15117. Diag(NBody->getSemiLoc(), DiagID);
  15118. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  15119. }
  15120. }
  15121. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  15122. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  15123. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  15124. SourceLocation OpLoc) {
  15125. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  15126. return;
  15127. if (inTemplateInstantiation())
  15128. return;
  15129. // Strip parens and casts away.
  15130. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  15131. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  15132. // Check for a call expression
  15133. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  15134. if (!CE || CE->getNumArgs() != 1)
  15135. return;
  15136. // Check for a call to std::move
  15137. if (!CE->isCallToStdMove())
  15138. return;
  15139. // Get argument from std::move
  15140. RHSExpr = CE->getArg(0);
  15141. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  15142. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  15143. // Two DeclRefExpr's, check that the decls are the same.
  15144. if (LHSDeclRef && RHSDeclRef) {
  15145. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  15146. return;
  15147. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  15148. RHSDeclRef->getDecl()->getCanonicalDecl())
  15149. return;
  15150. auto D = Diag(OpLoc, diag::warn_self_move)
  15151. << LHSExpr->getType() << LHSExpr->getSourceRange()
  15152. << RHSExpr->getSourceRange();
  15153. if (const FieldDecl *F =
  15154. getSelfAssignmentClassMemberCandidate(RHSDeclRef->getDecl()))
  15155. D << 1 << F
  15156. << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
  15157. else
  15158. D << 0;
  15159. return;
  15160. }
  15161. // Member variables require a different approach to check for self moves.
  15162. // MemberExpr's are the same if every nested MemberExpr refers to the same
  15163. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  15164. // the base Expr's are CXXThisExpr's.
  15165. const Expr *LHSBase = LHSExpr;
  15166. const Expr *RHSBase = RHSExpr;
  15167. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  15168. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  15169. if (!LHSME || !RHSME)
  15170. return;
  15171. while (LHSME && RHSME) {
  15172. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  15173. RHSME->getMemberDecl()->getCanonicalDecl())
  15174. return;
  15175. LHSBase = LHSME->getBase();
  15176. RHSBase = RHSME->getBase();
  15177. LHSME = dyn_cast<MemberExpr>(LHSBase);
  15178. RHSME = dyn_cast<MemberExpr>(RHSBase);
  15179. }
  15180. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  15181. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  15182. if (LHSDeclRef && RHSDeclRef) {
  15183. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  15184. return;
  15185. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  15186. RHSDeclRef->getDecl()->getCanonicalDecl())
  15187. return;
  15188. Diag(OpLoc, diag::warn_self_move)
  15189. << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
  15190. << RHSExpr->getSourceRange();
  15191. return;
  15192. }
  15193. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  15194. Diag(OpLoc, diag::warn_self_move)
  15195. << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
  15196. << RHSExpr->getSourceRange();
  15197. }
  15198. //===--- Layout compatibility ----------------------------------------------//
  15199. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  15200. /// Check if two enumeration types are layout-compatible.
  15201. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  15202. // C++11 [dcl.enum] p8:
  15203. // Two enumeration types are layout-compatible if they have the same
  15204. // underlying type.
  15205. return ED1->isComplete() && ED2->isComplete() &&
  15206. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  15207. }
  15208. /// Check if two fields are layout-compatible.
  15209. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  15210. FieldDecl *Field2) {
  15211. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  15212. return false;
  15213. if (Field1->isBitField() != Field2->isBitField())
  15214. return false;
  15215. if (Field1->isBitField()) {
  15216. // Make sure that the bit-fields are the same length.
  15217. unsigned Bits1 = Field1->getBitWidthValue(C);
  15218. unsigned Bits2 = Field2->getBitWidthValue(C);
  15219. if (Bits1 != Bits2)
  15220. return false;
  15221. }
  15222. return true;
  15223. }
  15224. /// Check if two standard-layout structs are layout-compatible.
  15225. /// (C++11 [class.mem] p17)
  15226. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  15227. RecordDecl *RD2) {
  15228. // If both records are C++ classes, check that base classes match.
  15229. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  15230. // If one of records is a CXXRecordDecl we are in C++ mode,
  15231. // thus the other one is a CXXRecordDecl, too.
  15232. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  15233. // Check number of base classes.
  15234. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  15235. return false;
  15236. // Check the base classes.
  15237. for (CXXRecordDecl::base_class_const_iterator
  15238. Base1 = D1CXX->bases_begin(),
  15239. BaseEnd1 = D1CXX->bases_end(),
  15240. Base2 = D2CXX->bases_begin();
  15241. Base1 != BaseEnd1;
  15242. ++Base1, ++Base2) {
  15243. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  15244. return false;
  15245. }
  15246. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  15247. // If only RD2 is a C++ class, it should have zero base classes.
  15248. if (D2CXX->getNumBases() > 0)
  15249. return false;
  15250. }
  15251. // Check the fields.
  15252. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  15253. Field2End = RD2->field_end(),
  15254. Field1 = RD1->field_begin(),
  15255. Field1End = RD1->field_end();
  15256. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  15257. if (!isLayoutCompatible(C, *Field1, *Field2))
  15258. return false;
  15259. }
  15260. if (Field1 != Field1End || Field2 != Field2End)
  15261. return false;
  15262. return true;
  15263. }
  15264. /// Check if two standard-layout unions are layout-compatible.
  15265. /// (C++11 [class.mem] p18)
  15266. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  15267. RecordDecl *RD2) {
  15268. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  15269. for (auto *Field2 : RD2->fields())
  15270. UnmatchedFields.insert(Field2);
  15271. for (auto *Field1 : RD1->fields()) {
  15272. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  15273. I = UnmatchedFields.begin(),
  15274. E = UnmatchedFields.end();
  15275. for ( ; I != E; ++I) {
  15276. if (isLayoutCompatible(C, Field1, *I)) {
  15277. bool Result = UnmatchedFields.erase(*I);
  15278. (void) Result;
  15279. assert(Result);
  15280. break;
  15281. }
  15282. }
  15283. if (I == E)
  15284. return false;
  15285. }
  15286. return UnmatchedFields.empty();
  15287. }
  15288. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  15289. RecordDecl *RD2) {
  15290. if (RD1->isUnion() != RD2->isUnion())
  15291. return false;
  15292. if (RD1->isUnion())
  15293. return isLayoutCompatibleUnion(C, RD1, RD2);
  15294. else
  15295. return isLayoutCompatibleStruct(C, RD1, RD2);
  15296. }
  15297. /// Check if two types are layout-compatible in C++11 sense.
  15298. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  15299. if (T1.isNull() || T2.isNull())
  15300. return false;
  15301. // C++11 [basic.types] p11:
  15302. // If two types T1 and T2 are the same type, then T1 and T2 are
  15303. // layout-compatible types.
  15304. if (C.hasSameType(T1, T2))
  15305. return true;
  15306. T1 = T1.getCanonicalType().getUnqualifiedType();
  15307. T2 = T2.getCanonicalType().getUnqualifiedType();
  15308. const Type::TypeClass TC1 = T1->getTypeClass();
  15309. const Type::TypeClass TC2 = T2->getTypeClass();
  15310. if (TC1 != TC2)
  15311. return false;
  15312. if (TC1 == Type::Enum) {
  15313. return isLayoutCompatible(C,
  15314. cast<EnumType>(T1)->getDecl(),
  15315. cast<EnumType>(T2)->getDecl());
  15316. } else if (TC1 == Type::Record) {
  15317. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  15318. return false;
  15319. return isLayoutCompatible(C,
  15320. cast<RecordType>(T1)->getDecl(),
  15321. cast<RecordType>(T2)->getDecl());
  15322. }
  15323. return false;
  15324. }
  15325. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  15326. /// Given a type tag expression find the type tag itself.
  15327. ///
  15328. /// \param TypeExpr Type tag expression, as it appears in user's code.
  15329. ///
  15330. /// \param VD Declaration of an identifier that appears in a type tag.
  15331. ///
  15332. /// \param MagicValue Type tag magic value.
  15333. ///
  15334. /// \param isConstantEvaluated whether the evalaution should be performed in
  15335. /// constant context.
  15336. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  15337. const ValueDecl **VD, uint64_t *MagicValue,
  15338. bool isConstantEvaluated) {
  15339. while(true) {
  15340. if (!TypeExpr)
  15341. return false;
  15342. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  15343. switch (TypeExpr->getStmtClass()) {
  15344. case Stmt::UnaryOperatorClass: {
  15345. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  15346. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  15347. TypeExpr = UO->getSubExpr();
  15348. continue;
  15349. }
  15350. return false;
  15351. }
  15352. case Stmt::DeclRefExprClass: {
  15353. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  15354. *VD = DRE->getDecl();
  15355. return true;
  15356. }
  15357. case Stmt::IntegerLiteralClass: {
  15358. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  15359. llvm::APInt MagicValueAPInt = IL->getValue();
  15360. if (MagicValueAPInt.getActiveBits() <= 64) {
  15361. *MagicValue = MagicValueAPInt.getZExtValue();
  15362. return true;
  15363. } else
  15364. return false;
  15365. }
  15366. case Stmt::BinaryConditionalOperatorClass:
  15367. case Stmt::ConditionalOperatorClass: {
  15368. const AbstractConditionalOperator *ACO =
  15369. cast<AbstractConditionalOperator>(TypeExpr);
  15370. bool Result;
  15371. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
  15372. isConstantEvaluated)) {
  15373. if (Result)
  15374. TypeExpr = ACO->getTrueExpr();
  15375. else
  15376. TypeExpr = ACO->getFalseExpr();
  15377. continue;
  15378. }
  15379. return false;
  15380. }
  15381. case Stmt::BinaryOperatorClass: {
  15382. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  15383. if (BO->getOpcode() == BO_Comma) {
  15384. TypeExpr = BO->getRHS();
  15385. continue;
  15386. }
  15387. return false;
  15388. }
  15389. default:
  15390. return false;
  15391. }
  15392. }
  15393. }
  15394. /// Retrieve the C type corresponding to type tag TypeExpr.
  15395. ///
  15396. /// \param TypeExpr Expression that specifies a type tag.
  15397. ///
  15398. /// \param MagicValues Registered magic values.
  15399. ///
  15400. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  15401. /// kind.
  15402. ///
  15403. /// \param TypeInfo Information about the corresponding C type.
  15404. ///
  15405. /// \param isConstantEvaluated whether the evalaution should be performed in
  15406. /// constant context.
  15407. ///
  15408. /// \returns true if the corresponding C type was found.
  15409. static bool GetMatchingCType(
  15410. const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
  15411. const ASTContext &Ctx,
  15412. const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
  15413. *MagicValues,
  15414. bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
  15415. bool isConstantEvaluated) {
  15416. FoundWrongKind = false;
  15417. // Variable declaration that has type_tag_for_datatype attribute.
  15418. const ValueDecl *VD = nullptr;
  15419. uint64_t MagicValue;
  15420. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
  15421. return false;
  15422. if (VD) {
  15423. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  15424. if (I->getArgumentKind() != ArgumentKind) {
  15425. FoundWrongKind = true;
  15426. return false;
  15427. }
  15428. TypeInfo.Type = I->getMatchingCType();
  15429. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  15430. TypeInfo.MustBeNull = I->getMustBeNull();
  15431. return true;
  15432. }
  15433. return false;
  15434. }
  15435. if (!MagicValues)
  15436. return false;
  15437. llvm::DenseMap<Sema::TypeTagMagicValue,
  15438. Sema::TypeTagData>::const_iterator I =
  15439. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  15440. if (I == MagicValues->end())
  15441. return false;
  15442. TypeInfo = I->second;
  15443. return true;
  15444. }
  15445. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  15446. uint64_t MagicValue, QualType Type,
  15447. bool LayoutCompatible,
  15448. bool MustBeNull) {
  15449. if (!TypeTagForDatatypeMagicValues)
  15450. TypeTagForDatatypeMagicValues.reset(
  15451. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  15452. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  15453. (*TypeTagForDatatypeMagicValues)[Magic] =
  15454. TypeTagData(Type, LayoutCompatible, MustBeNull);
  15455. }
  15456. static bool IsSameCharType(QualType T1, QualType T2) {
  15457. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  15458. if (!BT1)
  15459. return false;
  15460. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  15461. if (!BT2)
  15462. return false;
  15463. BuiltinType::Kind T1Kind = BT1->getKind();
  15464. BuiltinType::Kind T2Kind = BT2->getKind();
  15465. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  15466. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  15467. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  15468. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  15469. }
  15470. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  15471. const ArrayRef<const Expr *> ExprArgs,
  15472. SourceLocation CallSiteLoc) {
  15473. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  15474. bool IsPointerAttr = Attr->getIsPointer();
  15475. // Retrieve the argument representing the 'type_tag'.
  15476. unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
  15477. if (TypeTagIdxAST >= ExprArgs.size()) {
  15478. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  15479. << 0 << Attr->getTypeTagIdx().getSourceIndex();
  15480. return;
  15481. }
  15482. const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
  15483. bool FoundWrongKind;
  15484. TypeTagData TypeInfo;
  15485. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  15486. TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
  15487. TypeInfo, isConstantEvaluated())) {
  15488. if (FoundWrongKind)
  15489. Diag(TypeTagExpr->getExprLoc(),
  15490. diag::warn_type_tag_for_datatype_wrong_kind)
  15491. << TypeTagExpr->getSourceRange();
  15492. return;
  15493. }
  15494. // Retrieve the argument representing the 'arg_idx'.
  15495. unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
  15496. if (ArgumentIdxAST >= ExprArgs.size()) {
  15497. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  15498. << 1 << Attr->getArgumentIdx().getSourceIndex();
  15499. return;
  15500. }
  15501. const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
  15502. if (IsPointerAttr) {
  15503. // Skip implicit cast of pointer to `void *' (as a function argument).
  15504. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  15505. if (ICE->getType()->isVoidPointerType() &&
  15506. ICE->getCastKind() == CK_BitCast)
  15507. ArgumentExpr = ICE->getSubExpr();
  15508. }
  15509. QualType ArgumentType = ArgumentExpr->getType();
  15510. // Passing a `void*' pointer shouldn't trigger a warning.
  15511. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  15512. return;
  15513. if (TypeInfo.MustBeNull) {
  15514. // Type tag with matching void type requires a null pointer.
  15515. if (!ArgumentExpr->isNullPointerConstant(Context,
  15516. Expr::NPC_ValueDependentIsNotNull)) {
  15517. Diag(ArgumentExpr->getExprLoc(),
  15518. diag::warn_type_safety_null_pointer_required)
  15519. << ArgumentKind->getName()
  15520. << ArgumentExpr->getSourceRange()
  15521. << TypeTagExpr->getSourceRange();
  15522. }
  15523. return;
  15524. }
  15525. QualType RequiredType = TypeInfo.Type;
  15526. if (IsPointerAttr)
  15527. RequiredType = Context.getPointerType(RequiredType);
  15528. bool mismatch = false;
  15529. if (!TypeInfo.LayoutCompatible) {
  15530. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  15531. // C++11 [basic.fundamental] p1:
  15532. // Plain char, signed char, and unsigned char are three distinct types.
  15533. //
  15534. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  15535. // char' depending on the current char signedness mode.
  15536. if (mismatch)
  15537. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  15538. RequiredType->getPointeeType())) ||
  15539. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  15540. mismatch = false;
  15541. } else
  15542. if (IsPointerAttr)
  15543. mismatch = !isLayoutCompatible(Context,
  15544. ArgumentType->getPointeeType(),
  15545. RequiredType->getPointeeType());
  15546. else
  15547. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  15548. if (mismatch)
  15549. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  15550. << ArgumentType << ArgumentKind
  15551. << TypeInfo.LayoutCompatible << RequiredType
  15552. << ArgumentExpr->getSourceRange()
  15553. << TypeTagExpr->getSourceRange();
  15554. }
  15555. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  15556. CharUnits Alignment) {
  15557. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  15558. }
  15559. void Sema::DiagnoseMisalignedMembers() {
  15560. for (MisalignedMember &m : MisalignedMembers) {
  15561. const NamedDecl *ND = m.RD;
  15562. if (ND->getName().empty()) {
  15563. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  15564. ND = TD;
  15565. }
  15566. Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
  15567. << m.MD << ND << m.E->getSourceRange();
  15568. }
  15569. MisalignedMembers.clear();
  15570. }
  15571. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  15572. E = E->IgnoreParens();
  15573. if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
  15574. return;
  15575. if (isa<UnaryOperator>(E) &&
  15576. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  15577. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  15578. if (isa<MemberExpr>(Op)) {
  15579. auto *MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
  15580. if (MA != MisalignedMembers.end() &&
  15581. (T->isDependentType() || T->isIntegerType() ||
  15582. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  15583. Context.getTypeAlignInChars(
  15584. T->getPointeeType()) <= MA->Alignment))))
  15585. MisalignedMembers.erase(MA);
  15586. }
  15587. }
  15588. }
  15589. void Sema::RefersToMemberWithReducedAlignment(
  15590. Expr *E,
  15591. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  15592. Action) {
  15593. const auto *ME = dyn_cast<MemberExpr>(E);
  15594. if (!ME)
  15595. return;
  15596. // No need to check expressions with an __unaligned-qualified type.
  15597. if (E->getType().getQualifiers().hasUnaligned())
  15598. return;
  15599. // For a chain of MemberExpr like "a.b.c.d" this list
  15600. // will keep FieldDecl's like [d, c, b].
  15601. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  15602. const MemberExpr *TopME = nullptr;
  15603. bool AnyIsPacked = false;
  15604. do {
  15605. QualType BaseType = ME->getBase()->getType();
  15606. if (BaseType->isDependentType())
  15607. return;
  15608. if (ME->isArrow())
  15609. BaseType = BaseType->getPointeeType();
  15610. RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
  15611. if (RD->isInvalidDecl())
  15612. return;
  15613. ValueDecl *MD = ME->getMemberDecl();
  15614. auto *FD = dyn_cast<FieldDecl>(MD);
  15615. // We do not care about non-data members.
  15616. if (!FD || FD->isInvalidDecl())
  15617. return;
  15618. AnyIsPacked =
  15619. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  15620. ReverseMemberChain.push_back(FD);
  15621. TopME = ME;
  15622. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  15623. } while (ME);
  15624. assert(TopME && "We did not compute a topmost MemberExpr!");
  15625. // Not the scope of this diagnostic.
  15626. if (!AnyIsPacked)
  15627. return;
  15628. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  15629. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  15630. // TODO: The innermost base of the member expression may be too complicated.
  15631. // For now, just disregard these cases. This is left for future
  15632. // improvement.
  15633. if (!DRE && !isa<CXXThisExpr>(TopBase))
  15634. return;
  15635. // Alignment expected by the whole expression.
  15636. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  15637. // No need to do anything else with this case.
  15638. if (ExpectedAlignment.isOne())
  15639. return;
  15640. // Synthesize offset of the whole access.
  15641. CharUnits Offset;
  15642. for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
  15643. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
  15644. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  15645. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  15646. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  15647. // The base expression of the innermost MemberExpr may give
  15648. // stronger guarantees than the class containing the member.
  15649. if (DRE && !TopME->isArrow()) {
  15650. const ValueDecl *VD = DRE->getDecl();
  15651. if (!VD->getType()->isReferenceType())
  15652. CompleteObjectAlignment =
  15653. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  15654. }
  15655. // Check if the synthesized offset fulfills the alignment.
  15656. if (Offset % ExpectedAlignment != 0 ||
  15657. // It may fulfill the offset it but the effective alignment may still be
  15658. // lower than the expected expression alignment.
  15659. CompleteObjectAlignment < ExpectedAlignment) {
  15660. // If this happens, we want to determine a sensible culprit of this.
  15661. // Intuitively, watching the chain of member expressions from right to
  15662. // left, we start with the required alignment (as required by the field
  15663. // type) but some packed attribute in that chain has reduced the alignment.
  15664. // It may happen that another packed structure increases it again. But if
  15665. // we are here such increase has not been enough. So pointing the first
  15666. // FieldDecl that either is packed or else its RecordDecl is,
  15667. // seems reasonable.
  15668. FieldDecl *FD = nullptr;
  15669. CharUnits Alignment;
  15670. for (FieldDecl *FDI : ReverseMemberChain) {
  15671. if (FDI->hasAttr<PackedAttr>() ||
  15672. FDI->getParent()->hasAttr<PackedAttr>()) {
  15673. FD = FDI;
  15674. Alignment = std::min(
  15675. Context.getTypeAlignInChars(FD->getType()),
  15676. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  15677. break;
  15678. }
  15679. }
  15680. assert(FD && "We did not find a packed FieldDecl!");
  15681. Action(E, FD->getParent(), FD, Alignment);
  15682. }
  15683. }
  15684. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  15685. using namespace std::placeholders;
  15686. RefersToMemberWithReducedAlignment(
  15687. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  15688. _2, _3, _4));
  15689. }
  15690. bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
  15691. if (checkArgCount(*this, TheCall, 1))
  15692. return true;
  15693. ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
  15694. if (A.isInvalid())
  15695. return true;
  15696. TheCall->setArg(0, A.get());
  15697. QualType TyA = A.get()->getType();
  15698. if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
  15699. return true;
  15700. TheCall->setType(TyA);
  15701. return false;
  15702. }
  15703. bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
  15704. if (checkArgCount(*this, TheCall, 2))
  15705. return true;
  15706. ExprResult A = TheCall->getArg(0);
  15707. ExprResult B = TheCall->getArg(1);
  15708. // Do standard promotions between the two arguments, returning their common
  15709. // type.
  15710. QualType Res =
  15711. UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
  15712. if (A.isInvalid() || B.isInvalid())
  15713. return true;
  15714. QualType TyA = A.get()->getType();
  15715. QualType TyB = B.get()->getType();
  15716. if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
  15717. return Diag(A.get()->getBeginLoc(),
  15718. diag::err_typecheck_call_different_arg_types)
  15719. << TyA << TyB;
  15720. if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
  15721. return true;
  15722. TheCall->setArg(0, A.get());
  15723. TheCall->setArg(1, B.get());
  15724. TheCall->setType(Res);
  15725. return false;
  15726. }
  15727. bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
  15728. if (checkArgCount(*this, TheCall, 1))
  15729. return true;
  15730. ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
  15731. if (A.isInvalid())
  15732. return true;
  15733. TheCall->setArg(0, A.get());
  15734. return false;
  15735. }
  15736. ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
  15737. ExprResult CallResult) {
  15738. if (checkArgCount(*this, TheCall, 1))
  15739. return ExprError();
  15740. ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
  15741. if (MatrixArg.isInvalid())
  15742. return MatrixArg;
  15743. Expr *Matrix = MatrixArg.get();
  15744. auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
  15745. if (!MType) {
  15746. Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  15747. << 1 << /* matrix ty*/ 1 << Matrix->getType();
  15748. return ExprError();
  15749. }
  15750. // Create returned matrix type by swapping rows and columns of the argument
  15751. // matrix type.
  15752. QualType ResultType = Context.getConstantMatrixType(
  15753. MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
  15754. // Change the return type to the type of the returned matrix.
  15755. TheCall->setType(ResultType);
  15756. // Update call argument to use the possibly converted matrix argument.
  15757. TheCall->setArg(0, Matrix);
  15758. return CallResult;
  15759. }
  15760. // Get and verify the matrix dimensions.
  15761. static std::optional<unsigned>
  15762. getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
  15763. SourceLocation ErrorPos;
  15764. std::optional<llvm::APSInt> Value =
  15765. Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
  15766. if (!Value) {
  15767. S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
  15768. << Name;
  15769. return {};
  15770. }
  15771. uint64_t Dim = Value->getZExtValue();
  15772. if (!ConstantMatrixType::isDimensionValid(Dim)) {
  15773. S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
  15774. << Name << ConstantMatrixType::getMaxElementsPerDimension();
  15775. return {};
  15776. }
  15777. return Dim;
  15778. }
  15779. ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
  15780. ExprResult CallResult) {
  15781. if (!getLangOpts().MatrixTypes) {
  15782. Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
  15783. return ExprError();
  15784. }
  15785. if (checkArgCount(*this, TheCall, 4))
  15786. return ExprError();
  15787. unsigned PtrArgIdx = 0;
  15788. Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
  15789. Expr *RowsExpr = TheCall->getArg(1);
  15790. Expr *ColumnsExpr = TheCall->getArg(2);
  15791. Expr *StrideExpr = TheCall->getArg(3);
  15792. bool ArgError = false;
  15793. // Check pointer argument.
  15794. {
  15795. ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
  15796. if (PtrConv.isInvalid())
  15797. return PtrConv;
  15798. PtrExpr = PtrConv.get();
  15799. TheCall->setArg(0, PtrExpr);
  15800. if (PtrExpr->isTypeDependent()) {
  15801. TheCall->setType(Context.DependentTy);
  15802. return TheCall;
  15803. }
  15804. }
  15805. auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
  15806. QualType ElementTy;
  15807. if (!PtrTy) {
  15808. Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  15809. << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
  15810. ArgError = true;
  15811. } else {
  15812. ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
  15813. if (!ConstantMatrixType::isValidElementType(ElementTy)) {
  15814. Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  15815. << PtrArgIdx + 1 << /* pointer to element ty*/ 2
  15816. << PtrExpr->getType();
  15817. ArgError = true;
  15818. }
  15819. }
  15820. // Apply default Lvalue conversions and convert the expression to size_t.
  15821. auto ApplyArgumentConversions = [this](Expr *E) {
  15822. ExprResult Conv = DefaultLvalueConversion(E);
  15823. if (Conv.isInvalid())
  15824. return Conv;
  15825. return tryConvertExprToType(Conv.get(), Context.getSizeType());
  15826. };
  15827. // Apply conversion to row and column expressions.
  15828. ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
  15829. if (!RowsConv.isInvalid()) {
  15830. RowsExpr = RowsConv.get();
  15831. TheCall->setArg(1, RowsExpr);
  15832. } else
  15833. RowsExpr = nullptr;
  15834. ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
  15835. if (!ColumnsConv.isInvalid()) {
  15836. ColumnsExpr = ColumnsConv.get();
  15837. TheCall->setArg(2, ColumnsExpr);
  15838. } else
  15839. ColumnsExpr = nullptr;
  15840. // If any part of the result matrix type is still pending, just use
  15841. // Context.DependentTy, until all parts are resolved.
  15842. if ((RowsExpr && RowsExpr->isTypeDependent()) ||
  15843. (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
  15844. TheCall->setType(Context.DependentTy);
  15845. return CallResult;
  15846. }
  15847. // Check row and column dimensions.
  15848. std::optional<unsigned> MaybeRows;
  15849. if (RowsExpr)
  15850. MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
  15851. std::optional<unsigned> MaybeColumns;
  15852. if (ColumnsExpr)
  15853. MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
  15854. // Check stride argument.
  15855. ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
  15856. if (StrideConv.isInvalid())
  15857. return ExprError();
  15858. StrideExpr = StrideConv.get();
  15859. TheCall->setArg(3, StrideExpr);
  15860. if (MaybeRows) {
  15861. if (std::optional<llvm::APSInt> Value =
  15862. StrideExpr->getIntegerConstantExpr(Context)) {
  15863. uint64_t Stride = Value->getZExtValue();
  15864. if (Stride < *MaybeRows) {
  15865. Diag(StrideExpr->getBeginLoc(),
  15866. diag::err_builtin_matrix_stride_too_small);
  15867. ArgError = true;
  15868. }
  15869. }
  15870. }
  15871. if (ArgError || !MaybeRows || !MaybeColumns)
  15872. return ExprError();
  15873. TheCall->setType(
  15874. Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
  15875. return CallResult;
  15876. }
  15877. ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
  15878. ExprResult CallResult) {
  15879. if (checkArgCount(*this, TheCall, 3))
  15880. return ExprError();
  15881. unsigned PtrArgIdx = 1;
  15882. Expr *MatrixExpr = TheCall->getArg(0);
  15883. Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
  15884. Expr *StrideExpr = TheCall->getArg(2);
  15885. bool ArgError = false;
  15886. {
  15887. ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
  15888. if (MatrixConv.isInvalid())
  15889. return MatrixConv;
  15890. MatrixExpr = MatrixConv.get();
  15891. TheCall->setArg(0, MatrixExpr);
  15892. }
  15893. if (MatrixExpr->isTypeDependent()) {
  15894. TheCall->setType(Context.DependentTy);
  15895. return TheCall;
  15896. }
  15897. auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
  15898. if (!MatrixTy) {
  15899. Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  15900. << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
  15901. ArgError = true;
  15902. }
  15903. {
  15904. ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
  15905. if (PtrConv.isInvalid())
  15906. return PtrConv;
  15907. PtrExpr = PtrConv.get();
  15908. TheCall->setArg(1, PtrExpr);
  15909. if (PtrExpr->isTypeDependent()) {
  15910. TheCall->setType(Context.DependentTy);
  15911. return TheCall;
  15912. }
  15913. }
  15914. // Check pointer argument.
  15915. auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
  15916. if (!PtrTy) {
  15917. Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
  15918. << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
  15919. ArgError = true;
  15920. } else {
  15921. QualType ElementTy = PtrTy->getPointeeType();
  15922. if (ElementTy.isConstQualified()) {
  15923. Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
  15924. ArgError = true;
  15925. }
  15926. ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
  15927. if (MatrixTy &&
  15928. !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
  15929. Diag(PtrExpr->getBeginLoc(),
  15930. diag::err_builtin_matrix_pointer_arg_mismatch)
  15931. << ElementTy << MatrixTy->getElementType();
  15932. ArgError = true;
  15933. }
  15934. }
  15935. // Apply default Lvalue conversions and convert the stride expression to
  15936. // size_t.
  15937. {
  15938. ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
  15939. if (StrideConv.isInvalid())
  15940. return StrideConv;
  15941. StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
  15942. if (StrideConv.isInvalid())
  15943. return StrideConv;
  15944. StrideExpr = StrideConv.get();
  15945. TheCall->setArg(2, StrideExpr);
  15946. }
  15947. // Check stride argument.
  15948. if (MatrixTy) {
  15949. if (std::optional<llvm::APSInt> Value =
  15950. StrideExpr->getIntegerConstantExpr(Context)) {
  15951. uint64_t Stride = Value->getZExtValue();
  15952. if (Stride < MatrixTy->getNumRows()) {
  15953. Diag(StrideExpr->getBeginLoc(),
  15954. diag::err_builtin_matrix_stride_too_small);
  15955. ArgError = true;
  15956. }
  15957. }
  15958. }
  15959. if (ArgError)
  15960. return ExprError();
  15961. return CallResult;
  15962. }
  15963. /// \brief Enforce the bounds of a TCB
  15964. /// CheckTCBEnforcement - Enforces that every function in a named TCB only
  15965. /// directly calls other functions in the same TCB as marked by the enforce_tcb
  15966. /// and enforce_tcb_leaf attributes.
  15967. void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
  15968. const NamedDecl *Callee) {
  15969. const NamedDecl *Caller = getCurFunctionOrMethodDecl();
  15970. if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
  15971. return;
  15972. // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
  15973. // all TCBs the callee is a part of.
  15974. llvm::StringSet<> CalleeTCBs;
  15975. for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
  15976. CalleeTCBs.insert(A->getTCBName());
  15977. for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
  15978. CalleeTCBs.insert(A->getTCBName());
  15979. // Go through the TCBs the caller is a part of and emit warnings if Caller
  15980. // is in a TCB that the Callee is not.
  15981. for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
  15982. StringRef CallerTCB = A->getTCBName();
  15983. if (CalleeTCBs.count(CallerTCB) == 0) {
  15984. this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
  15985. << Callee << CallerTCB;
  15986. }
  15987. }
  15988. }